Creates a new or returns an existing term for the target vocabulary.
764711
protected function getTerm($name, Row $row, $vocabulary) {
    // Attempt to fetch an existing term.
    $properties = [];
    if (!empty($name)) {
      $properties['name'] = $name;
    }
    $vocabularies = taxonomy_vocabulary_get_names();
    if (isset($vocabularies[$vocabulary])) {
      $properties['vid'] = $vocabulary;
    }
    else {
      // Return NULL when filtering by a non-existing vocabulary.
      return NULL;
    }

    $terms = \Drupal::getContainer()->get('entity.manager')->getStorage('taxonomy_term')->loadByProperties($properties);
    $term = reset($terms);
    if (!empty($term)) {
      if ($row->getDestinationProperty('langcode') && $row->getDestinationProperty('langcode') != LanguageInterface::LANGCODE_NOT_SPECIFIED) {
        if (!$term->hasTranslation($row->getDestinationProperty('langcode'))) {
          $term->addTranslation($row->getDestinationProperty('langcode'));
        }
        $term = $term->getTranslation($row->getDestinationProperty('langcode'));
      }
      return $term;
    }
    // Fallback, create a new term.
    $term = Term::create($properties);
    if ($row->getDestinationProperty('langcode')) {
      $term->langcode = $row->getDestinationProperty('langcode');
    }
    return $term;
  }
460352
private OntologyTermSynonym createSynonym(String synonym) {
    OntologyTermSynonym entity = ontologyTermSynonymFactory.create();
    entity.setId(idGenerator.generateId());
    entity.setOntologyTermSynonym(synonym);
    synonymRepository.add(entity);
    return entity;
  }
1028945
def expand(self, name=None, target=None, **kwargs):
    
    if name is None:
      raise TargetDefinitionException('{}:?'.format(self._parse_context.rel_path, name),
                                      'The alias() must have a name!')
    if target is None:
      raise TargetDefinitionException('{}:{}'.format(self._parse_context.rel_path, name),
                                      'The alias() must have a "target" parameter.')
    self._parse_context.create_object(
      AliasTarget,
      type_alias='alias',
      name=name,
      dependencies=[target] if target else [],
      **kwargs
    )
608224
public function create(
        $vocabularies,
        $limit,
        $nameWords
    ) {
        $siteVocabularies = $this->drupalApi->getVocabularies();
        $terms = [];
        for ($i = 0; $i < $limit; $i++) {
            try {
                $vocabulary = $vocabularies[array_rand($vocabularies)];
                $term = $this->entityTypeManager->getStorage('taxonomy_term')->create(
                    [
                        'vid' => $vocabulary,
                        'name' => $this->getRandom()->sentences(mt_rand(1, $nameWords), true),
                        'description' => [
                            'value' => $this->getRandom()->sentences(mt_rand(1, $nameWords)),
                            'format' => 'full_html',
                        ],
                        'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
                    ]
                );
                $term->save();
                $terms['success'][] = [
                    'tid' => $term->id(),
                    'vocabulary' => $siteVocabularies[$vocabulary],
                    'name' => $term->getName(),
                ];
            } catch (\Exception $error) {
                $terms['error'][] = $error->getMessage();
            }
        }

        return $terms;
    }
