Processes gathered elements coming from the legacy criterion strategy

Legacy criterion strategy is converted to a rubric with single rubric item
and the layout set to 'list'.
433959
protected function convert_legacy_criterion_elements() {

        $this->write_xml('workshopform_rubric_config', array('layout' => 'list'));

        $firstelement = reset($this->elements);
        if ($firstelement === false) {
            // no elements defined in moodle.xml
            return;
        }

        // write the xml describing the artificial single rubric item
        $this->xmlwriter->begin_tag('workshopform_rubric_dimension', array('id' => $firstelement['id']));
        $this->xmlwriter->full_tag('sort', 1);
        $this->xmlwriter->full_tag('description', trim(get_string('dimensionnumber', 'workshopform_rubric', '')));
        $this->xmlwriter->full_tag('descriptionformat', FORMAT_HTML);

        foreach ($this->elements as $element) {
            $this->write_xml('workshopform_rubric_level', array(
                'id'               => $element['id'],
                'grade'            => $element['maxscore'],
                'definition'       => $element['description'],
                'definitionformat' => FORMAT_HTML
            ), array('/workshopform_rubric_level/id'));
        }

        $this->xmlwriter->end_tag('workshopform_rubric_dimension');
    }
454914
def prepare_components(self):
        
        # Register the components based on user option
        # First, tabular report
        generated_components = deepcopy(all_default_report_components)
        # Rohmat: I need to define the definitions here, I can't get
        # the definition using definition helper method.
        component_definitions = {
            impact_report_pdf_component['key']:
                impact_report_pdf_component,
            action_checklist_pdf_component['key']:
                action_checklist_pdf_component,
            analysis_provenance_details_pdf_component['key']:
                analysis_provenance_details_pdf_component,
            infographic_report['key']: infographic_report
        }
        duplicated_report_metadata = None
        for key, checkbox in list(self.all_checkboxes.items()):
            if not checkbox.isChecked():
                component = component_definitions[key]
                if component in generated_components:
                    generated_components.remove(component)
                    continue

                if self.is_multi_exposure:
                    impact_report_metadata = (
                        standard_multi_exposure_impact_report_metadata_pdf)
                else:
                    impact_report_metadata = (
                        standard_impact_report_metadata_pdf)

                if component in impact_report_metadata['components']:
                    if not duplicated_report_metadata:
                        duplicated_report_metadata = deepcopy(
                            impact_report_metadata)
                    duplicated_report_metadata['components'].remove(
                        component)
                    if impact_report_metadata in generated_components:
                        generated_components.remove(
                            impact_report_metadata)
                        generated_components.append(
                            duplicated_report_metadata)

        # Second, custom and map report
        # Get selected template path to use
        selected_template_path = None
        if self.search_directory_radio.isChecked():
            selected_template_path = self.template_combo.itemData(
                self.template_combo.currentIndex())
        elif self.search_on_disk_radio.isChecked():
            selected_template_path = self.template_path.text()
            if not exists(selected_template_path):
                # noinspection PyCallByClass,PyTypeChecker
                QtWidgets.QMessageBox.warning(
                    self,
                    tr('InaSAFE'),
                    tr(
                        'Please select a valid template before printing. '
                        'The template you choose does not exist.'))

        if map_report in generated_components:
            # if self.no_map_radio.isChecked():
            #     generated_components.remove(map_report)
            if self.default_template_radio.isChecked():
                # make sure map report is there
                generated_components.append(
                    generated_components.pop(
                        generated_components.index(map_report)))
            elif self.override_template_radio.isChecked():
                hazard_type = definition(
                    self.impact_function.provenance['hazard_keywords'][
                        'hazard'])
                exposure_type = definition(
                    self.impact_function.provenance['exposure_keywords'][
                        'exposure'])
                generated_components.remove(map_report)
                generated_components.append(
                    update_template_component(
                        component=map_report,
                        hazard=hazard_type,
                        exposure=exposure_type))
            elif selected_template_path:
                generated_components.remove(map_report)
                generated_components.append(
                    override_component_template(
                        map_report, selected_template_path))

        return generated_components
545815
private function mapReviewAndRatingList($reviewAndRatingDataList)
    {
        $mappedReviewAndRating = new ArrayCollection();

        foreach ($reviewAndRatingDataList as $reviewAndRatingData) {
            $mappedReviewAndRating[] = $this->mapReviewAndRating($reviewAndRatingData);
        }

        return $mappedReviewAndRating;
    }
1372020
def process_form(self, instance, field, form, empty_marker = None,
                     emptyReturnsMarker = False):
        
        bsc = getToolByName(instance, 'bika_setup_catalog')
        default = super(PartitionSetupWidget,self).process_form(
            instance, field, form, empty_marker, emptyReturnsMarker)
        if not default:
            return [], {}
        value = default[0]
        kwargs = len(default) > 1 and default[1] or {}
        newvalue = []
        for v in value:
            v = dict(v)
            if v.get('separate', '') == 'on' and not 'preservation' in v:
                container_uid = v.get('container', [''])[0];
                if container_uid:
                    container = bsc(UID=container_uid)[0].getObject();
                    if container.getPrePreserved():
                        pres = container.getPreservation()
                        if pres:
                            v['preservation'] = [pres.UID()]
            newvalue.append(v)
        return newvalue, kwargs