1260246
private void createTermDefinition(Map<String, Object> context, String term,
            Map<String, Boolean> defined) throws JsonLdError {
        if (defined.containsKey(term)) {
            if (Boolean.TRUE.equals(defined.get(term))) {
                return;
            }
            throw new JsonLdError(Error.CYCLIC_IRI_MAPPING, term);
        }

        defined.put(term, false);

        if (JsonLdUtils.isKeyword(term)
                && !(options.getAllowContainerSetOnType() && JsonLdConsts.TYPE.equals(term)
                        && !(context.get(term)).toString().contains(JsonLdConsts.ID))) {
            throw new JsonLdError(Error.KEYWORD_REDEFINITION, term);
        }

        this.termDefinitions.remove(term);
        Object value = context.get(term);
        if (value == null || (value instanceof Map
                && ((Map<String, Object>) value).containsKey(JsonLdConsts.ID)
                && ((Map<String, Object>) value).get(JsonLdConsts.ID) == null)) {
            this.termDefinitions.put(term, null);
            defined.put(term, true);
            return;
        }

        if (value instanceof String) {
            value = newMap(JsonLdConsts.ID, value);
        }

        if (!(value instanceof Map)) {
            throw new JsonLdError(Error.INVALID_TERM_DEFINITION, value);
        }

        // casting the value so it doesn't have to be done below everytime
        final Map<String, Object> val = (Map<String, Object>) value;

        // 9) create a new term definition
        final Map<String, Object> definition = newMap();

        // 10)
        if (val.containsKey(JsonLdConsts.TYPE)) {
            if (!(val.get(JsonLdConsts.TYPE) instanceof String)) {
                throw new JsonLdError(Error.INVALID_TYPE_MAPPING, val.get(JsonLdConsts.TYPE));
            }
            String type = (String) val.get(JsonLdConsts.TYPE);
            try {
                type = this.expandIri((String) val.get(JsonLdConsts.TYPE), false, true, context,
                        defined);
            } catch (final JsonLdError error) {
                if (error.getType() != Error.INVALID_IRI_MAPPING) {
                    throw error;
                }
                throw new JsonLdError(Error.INVALID_TYPE_MAPPING, type, error);
            }
            // TODO: fix check for absoluteIri (blank nodes shouldn't count, at
            // least not here!)
            if (JsonLdConsts.ID.equals(type) || JsonLdConsts.VOCAB.equals(type)
                    || (!type.startsWith(JsonLdConsts.BLANK_NODE_PREFIX)
                            && JsonLdUtils.isAbsoluteIri(type))) {
                definition.put(JsonLdConsts.TYPE, type);
            } else {
                throw new JsonLdError(Error.INVALID_TYPE_MAPPING, type);
            }
        }

        // 11)
        if (val.containsKey(JsonLdConsts.REVERSE)) {
            if (val.containsKey(JsonLdConsts.ID)) {
                throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY, val);
            }
            if (!(val.get(JsonLdConsts.REVERSE) instanceof String)) {
                throw new JsonLdError(Error.INVALID_IRI_MAPPING,
                        "Expected String for @reverse value. got "
                                + (val.get(JsonLdConsts.REVERSE) == null ? "null"
                                        : val.get(JsonLdConsts.REVERSE).getClass()));
            }
            final String reverse = this.expandIri((String) val.get(JsonLdConsts.REVERSE), false,
                    true, context, defined);
            if (!JsonLdUtils.isAbsoluteIri(reverse)) {
                throw new JsonLdError(Error.INVALID_IRI_MAPPING,
                        "Non-absolute @reverse IRI: " + reverse);
            }
            definition.put(JsonLdConsts.ID, reverse);
            if (val.containsKey(JsonLdConsts.CONTAINER)) {
                final String container = (String) val.get(JsonLdConsts.CONTAINER);
                if (container == null || JsonLdConsts.SET.equals(container)
                        || JsonLdConsts.INDEX.equals(container)) {
                    definition.put(JsonLdConsts.CONTAINER, container);
                } else {
                    throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY,
                            "reverse properties only support set- and index-containers");
                }
            }
            definition.put(JsonLdConsts.REVERSE, true);
            this.termDefinitions.put(term, definition);
            defined.put(term, true);
            return;
        }

        // 12)
        definition.put(JsonLdConsts.REVERSE, false);

        // 13)
        if (val.get(JsonLdConsts.ID) != null && !term.equals(val.get(JsonLdConsts.ID))) {
            if (!(val.get(JsonLdConsts.ID) instanceof String)) {
                throw new JsonLdError(Error.INVALID_IRI_MAPPING,
                        "expected value of @id to be a string");
            }

            final String res = this.expandIri((String) val.get(JsonLdConsts.ID), false, true,
                    context, defined);
            if (JsonLdUtils.isKeyword(res) || JsonLdUtils.isAbsoluteIri(res)) {
                if (JsonLdConsts.CONTEXT.equals(res)) {
                    throw new JsonLdError(Error.INVALID_KEYWORD_ALIAS, "cannot alias @context");
                }
                definition.put(JsonLdConsts.ID, res);
            } else {
                throw new JsonLdError(Error.INVALID_IRI_MAPPING,
                        "resulting IRI mapping should be a keyword, absolute IRI or blank node");
            }
        }

        // 14)
        else if (term.indexOf(":") >= 0) {
            final int colIndex = term.indexOf(":");
            final String prefix = term.substring(0, colIndex);
            final String suffix = term.substring(colIndex + 1);
            if (context.containsKey(prefix)) {
                this.createTermDefinition(context, prefix, defined);
            }
            if (termDefinitions.containsKey(prefix)) {
                definition.put(JsonLdConsts.ID,
                        ((Map<String, Object>) termDefinitions.get(prefix)).get(JsonLdConsts.ID)
                                + suffix);
            } else {
                definition.put(JsonLdConsts.ID, term);
            }
            // 15)
        } else if (this.containsKey(JsonLdConsts.VOCAB)) {
            definition.put(JsonLdConsts.ID, this.get(JsonLdConsts.VOCAB) + term);
        } else if (!JsonLdConsts.TYPE.equals(term)) {
            throw new JsonLdError(Error.INVALID_IRI_MAPPING,
                    "relative term definition without vocab mapping");
        }

        // 16)
        if (val.containsKey(JsonLdConsts.CONTAINER)) {
            final String container = (String) val.get(JsonLdConsts.CONTAINER);
            if (!JsonLdConsts.LIST.equals(container) && !JsonLdConsts.SET.equals(container)
                    && !JsonLdConsts.INDEX.equals(container)
                    && !JsonLdConsts.LANGUAGE.equals(container)) {
                throw new JsonLdError(Error.INVALID_CONTAINER_MAPPING,
                        "@container must be either @list, @set, @index, or @language");
            }
            definition.put(JsonLdConsts.CONTAINER, container);
            if (JsonLdConsts.TYPE.equals(term)) {
                definition.put(JsonLdConsts.ID, "type");
            }
        }

        // 17)
        if (val.containsKey(JsonLdConsts.LANGUAGE) && !val.containsKey(JsonLdConsts.TYPE)) {
            if (val.get(JsonLdConsts.LANGUAGE) == null
                    || val.get(JsonLdConsts.LANGUAGE) instanceof String) {
                final String language = (String) val.get(JsonLdConsts.LANGUAGE);
                definition.put(JsonLdConsts.LANGUAGE,
                        language != null ? language.toLowerCase() : null);
            } else {
                throw new JsonLdError(Error.INVALID_LANGUAGE_MAPPING,
                        "@language must be a string or null");
            }
        }

        // 18)
        this.termDefinitions.put(term, definition);
        defined.put(term, true);
    }
144437
def copy(self):
        
        new_term = PauliTerm("I", 0, 1.0)  # create new object
        # manually copy all attributes over
        for key in self.__dict__.keys():
            val = self.__dict__[key]
            if isinstance(val, (dict, list, set)):  # mutable types
                new_term.__dict__[key] = copy.copy(val)
            else:  # immutable types
                new_term.__dict__[key] = val

        return new_term
1111121
def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False):
    """"""
    # We assume that vocab file is present in data_dir directory where the
    # data generated will be stored.
    vocab_filepath = os.path.join(data_dir, self.vocab_filename)
    encoder = text_encoder.SubwordTextEncoder(vocab_filepath)
    return encoder
189251
public function termCreate($term)
    {
        $this->dispatchHooks('BeforeTermCreateScope', $term);
        $this->parseEntityFields('taxonomy_term', $term);
        $saved = $this->getDriver()->createTerm($term);
        $this->dispatchHooks('AfterTermCreateScope', $saved);
        $this->terms[] = $saved;
        return $saved;
    }
1112173
public function actionCreate()
    {
        $model = new TaxonomyVocabulary(['scenario' => 'admin-create']);
        $statusArray = TaxonomyVocabulary::statusLabels();

        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {
                if ($model->save(false)) {
                    return $this->redirect(['update', 'id' => $model->id]);
                } else {
                    Yii::$app->session->setFlash('danger', Manager::t('admin', 'Failed to create a vocabulary'));
                    return $this->refresh();
                }
            } elseif (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }

        return $this->render('create', [
            'model' => $model,
            'statusArray' => $statusArray
        ]);
    }
349259
def add(self, word):
        """"""
        if not word or word.strip() == '':
            return
        self.words[word]=word
670470
def add_term(self,term_obj):
        
        if term_obj.get_id() in self.idx:
            raise ValueError("Term with id {} already exists!"
                             .format(term_obj.get_id()))
        self.node.append(term_obj.get_node())
        self.idx[term_obj.get_id()] = term_obj