129271
private void doChangeSelectionInList(int moveBy)
	{
		PlayListEntry [] selected = playList.getSelectedEntries();
		if (selected==null || selected.length == 0)
		{
			playList.setSelectedElement(0);
			doMakeIndexVisible(0);
		}
		else
		{
			int firstIndex = selected[0].getIndexInPlaylist(); 
			int lastIndex = selected[selected.length - 1].getIndexInPlaylist();
			if (moveBy < 0)
			{
				firstIndex += moveBy;
				if (firstIndex<0) firstIndex = 0;
			}
			else
			{
				lastIndex += moveBy;
				if (lastIndex >= playList.size()) lastIndex = playList.size() - 1; 
			}
			playList.setSelectedElements(firstIndex, lastIndex);
			if (moveBy < 0) doMakeIndexVisible(firstIndex); else doMakeIndexVisible(lastIndex);
		}
	}
993333
def _populate_label_legacy_structures():
    
    global DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL
    global label_sizes, label_type_specs

    from brother_ql.labels import FormFactor
    DIE_CUT_LABEL =       FormFactor.DIE_CUT
    ENDLESS_LABEL =       FormFactor.ENDLESS
    ROUND_DIE_CUT_LABEL = FormFactor.ROUND_DIE_CUT

    from brother_ql.labels import LabelsManager
    lm = LabelsManager()
    label_sizes = list(lm.iter_identifiers())
    for label in lm.iter_elements():
        l = {}
        l['name'] = label.name
        l['kind'] = label.form_factor
        l['color'] = label.color
        l['tape_size'] = label.tape_size
        l['dots_total'] = label.dots_total
        l['dots_printable'] = label.dots_printable
        l['right_margin_dots'] = label.offset_r
        l['feed_margin'] = label.feed_margin
        l['restrict_printers'] = label.restricted_to_models
        label_type_specs[label.identifier] = l
441524
public List<WordTag> process(List list) {
    List<IN> featureLabels = new ArrayList<IN>();
    for (Object o : list) {
      CoreLabel wi = new CoreLabel();
      if (o instanceof HasWord) {
        wi.setWord(((HasWord) o).word());
        if (o instanceof HasTag) {
          wi.setTag(((HasTag) o).tag());
        }
      } else {
        wi.setWord(o.toString());
      }
      featureLabels.add((IN) wi);
    }
    List<IN> tagged = classify(featureLabels);
    List<WordTag> out = new ArrayList<WordTag>();
    for (CoreLabel wi : tagged) {
      out.add(new WordTag(wi.word(), wi.get(AnswerAnnotation.class)));
    }
    return out;
  }
263207
def recategorize(self, new_categories):
        '''
        
        '''
        assert len(new_categories) == self.get_num_docs()

        new_category_idx_store = IndexStoreFromList.build(set(new_categories))
        new_y = np.array(new_category_idx_store.getidxstrictbatch(new_categories))

        new_tdm = self._make_new_term_doc_matrix(self._X, self._mX, new_y, self._term_idx_store, new_category_idx_store,
                                                 self._metadata_idx_store, new_y == new_y)
        return new_tdm
1258619
public function process_gradingform_guide_criterion($data) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;
        $data->definitionid = $this->get_new_parentid('grading_definition');

        $newid = $DB->insert_record('gradingform_guide_criteria', $data);
        $this->set_mapping('gradingform_guide_criterion', $oldid, $newid);
    }
262267
public void addStrategy(MappingStrategy strategy)
    {
        if (strategies == null)
        {
            strategies = new ArrayList<>();
        }
        strategies.add(strategy);
    }
1259972
def serialize(self):
        
        lines = []

        for criterion in self.filter_criteria:
            lines.append(criterion.name())
            lines.append(criterion.serialize())

        return '\n'.join(lines)
663054
def parse(options)
      # find the record store, possibly based on the :store option
      store = record_store(options.delete(:store))
      # dispatch the parse call to all known strategies
      Dispatcher.strategy_classes.map{ |klass| klass.parse(@base, store, options) }.flatten.compact.each do |strategy|
        raise "Multiple record cache definitions found for '#{strategy.attribute}' on #{@base.name}" if @strategy_by_attribute[strategy.attribute]
        # and keep track of all strategies
        @strategy_by_attribute[strategy.attribute] = strategy
      end
      # make sure the strategies are ordered again on next call to +ordered_strategies+
      @ordered_strategies = nil
    end