823307
def generate_words(numberofwords, wordlist, secure=None):
    """"""
    if not secure:
        chooser = random.choice
    else:
        chooser = random.SystemRandom().choice
    return [chooser(wordlist) for _ in range(numberofwords)]
1228515
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab':
        ""
        freq = Counter(p for o in tokens for p in o)
        itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq]
        for o in reversed(defaults.text_spec_tok):
            if o in itos: itos.remove(o)
            itos.insert(0, o)
        return cls(itos)
60668
public void buildVocab() {


        val constructor = new VocabConstructor.Builder<T>().addSource(iterator, minWordFrequency)
                        .setTargetVocabCache(vocab).fetchLabels(trainSequenceVectors).setStopWords(stopWords)
                        .enableScavenger(enableScavenger).setEntriesLimit(vocabLimit)
                        .allowParallelTokenization(configuration.isAllowParallelTokenization())
                        .setUnk(useUnknown && unknownElement != null ? unknownElement : null).build();

        if (existingModel != null && lookupTable instanceof InMemoryLookupTable
                        && existingModel.lookupTable() instanceof InMemoryLookupTable) {
            log.info("Merging existing vocabulary into the current one...");
            /*
                if we have existing model defined, we're forced to fetch labels only.
                the rest of vocabulary & weights should be transferred from existing model
             */

            constructor.buildMergedVocabulary(existingModel, true);

            /*
                Now we have vocab transferred, and we should transfer syn0 values into lookup table
             */
            ((InMemoryLookupTable<VocabWord>) lookupTable)
                            .consume((InMemoryLookupTable<VocabWord>) existingModel.lookupTable());
        } else {
            log.info("Starting vocabulary building...");
            // if we don't have existing model defined, we just build vocabulary


            constructor.buildJointVocabulary(false, true);

            /*
            if (useUnknown && unknownElement != null && !vocab.containsWord(unknownElement.getLabel())) {
                log.info("Adding UNK element...");
                unknownElement.setSpecial(true);
                unknownElement.markAsLabel(false);
                unknownElement.setIndex(vocab.numWords());
                vocab.addToken(unknownElement);
            }
            */


            // check for malformed inputs. if numWords/numSentences ratio is huge, then user is passing something weird
            if (vocab.numWords() / constructor.getNumberOfSequences() > 1000) {
                log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                log.warn("!                                                                                       !");
                log.warn("! Your input looks malformed: number of sentences is too low, model accuracy may suffer !");
                log.warn("!                                                                                       !");
                log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            }
        }


    }
223593
def new(cls, package):
        """"""
        partname = package.next_partname("/word/footer%d.xml")
        content_type = CT.WML_FOOTER
        element = parse_xml(cls._default_footer_xml())
        return cls(partname, content_type, element, package)
965691
def get_or_generate_vocabulary(data_dir,
                               tmp_dir,
                               data_prefix,
                               max_page_size_exp,
                               approx_vocab_size=32768,
                               strip=True):
  
  num_pages_for_vocab_generation = approx_vocab_size // 3
  vocab_file = vocab_filename(approx_vocab_size, strip)

  def my_generator(data_prefix):
    """Line generator for vocab."""
    count = 0
    for page in corpus_page_generator(
        all_corpus_files(data_prefix)[::-1], tmp_dir, max_page_size_exp):
      revisions = page["revisions"]
      if revisions:
        text = get_text(revisions[-1], strip=strip)
        yield text
        count += 1
        if count % 100 == 0:
          tf.logging.info("reading pages for vocab %d" % count)
        if count > num_pages_for_vocab_generation:
          break

  return generator_utils.get_or_generate_vocab_inner(data_dir, vocab_file,
                                                     approx_vocab_size,
                                                     my_generator(data_prefix))
429778
def load_or_create_vocab(data: str, vocab_path: Optional[str], num_words: int, word_min_count: int,
                         pad_to_multiple_of: Optional[int] = None) -> Vocab:
    
    if vocab_path is None:
        return build_from_paths(paths=[data], num_words=num_words, min_count=word_min_count,
                                pad_to_multiple_of=pad_to_multiple_of)
    else:
        return vocab_from_json(vocab_path)