269103
function() {
        var assetKey, newEntry, oldEntry;

        // Reuse existing metadata.
        for ( assetKey in oldAvailableLists ) {
            oldEntry = oldAvailableLists[assetKey];
            newEntry = newAvailableLists[assetKey];
            // List no longer exists. If a stock list, try to convert to
            // imported list if it was selected.
            if ( newEntry === undefined ) {
                µb.removeFilterList(assetKey);
                if ( assetKey.indexOf('://') === -1 ) {
                    customListFromStockList(assetKey);
                }
                continue;
            }
            if ( oldEntry.entryCount !== undefined ) {
                newEntry.entryCount = oldEntry.entryCount;
            }
            if ( oldEntry.entryUsedCount !== undefined ) {
                newEntry.entryUsedCount = oldEntry.entryUsedCount;
            }
            // This may happen if the list name was pulled from the list
            // content.
            // https://github.com/chrisaljoudi/uBlock/issues/982
            // There is no guarantee the title was successfully extracted from
            // the list content.
            if (
                newEntry.title === '' &&
                typeof oldEntry.title === 'string' &&
                oldEntry.title !== ''
            ) {
                newEntry.title = oldEntry.title;
            }
        }

        // Remove unreferenced imported filter lists.
        var dict = new Set(importedListKeys);
        for ( assetKey in newAvailableLists ) {
            newEntry = newAvailableLists[assetKey];
            if ( newEntry.submitter !== 'user' ) { continue; }
            if ( dict.has(assetKey) ) { continue; }
            delete newAvailableLists[assetKey];
            µb.assets.unregisterAssetSource(assetKey);
            µb.removeFilterList(assetKey);
        }
    }
898099
def CreateDefaultPartition(client, ad_group_id):
  
  ad_group_criterion_service = client.GetService('AdGroupCriterionService',
                                                 version='v201809')

  operations = [{
      'operator': 'ADD',
      'operand': {
          'xsi_type': 'BiddableAdGroupCriterion',
          'adGroupId': ad_group_id,
          # Make sure that caseValue and parentCriterionId are left unspecified.
          # This makes this partition as generic as possible to use as a
          # fallback when others don't match.
          'criterion': {
              'xsi_type': 'ProductPartition',
              'partitionType': 'UNIT'
          },
          'biddingStrategyConfiguration': {
              'bids': [{
                  'xsi_type': 'CpcBid',
                  'bid': {
                      'microAmount': 500000
                  }
              }]
          }
      }
  }]

  ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0]

  print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.'
         % (ad_group_criterion['criterion']['id'],
            ad_group_criterion['adGroupId']))
939727
public function transformCriterionGroup(CriterionGroupInterface $criterionGroup)
    {
        $criterionCount = $criterionGroup->count();
        $subQuery = [];

        if ($criterionCount === 1) {
            // Handle simple criterion
            $criterion = $criterionGroup->getCriteria();
            /** @var CriterionInterface $criterionGroup */
            $criterion = array_pop($criterion)[0];

            $subQuery["filtered"] = $this->transformCriterion($criterion);
        } else {
            //Handle multiple criteria

            // 1st, split OR groups
            // This must be transformed with operator priority: AND is prior to OR.

            $splitConditions = [];
            $i = 0;

            foreach ($criterionGroup->getCriteria() as $criterionTuple) {
                /** @var CriterionInterface $criterion */
                list($criterion, $link) = $criterionTuple;
                $splitConditions[$i][] = $criterion;

                if ($link === Link::LINK_OR) {
                    $i++;
                }
            }

            if (count($splitConditions) === 1) {
                // Group without OR
                $subQuery["filtered"] = [
                    "filter" => [],
                ];

                $keyBag = [];

                /** @var CriterionInterface $criterion */
                foreach ($splitConditions[0] as $criterion) {
                    $subQuery["filtered"] = array_merge_recursive(
                        $subQuery["filtered"],
                        $this->transformCriterion($criterion, $keyBag)
                    );
                }
            } else {
                // Group with OR
                $subQueries = [];

                foreach ($splitConditions as $splitCondition) {
                    $keyBag = [];

                    $subQuery["filtered"] = [
                        "filter" => [],
                    ];

                    /** @var CriterionInterface $criterion */
                    foreach ($splitCondition as $criterion) {
                        $subQuery["filtered"] = array_merge_recursive(
                            $subQuery["filtered"],
                            $this->transformCriterion($criterion, $keyBag)
                        );
                    }

                    $subQueries[]["query"] = $subQuery;
                }

                $subQuery = ["filtered" => ["filter" => ["or" => $subQueries]]];
            }
        }

        return $subQuery;
    }
15585
def clear_rubric(self):
        
        # Implemented from template for osid.resource.ResourceForm.clear_avatar_template
        if (self.get_rubric_metadata().is_read_only() or
                self.get_rubric_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['rubricId'] = self._rubric_default
15283
private void sortList(ArrayList candidateList) {
    java.util.Collections.sort(candidateList, new java.util.Comparator() {
      public int compare(Object o1, Object o2) {
        double scoreT = ( (TagLink.Candidates) o1).getScore();
        double scoreU = ( (TagLink.Candidates) o2).getScore();
        if(scoreU > scoreT){
			return 1;
		}
        if(scoreU > scoreT){
			return -1;
		}
		return 0;
      }
    }
    );
  }