Question:
Returns all the commerce regions where commerceCountryId = ? and active = ?.

@param commerceCountryId the commerce country ID
@param active the active
@return the matching commerce regions

@Override
	public List<CommerceRegion> findByC_A(long commerceCountryId, boolean active) {
		return findByC_A(commerceCountryId, active, QueryUtil.ALL_POS,
			QueryUtil.ALL_POS, null);
	}

public function deriveProductTree(SKU $sku) {
    static $cache = [];

    if (isset($cache[$sku->language()->getId()], $cache[$sku->language()->getId()][$sku->id()])) {
      return $cache[$sku->language()->getId()][$sku->id()];
    }

    $tree = [
      'parent' => $sku,
      'products' => self::getChildren($sku),
      'combinations' => [],
    ];

    $configurables = unserialize(
      $sku->get('field_configurable_attributes')->getString()
    );

    $tree['configurables'] = [];
    foreach ($configurables as $configurable) {
      $tree['configurables'][$configurable['code']] = $configurable;
    }

    $configurable_codes = array_keys($tree['configurables']);

    foreach ($tree['products'] ?? [] as $sku_code => $sku_entity) {
      $attributes = $sku_entity->get('attributes')->getValue();
      $attributes = array_column($attributes, 'value', 'key');
      foreach ($configurable_codes as $code) {
        $value = $attributes[$code] ?? '';

        if (empty($value)) {
          continue;
        }

        $tree['combinations']['by_sku'][$sku_code][$code] = $value;
      }
    }

    /** @var \Drupal\acm_sku\CartFormHelper $helper */
    $helper = \Drupal::service('acm_sku.cart_form_helper');

    $configurable_weights = $helper->getConfigurableAttributeWeights(
      $sku->get('attribute_set')->getString()
    );

    // Sort configurables based on the config.
    uasort($tree['configurables'], function ($a, $b) use ($configurable_weights) {
      return $configurable_weights[$a['code']] - $configurable_weights[$b['code']];
    });

    $tree['options'] = Configurable::recursiveConfigurableTree(
      $tree,
      $tree['configurables']
    );

    $cache[$sku->language()->getId()][$sku->id()] = $tree;

    return $tree;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@Override
	public EClass getIfcRectangularPyramid() {
		if (ifcRectangularPyramidEClass == null) {
			ifcRectangularPyramidEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(504);
		}
		return ifcRectangularPyramidEClass;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

Instruction: Given a code description, retrieve the corresponding code.


Question:
This function serves as interface between model input vectors and
            objective input vectors

def model_to_objective(self, x_model):
        '''
        '''
        idx_model = 0
        x_objective = []

        for idx_obj in range(self.objective_dimensionality):
            variable = self.space_expanded[idx_obj]
            new_entry = variable.model_to_objective(x_model, idx_model)
            x_objective += new_entry
            idx_model += variable.dimensionality_in_model

        return x_objective

@Nonnull
	public static <T1, T2> LBiObjFltPredicate<T1, T2> biObjFltPredicateFrom(Consumer<LBiObjFltPredicateBuilder<T1, T2>> buildingFunction) {
		LBiObjFltPredicateBuilder builder = new LBiObjFltPredicateBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add the templating definitions to the container.

Adds the View class, and if no other templating strategy is present, adds and binds the default.

@since  1.0.0

private static function init_templating()
    {
        // If no templating strategy has already been registered.
        if (!static::$container->has(Templating_Interface::class)) {
            // Add the default rendering engine.
            static::$container->add_singleton(
                \Snap\Templating\Standard\Standard_Strategy::class,
                function () {
                    return new \Snap\Templating\Standard\Standard_Strategy;
                }
            );

            static::$container->bind(\Snap\Templating\Standard\Standard_Strategy::class, Templating_Interface::class);

            static::$container->add(
                \Snap\Templating\Standard\Partial::class,
                function (Container $hodl) {
                    return $hodl->resolve(\Snap\Templating\Standard\Partial::class);
                }
            );
        }
    }

public function loadFile($url)
    {
        //Locate the template
        $locator = $this->getObject('template.locator.factory')->createLocator($url);

        if (!$file = $locator->locate($url)) {
            throw new InvalidArgumentException(sprintf('The template "%s" cannot be located.', $url));
        }

        $type = pathinfo($file, PATHINFO_EXTENSION);

        if(!in_array($type, $this->_excluded_types))
        {
            //Create the template engine
            $config = array(
                'template' => $this,
                'functions' => $this->_functions
            );

            $this->_source = $this->getObject('template.engine.factory')
                ->createEngine($file, $config)
                ->loadFile($url);
        }
        else parent::loadFile($url);

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: To be overridden in subclasses.

def handle_error(error)
      return unless que_target

      max = resolve_que_setting(:maximum_retry_count)

      if max && error_count > max
        expire
      else
        retry_in_default_interval
      end
    end

@Inline(value = "translate($1, null, $2, $3)")
	public void translate(List<? extends S> thePath, double curvilineCoord, double shiftCoord) {
		translate(thePath, null, curvilineCoord, shiftCoord);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: Converts a MOR to a psphere object.

def _mor_to_pobject(self, mo_ref):
        """"""
        kls = classmapper(mo_ref._type)
        new_object = kls(mo_ref, self)
        return new_object

function pretty(srcObj) {
      return typeOf(srcObj, 'arr', 'obj') ? JSON.stringify(srcObj, null, 2) : String(srcObj);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Generates the list of OpenEngSBModelEntries which need to be added. Also adds the entries of the super classes.

private static String createModelEntryList(CtClass clazz) throws NotFoundException, CannotCompileException {
        StringBuilder builder = new StringBuilder();
        CtClass tempClass = clazz;
        while (tempClass != null) {
            for (CtField field : tempClass.getDeclaredFields()) {
                String property = field.getName();
                if (property.equals(TAIL_FIELD) || property.equals(LOGGER_FIELD)
                        || JavassistUtils.hasAnnotation(field, IgnoredModelField.class.getName())) {
                    builder.append(createTrace(String.format("Skip property '%s' of the model", property)));
                    continue;
                }
                builder.append(handleField(field, clazz));
            }
            tempClass = tempClass.getSuperclass();
        }
        return builder.toString();
    }

def metadata_update_endpoints(self):

        metadata = load_mpe_service_metadata(self.args.metadata_file)
        group_name = metadata.get_group_name_nonetrick(self.args.group_name)
        metadata.remove_all_endpoints_for_group(group_name)
        for endpoint in self.args.endpoints:
            metadata.add_endpoint(group_name, endpoint)
        metadata.save_pretty(self.args.metadata_file)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Resolves the proxied bean instance for this bean.

@param beanContext The {@link BeanContext}
@return The proxied bean

@SuppressWarnings({"unchecked", "unused"})
    @Internal
    protected final Object getProxiedBean(BeanContext beanContext) {
        DefaultBeanContext defaultBeanContext = (DefaultBeanContext) beanContext;
        Optional<String> qualifier = getAnnotationMetadata().getAnnotationNameByStereotype(javax.inject.Qualifier.class);
        return defaultBeanContext.getProxyTargetBean(getBeanType(), (Qualifier<T>) qualifier.map(q -> Qualifiers.byAnnotation(getAnnotationMetadata(), q)).orElse(null));
    }

def produce_context(namespace, context_id, max_delay=None):
    """"""
    try:
        context_obj = get_context(namespace, context_id)
        logger.info("Found context '%s:%s'", namespace, context_id)
    except ContextError:
        logger.info("Context '%s:%s' not found", namespace, context_id)
        if max_delay is not None:
            max_delay = float(max_delay)
        logger.info("Context error handled with max_delay=%s", max_delay)
        if not max_delay \
                or arrival_delay_greater_than(context_id, max_delay):
            context_obj = {}
            logger.info(
                "Timeout: waited %s seconds for context '%s'",
                max_delay, context_id)
        else:
            msg = "Context '{}' not found: resorting".format(context_id)
            raise OutOfOrderError(msg)

    return context_obj

Instruction: Given a code description, retrieve the corresponding code.


Question:
Manage the sending of authentication traps.

    :param bool status: The enabled status.

    Example of usage:

    .. code-block:: yaml

        snmp-auth-traps:
            win_snmp.auth_traps_enabled:
                - status: True

def auth_traps_enabled(name, status=True):
    '''

    '''
    ret = {'name': name,
           'changes': {},
           'comment': six.text_type(),
           'result': None}

    vname = 'EnableAuthenticationTraps'
    current_status = __salt__['win_snmp.get_auth_traps_enabled']()

    if status == current_status:
        ret['comment'] = '{0} already contains the provided value.'.format(vname)
        ret['result'] = True
    elif __opts__['test']:
        ret['comment'] = '{0} will be changed.'.format(vname)
        ret['changes'] = {'old': current_status,
                          'new': status}
    else:
        ret['comment'] = 'Set {0} to contain the provided value.'.format(vname)
        ret['changes'] = {'old': current_status,
                          'new': status}
        ret['result'] = __salt__['win_snmp.set_auth_traps_enabled'](status=status)

    return ret

def wait_multi(self, channels, allowed_methods=None, timeout=None):
        """"""
        chanmap = dict((chan.channel_id, chan) for chan in channels)
        chanid, method_sig, args, content = self._wait_multiple(
                chanmap.keys(), allowed_methods, timeout=timeout)

        channel = chanmap[chanid]

        if content \
        and channel.auto_decode \
        and hasattr(content, 'content_encoding'):
            try:
                content.body = content.body.decode(content.content_encoding)
            except Exception:
                pass

        amqp_method = channel._METHOD_MAP.get(method_sig, None)

        if amqp_method is None:
            raise Exception('Unknown AMQP method (%d, %d)' % method_sig)

        if content is None:
            return amqp_method(channel, args)
        else:
            return amqp_method(channel, args, content)

Instruction: Given a code description, retrieve the corresponding code.


Question: // Sets the app-only auth token to the specified string.

func (c *Client) SetAppToken(token string) {
	c.AppToken = &BearerToken{
		AccessToken: token,
	}
}

public void marshall(SoftwareTokenMfaConfigType softwareTokenMfaConfigType, ProtocolMarshaller protocolMarshaller) {

        if (softwareTokenMfaConfigType == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(softwareTokenMfaConfigType.getEnabled(), ENABLED_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add fragment of data to the queue.

@param {String} name Pagelet name that queued the content.
@param {String} parent Pagelet parent that queued the content.
@param {Mixed} data Output to be send to the response
@returns {Pagelet} this
@api public

function queue(name, parent, data) {
    this.length--;

    //
    // Object was queued, transform the response type to application/json.
    //
    if ('object' === typeof data && this._contentType !== contentTypes.json) {
      this.emit('contentType', 'json');
    }

    this._queue.push({
      parent: parent,
      name: name,
      view: data
    });

    return this;
  }

def _parse(self):

        responses = []
        for child in self._element:
            weight = int_attribute(child, 'weight', 1)
            self._log.debug('Parsing random entry with weight {weight}: {entry}'
                            .format(weight=weight, entry=child.text))

            # If the random element doesn't contain any tags, just store the text and return
            if not len(child):
                responses.append((child.text, weight))
                continue

            # Otherwise, parse all the available tags
            responses.append((tuple(self.trigger.agentml.parse_tags(child, self.trigger)), weight))
        self._responses = tuple(responses)

Instruction: Given a code description, retrieve the corresponding code.


Question:
The given $value is valid if it is an \Neos\Media\Domain\Model\ImageInterface of the configured resolution
Note: a value of NULL or empty string ('') is considered valid

@param ImageInterface $image The image that should be validated
@return void
@api

protected function isValid($image)
    {
        $this->validateOptions();

        if (!$image instanceof ImageInterface) {
            $this->addError('The given value was not an Image instance.', 1327943859);
            return;
        }
        if (isset($this->options['minimumWidth']) && $image->getWidth() < $this->options['minimumWidth']) {
            $this->addError('The actual image width of %1$d is lower than the allowed minimum width of %2$d.', 1319801362, [$image->getWidth(), $this->options['minimumWidth']]);
        } elseif (isset($this->options['maximumWidth']) && $image->getWidth() > $this->options['maximumWidth']) {
            $this->addError('The actual image width of %1$d is higher than the allowed maximum width of %2$d.', 1319801859, [$image->getWidth(), $this->options['maximumWidth']]);
        }
        if (isset($this->options['minimumHeight']) && $image->getHeight() < $this->options['minimumHeight']) {
            $this->addError('The actual image height of %1$d is lower than the allowed minimum height of %2$d.', 1319801925, [$image->getHeight(), $this->options['minimumHeight']]);
        } elseif (isset($this->options['maximumHeight']) && $image->getHeight() > $this->options['maximumHeight']) {
            $this->addError('The actual image height of %1$d is higher than the allowed maximum height of %2$d.', 1319801929, [$image->getHeight(), $this->options['maximumHeight']]);
        }

        if (isset($this->options['minimumResolution']) || isset($this->options['maximumResolution'])) {
            $resolution = $image->getWidth() * $image->getHeight();
            if (isset($this->options['minimumResolution']) && $resolution < $this->options['minimumResolution']) {
                $this->addError('The given image size of %1$d x %2$d is too low for the required minimum resolution of %3$d.', 1319813336, [$image->getHeight(), $image->getHeight(), $this->options['minimumResolution']]);
            } elseif (isset($this->options['maximumResolution']) && $resolution > $this->options['maximumResolution']) {
                $this->addError('The given image size of %1$d x %2$d is too high for the required maximum resolution of %3$d.', 1319813355, [$image->getHeight(), $image->getHeight(), $this->options['maximumResolution']]);
            }
        }
    }

func (schema *Schema) IsEmpty() bool {
	return (schema.Schema == nil) &&
		(schema.ID == nil) &&
		(schema.MultipleOf == nil) &&
		(schema.Maximum == nil) &&
		(schema.ExclusiveMaximum == nil) &&
		(schema.Minimum == nil) &&
		(schema.ExclusiveMinimum == nil) &&
		(schema.MaxLength == nil) &&
		(schema.MinLength == nil) &&
		(schema.Pattern == nil) &&
		(schema.AdditionalItems == nil) &&
		(schema.Items == nil) &&
		(schema.MaxItems == nil) &&
		(schema.MinItems == nil) &&
		(schema.UniqueItems == nil) &&
		(schema.MaxProperties == nil) &&
		(schema.MinProperties == nil) &&
		(schema.Required == nil) &&
		(schema.AdditionalProperties == nil) &&
		(schema.Properties == nil) &&
		(schema.PatternProperties == nil) &&
		(schema.Dependencies == nil) &&
		(schema.Enumeration == nil) &&
		(schema.Type == nil) &&
		(schema.AllOf == nil) &&
		(schema.AnyOf == nil) &&
		(schema.OneOf == nil) &&
		(schema.Not == nil) &&
		(schema.Definitions == nil) &&
		(schema.Title == nil) &&
		(schema.Description == nil) &&
		(schema.Default == nil) &&
		(schema.Format == nil) &&
		(schema.Ref == nil)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Count all the competencies in a learning plan template.

@param  template|int $templateorid The template or its ID.
@return int

public static function count_competencies_in_template($templateorid) {
        static::require_enabled();
        // First we do a permissions check.
        $template = $templateorid;
        if (!is_object($template)) {
            $template = new template($template);
        }

        if (!$template->can_read()) {
            throw new required_capability_exception($template->get_context(), 'moodle/competency:templateview',
                'nopermissions', '');
        }

        // OK - all set.
        return template_competency::count_competencies($template->get('id'));
    }

func (c Command) Size() int {
	if c.Payload != nil {
		return c.Payload.Size() + 1
	}
	return 1
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Generate a new key from a password using 50,000 rounds of HMAC-SHA256.

        This should generate the same result as bip32.org.

        WARNING: The security of this method has not been evaluated.

def from_master_secret_slow(cls, password, network=BitcoinMainNet):

        # Make sure the password string is bytes
        key = ensure_bytes(password)
        data = unhexlify(b"0" * 64)  # 256-bit 0
        for i in range(50000):
            data = hmac.new(key, msg=data, digestmod=sha256).digest()
        return cls.from_master_secret(data, network)

protected function pass($mac, $macHash)
    {
        $time = time();
        $hash = $this->getTextHash($mac);
        $pass = $this->passFromSession($macHash, $hash, $time);

        // if captcha info was NOT stored in session
        if ($pass === null) {
            $pass = $this->passFromDb((int) $macHash, $hash, $time);
        }

        return (bool) $pass;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Secret implements fi.SecretStore::Secret

func (c *ClientsetSecretStore) Secret(name string) (*fi.Secret, error) {
	s, err := c.FindSecret(name)
	if err != nil {
		return nil, err
	}
	if s == nil {
		return nil, fmt.Errorf("Secret not found: %q", name)
	}
	return s, nil
}

public function &getStorage($storage_name): LanguageStorage
    {
        $return = false;

        if (isset($storage_name, $this->storage->{$storage_name})) {
            $return = $this->storage->{$storage_name};
        }

        return $return;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Send the "cancel" message to the server

def cancel
      workitem[CANCEL_META] = true
      send_workitem_message
    rescue Exception => e
      Maestro.log.warn "Failed To Send Cancel Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}"
    ensure
      workitem.delete(CANCEL_META)
    end

func (f *flotillaState) Apply(l *raft.Log) interface{} {
	cmd := &commandReq{}
	err := decodeMsgPack(l.Data, cmd)
	if err != nil {
		return Result{nil, err}
	}
	// open write txn
	txn, err := f.env.writeTxn()
	if err != nil {
		return &Result{nil, err}
	}
	// execute command, get results
	cmdExec, ok := f.commands[cmd.Cmd]
	result := Result{nil, nil}
	if !ok {
		result.Err = fmt.Errorf("No command registered with name %s", cmd.Cmd)
	} else {
		result.Response, result.Err = cmdExec(cmd.Args, txn)
	}
	// confirm txn handle closed (our txn wrapper keeps track of state so we don't abort committed txn)
	txn.Abort()
	// check for callback
	//f.lg.Printf("flotillaState Finished command %s with result %s err %s", cmd.Cmd, string(result.Response), result.Err)
	if cmd.OriginAddr == f.addr {
		f.l.Lock()
		defer f.l.Unlock()
		cb, ok := f.localCallbacks[cmd.Reqno]
		if ok {
			cb.result <- result
			delete(f.localCallbacks, cmd.Reqno)
		} else {
			f.lg.Printf("ERROR no local callback for command that we should have had! reqno %d", cmd.Reqno)
		}
	}

	return result
}

Instruction: Given a code description, retrieve the corresponding code.


Question: event handler for toggle buttons in Hybrid(horizontal + vertical) OrgChart

function (event) {
      var $toggleBtn = $(event.target);
      var $descWrapper = $toggleBtn.parent().next();
      var $descendants = $descWrapper.find('.node');
      var $children = $descWrapper.children().children('.node');
      if ($children.is('.sliding')) { return; }
      $toggleBtn.toggleClass('fa-plus-square fa-minus-square');
      if ($descendants.eq(0).is('.slide-up')) {
        $descWrapper.removeClass('hidden');
        this.repaint($children.get(0));
        $children.addClass('sliding').removeClass('slide-up').eq(0).one('transitionend', { 'vNodes': $children }, this.expandVNodesEnd);
      } else {
        $descendants.addClass('sliding slide-up').eq(0).one('transitionend', { 'vNodes': $descendants }, this.collapseVNodesEnd);
        $descendants.find('.toggleBtn').removeClass('fa-minus-square').addClass('fa-plus-square');
      }
    }

function() {
      var t = this,
          branches = t.model.get('branches'),
          leaves = t.model.get('leaves'),
          hash = "";

      // The hash is the text of the branches & leaves
      branches && branches.forEach(function(node) {
        var label = node.get('label') || node.id,
            description = node.get('description');
        hash += '|' + label;
        if (description) {
          hash += '|' + description;
        }
      });

      // The hash is the text of the branches & leaves
      leaves && leaves.forEach(function(node) {
        var label = node.get('label') || node.id,
            description = node.get('description');
        hash += '|' + label;
        if (description) {
          hash += '|' + description;
        }
      });

      // Return the hash
      return hash;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param array $expected_rows
@param array $actual_rows

@return string

protected function generateMessageForPostSortDifferences(array $expected_rows, array $actual_rows)
    {
        $message = [];
        $this->addArrayDiffMessageLines($message, $actual_rows, $expected_rows, '--- ' . $this->getMissingRowsLabel());
        $this->addArrayDiffMessageLines($message, $expected_rows, $actual_rows, '+++ ' . $this->getUnexpectedRowsLabel());
        return implode(PHP_EOL, $message);
    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Generates a column for the given field and adds it to the table.

@param fieldDef The field
@param tableDef The table
@return The column def

private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)
    {
        String    name      = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);
        ColumnDef columnDef = tableDef.getColumn(name);

        if (columnDef == null)
        {
            columnDef = new ColumnDef(name);
            tableDef.addColumn(columnDef);
        }
        if (!fieldDef.isNested())
        {
            columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());
        }
        columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));
        columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));
        if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))
        {
            columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, "true");
            columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, "true");
        }
        else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))
        {
            columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, "true");
        }
        if ("database".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))
        {
            columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, "true");
        }
        columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());
        if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))
        {
            columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,
                                  fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));
        }
        if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))
        {
            columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,
                                  fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));
        }
        return columnDef;
    }

public JDBCAppendTableSink build() {
		Preconditions.checkNotNull(parameterTypes,
			"Types of the query parameters are not specified." +
			" Please specify types using the setParameterTypes() method.");

		JDBCOutputFormat format = JDBCOutputFormat.buildJDBCOutputFormat()
			.setUsername(username)
			.setPassword(password)
			.setDBUrl(dbURL)
			.setQuery(query)
			.setDrivername(driverName)
			.setBatchInterval(batchSize)
			.setSqlTypes(parameterTypes)
			.finish();

		return new JDBCAppendTableSink(format);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Resource set wrapper for the resource being serialized.

@return ResourceSetWrapper

protected function getCurrentResourceSetWrapper()
    {
        $segmentWrappers = $this->getStack()->getSegmentWrappers();
        $count = count($segmentWrappers);

        return 0 == $count ? $this->getRequest()->getTargetResourceSetWrapper() : $segmentWrappers[$count-1];
    }

public void marshall(JobResource jobResource, ProtocolMarshaller protocolMarshaller) {

        if (jobResource == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(jobResource.getS3Resources(), S3RESOURCES_BINDING);
            protocolMarshaller.marshall(jobResource.getLambdaResources(), LAMBDARESOURCES_BINDING);
            protocolMarshaller.marshall(jobResource.getEc2AmiResources(), EC2AMIRESOURCES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a random polygon of any class. The probability of each polygon to be sampled
        is proportional to its area if weighted is True.

def sample_cc(self, nsamples=1, weighted=True):

        weights = self.areas / np.sum(self.areas) if weighted else None
        for index in np.random.choice(a=len(self.geometries), size=nsamples, p=weights):
            yield self.geometries[index]

func (m *nodeMap) getRandomNodes(size int, exclude ...*Node) []*Node {
	allNodes := m.values()

	if size == 0 {
		size = len(allNodes)
	}

	// First, shuffle the allNodes slice
	for i := range allNodes {
		j := rand.Intn(i + 1)
		allNodes[i], allNodes[j] = allNodes[j], allNodes[i]
	}

	// Copy the first size nodes that are not otherwise excluded
	filtered := make([]*Node, 0, len(allNodes))

	// Horribly inefficient. Fix this later.

	var c int
Outer:
	for _, n := range allNodes {
		// Is the node in the excluded list?
		for _, e := range exclude {
			if n.Address() == e.Address() {
				continue Outer
			}
		}

		// Now we can append it
		filtered = append(filtered, n)
		c++

		if c >= size {
			break Outer
		}
	}

	return filtered
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Convert Group to an Array of Hashes (by calling .to_h on each member)
 @return [Array<Hash>]

def to_a(with_errors: false, with_values: false)
      options.map {|opt| opt.to_h(with_errors: with_errors, with_value: with_values) }
    end

def links
      @links ||= if @breadcrumb_key.present?
        # Reload breadcrumbs configuration if needed
        Gretel::Crumbs.reload_if_needed

        # Get breadcrumb set by the `breadcrumb` method
        crumb = Gretel::Crumb.new(context, breadcrumb_key, *breadcrumb_args)

        # Links of first crumb
        links = crumb.links.dup

        # Get parent links
        links.unshift *parent_links_for(crumb)

        links
      else
        []
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question: Processing the whole pipeline definition.

def process(self, pipeline):
        """"""
        output = []
        for entry in pipeline:
            key = list(entry.keys())[0]
            # an environment block can be repeated
            if key == "env":
                self.data.env_list[0].update(entry[key])
                self.logger.debug("Updating environment at level 0 with %s",
                                  self.data.env_list[0])
                continue

            # after validation it can't be anything else but a stage
            # and the title is inside the round brackets:
            stage = Stage(self, re.match(r"stage\((?P<title>.*)\)", key).group("title"))
            result = stage.process(entry[key])
            output += result['output']
            if not result['success']:
                return {'success': False, 'output': output}

        # logging the output of the cleanup shell when registered
        for line in self.cleanup():
            output.append(line)
            self.logger.info(" | %s", line)

        self.event.succeeded()
        return {'success': True, 'output': output}

def list(self, path=None, with_metadata=False, include_partitions=False):
        ''''''
        return self.upstream.list(
            path,
            with_metadata=with_metadata,
            include_partitions=include_partitions)

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetNodeTypeSpecificValues sets the NodeTypeSpecificValues field's value.

func (s *Parameter) SetNodeTypeSpecificValues(v []*NodeTypeSpecificValue) *Parameter {
	s.NodeTypeSpecificValues = v
	return s
}

public function addField($name, $type)
    {
        $this->checkNotNull($type, 'type')
            ->checkNotNull($name, 'name')
            ->field_definitions[$name] = $type;

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Fires the given event to all registered listeners

public void fireTagParseEvent(TagParseEvent tpe)
	{
		for (int i = 0; i < tagParseListeners.size(); i++)
		{
			TagParseListener l = tagParseListeners.get(i);
			l.tagParsed(tpe);
		}
	}

@Override
    public void afterInitialized(BaseComponent comp) {
        root = (BaseUIComponent) comp;
        this.comp = root;
        comp.setAttribute(Constants.ATTR_COMPOSER, this);
        comp.addEventListener(ThreadEx.ON_THREAD_COMPLETE, threadCompletionListener);
        appContext = SpringUtil.getAppContext();
        appFramework = FrameworkUtil.getAppFramework();
        eventManager = EventManager.getInstance();
        initialize();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: event for download button

def click_download(self, event):

		args ['parallel'] = self.p.get()
		args ['file_type'] = self.optionmenu.get()
		args ['no_redirects'] = self.t.get()
		args ['query'] = self.entry_query.get()
		args ['min_file_size'] = int( self.entry_min.get())
		args ['max_file_size'] = int( self.entry_max.get())
		args ['limit'] = int( self.entry_limit.get())
		args ['website']= self.entry_website.get()
		args ['option']= self.engine.get()
		print(args)
		self.check_threat()
		download_content_gui( **args )

public static DataStoreEvent removalEvent(DBIDs removals) {
    return new DataStoreEvent(DBIDUtil.EMPTYDBIDS, removals, DBIDUtil.EMPTYDBIDS);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetApplicationSettings sets the ApplicationSettings field's value.

func (s *CreateStackInput) SetApplicationSettings(v *ApplicationSettings) *CreateStackInput {
	s.ApplicationSettings = v
	return s
}

def _settings_from_file(self):
        """"""
        settings = load_source(
            'settings', text_type(self.user_dir.joinpath('settings.py')))
        return {key: getattr(settings, key)
                for key in const.DEFAULT_SETTINGS.keys()
                if hasattr(settings, key)}

Instruction: Given a code description, retrieve the corresponding code.


Question: /* ISTANBUL_IGNORE_IF_NOT_OSX

function _osxPs() {
  const fieldsInfo = _.map({user: 'user', pid: 'pid', ppid: 'ppid', cmd: 'comm', full_cmd: 'command'}, (value, key) => {
    return {name: key, specifier: value};
  });

  // Parsing OS X version of ps seems very complicated, you cannot specify a separator
  // but specifying a header is possible. So we will specify a well known header pattern and
  // read each column size to be able to parse the rest
  const spacerLength = 100;
  const spacer = '_'.repeat(spacerLength);
  const specifiersArg = _.map(fieldsInfo, e => `${e.specifier}=${spacer}`).join(',');

  let firstLine = true;
  const sizes = [];
  return _ps(['wwaxo', specifiersArg], line => {
    // Use the first line (the header) to calculate all columns length
    if (firstLine) {
      const re = new RegExp(`(${spacer} *)`, 'g');
      let match = null;
      /* eslint-disable no-cond-assign */
      while ((match = re.exec(line)) !== null) {
        const field = match[1];
        sizes.push(field.length);
      }
      /* eslint-enable no-cond-assign */
      if (sizes.length !== fieldsInfo.length) throw new Error('Cannot parse ps output');
      firstLine = false;
      return null;
    }

    const process = {};
    let startIdx = 0;
    // Split the line using the column sizes
    _.each(sizes, (size, index) => {
      const value = line.slice(startIdx, startIdx + size).trim();
      startIdx += size;
      const key = fieldsInfo[index].name;
      process[key] = value;
    });
    return process;
  });
}

func ParseRoller(l *LogRoller, what string, where string) error {
	if l == nil {
		l = DefaultLogRoller()
	}
	var value int
	var err error
	value, err = strconv.Atoi(where)
	if err != nil {
		return err
	}
	switch what {
	case directiveRotateSize:
		l.MaxSize = value
	case directiveRotateAge:
		l.MaxAge = value
	case directiveRotateKeep:
		l.MaxBackups = value
	}
	return nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add a preference.

@param preference The preference to add.
@return The generator parameter itself.

public GeneratorParameter add(Preference preference)
    {
        preferences.add(preference);
        Collections.sort(preferences);
        return this;
    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Setup argument Parsing.

def create_parser():
    """"""
    description = """RPC Release Diff Generator
--------------------------

Finds changes in OpenStack-Ansible, OpenStack-Ansible roles, and OpenStack
projects between two RPC-OpenStack revisions.

"""

    parser = argparse.ArgumentParser(
        usage='%(prog)s',
        description=description,
        epilog='Licensed "Apache 2.0"',
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        'old_commit',
        action='store',
        nargs=1,
        help="Git SHA of the older commit",
    )
    parser.add_argument(
        'new_commit',
        action='store',
        nargs=1,
        help="Git SHA of the newer commit",
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        default=False,
        help="Enable debug output",
    )
    parser.add_argument(
        '--verbose',
        action='store_true',
        default=False,
        help="Enable verbose output",
    )
    parser.add_argument(
        '-d', '--directory',
        action='store',
        default="~/.osa-differ",
        help="Git repo storage directory (default: ~/.osa-differ)",
    )
    parser.add_argument(
        '-rroc', '--role-requirements-old-commit',
        action='store',
        default=None,
        help=(
            "Name of the Ansible role requirements file to read from the old "
            "commit, defaults to value of `--role-requirements`."
        ),
    )
    parser.add_argument(
        '-rr', '--role-requirements',
        action='store',
        default=ROLE_REQ_FILE,
        help="Name of the ansible role requirements file to read",
    )
    parser.add_argument(
        '-r', '--rpc-repo-url',
        action='store',
        default="https://github.com/rcbops/rpc-openstack",
        help="Github repository for the rpc-openstack project"
    )
    parser.add_argument(
        '--osa-repo-url',
        action='store',
        default="https://git.openstack.org/openstack/openstack-ansible",
        help="URL of the openstack-ansible git repo"
    )
    parser.add_argument(
        '-rpoc', '--rpc-product-old-commit',
        action='store',
        default=None,
        help=(
            "Set the RPC product version for the old commit, defaults to "
            "value of `--rpc-product`."
        )
    )
    parser.add_argument(
        '-rp', '--rpc-product',
        action='store',
        default="master",
        help="Set the RPC product version"
    )
    parser.add_argument(
        '-u', '--update',
        action='store_true',
        default=False,
        help="Fetch latest changes to repo",
    )
    parser.add_argument(
        '--version-mappings',
        action=osa_differ.VersionMappingsAction,
        help=(
            "Map dependency versions in cases where the old version no longer "
            "exists. The argument should be of the form "
            "'repo-name;old-version1:new-version1;old-version2:new-version2'."
        ),
    )

    display_opts = parser.add_argument_group("Limit scope")
    display_opts.add_argument(
        "--skip-projects",
        action="store_true",
        help="Skip checking for changes in OpenStack projects"
    )
    display_opts.add_argument(
        "--skip-roles",
        action="store_true",
        help="Skip checking for changes in OpenStack-Ansible roles"
    )
    output_desc = ("Output is printed to stdout by default.")
    output_opts = parser.add_argument_group('Output options', output_desc)
    output_opts.add_argument(
        '--quiet',
        action='store_true',
        default=False,
        help="Do not output to stdout",
    )
    output_opts.add_argument(
        '--gist',
        action='store_true',
        default=False,
        help="Output into a GitHub Gist",
    )
    output_opts.add_argument(
        '--file',
        metavar="FILENAME",
        action='store',
        help="Output to a file",
    )
    return parser

def _es_content(settings):

        return {k: settings[k] for k in (ConsoleWidget.SETTING_WIDTH,
                                         ConsoleWidget.SETTING_ALIGN,
                                         ConsoleWidget.SETTING_PADDING,
                                         ConsoleWidget.SETTING_PADDING_LEFT,
                                         ConsoleWidget.SETTING_PADDING_RIGHT,
                                         ConsoleWidget.SETTING_PADDING_CHAR)}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Stops the profiling.
@param ResponseInterface $response

public function leave(ResponseInterface $response = null)
    {
        $this->ends = [
            'wt' => microtime(true),
            'mu' => memory_get_usage(),
            'pmu' => memory_get_peak_usage(),
        ];
        if ($response) {
            $this->response = [
                'headers' => $response->getHeaders(),
                'statusCode' => $response->getStatusCode(),
                'body' => (string)$response->getBody(),
            ];
        }
    }

public static HttpResponse parseMessage(InputStream in) throws IOException {
        HttpResponse m = new HttpResponse();
        m.parse(in);
        return m;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Calculate how much variance in returns do the values explain

def explained_variance(returns, values):

    exp_var = 1 - torch.var(returns - values) / torch.var(returns)
    return exp_var.item()

function yy_r160(){
    $this->_retvalue = array_merge($this->yystack[$this->yyidx + -1]->minor,$this->yystack[$this->yyidx + 0]->minor);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
通知状态变成不可用,主要是：

1.注册中心删除，更新节点后变成不可用时

2.连接断线后（心跳+调用），如果是可用节点为空

public void notifyStateChangeToUnavailable() {
        final List<ConsumerStateListener> onAvailable = consumerConfig.getOnAvailable();
        if (onAvailable != null) {
            AsyncRuntime.getAsyncThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    // 状态变化通知监听器
                    for (ConsumerStateListener listener : onAvailable) {
                        try {
                            listener.onUnavailable(consumerConfig.getConsumerBootstrap().getProxyIns());
                        } catch (Exception e) {
                            LOGGER.errorWithApp(consumerConfig.getAppName(),
                                "Failed to notify consumer state listener when state change to unavailable");
                        }
                    }
                }
            });
        }
    }

def setup_hook(config):
    """"""
    metadata = config['metadata']
    if sys.platform == 'win32':
        requires = metadata.get('requires_dist', '').split('\n')
        metadata['requires_dist'] = "\n".join(requires)
    config['metadata'] = metadata

    metadata['version'] = str(version)

    # pbr's setup_hook replaces easy_install.get_script_args with
    # their own version, override_get_script_args, prefering simpler
    # scripts which are not aware of multi-version.
    # prevent that by doing the opposite.  it's a horrible hack
    # but we are in patching wars already...
    from pbr import packaging

    def my_get_script_args(*args, **kwargs):
        return _main_module()._orig_get_script_args(*args, **kwargs)

    packaging.override_get_script_args = my_get_script_args
    easy_install.get_script_args = my_get_script_args

    # another hack to allow setup from tarball.
    orig_get_version = packaging.get_version

    def my_get_version(package_name, pre_version=None):
        if package_name == 'ryu':
            return str(version)
        return orig_get_version(package_name, pre_version)

    packaging.get_version = my_get_version

Instruction: Given a code description, retrieve the corresponding code.


Question:
Escape

@param string $str

@return String

public function escape(String $str) : String
    {
        if( ! is_resource($this->init) )
        {
            throw new InvalidArgumentException(NULL, '$this->init');
        }

        return curl_escape($this->init, $str);
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add a foreign key.

@param string $referenceTable   Referenced table name.
@param string $referenceColumns Columns of referenced table.
@param array  $options          Optional options.

@return TableApi Self.

public function addForeignKey($referenceTable, $referenceColumns, array $options = [])
    {
        $schema = isset($options['schema']) ? new Schema($options['schema']) : null;

        $foreignKey = new ForeignKey($this, new Table($referenceTable, $schema));
        $foreignKey->setReferencedColumns($referenceColumns);

        if (isset($options['column'])) {
            $foreignKey->setColumns($options['column']);
        } else {
            $foreignKey->setColumns($referenceColumns);
        }
        if (isset($options['update'])) {
            $foreignKey->setUpdateAction($options['update']);
        }
        if (isset($options['delete'])) {
            $foreignKey->setDeleteAction($options['delete']);
        }
        $this->actions[] =  function () use ($foreignKey) {
             return $this->manipulation->create($foreignKey);
        };

        return $this;
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // GetGid returns the group id for a given group name

func GetGid(name string) (int, error) {
	switch name {
	case "nobody":
		return NobodyGid, nil

	case "root":
		return RootGid, nil

	default:
		groupInfo, err := user.LookupGroup(name)
		if err != nil {
			return 0, err
		}

		return strconv.Atoi(groupInfo.Gid)
	}
}

func (sg SecurityGroup) RuleByID(ruleID UUID) (*IngressRule, *EgressRule) {
	for i, in := range sg.IngressRule {
		if in.RuleID.Equal(ruleID) {
			return &sg.IngressRule[i], nil
		}
	}

	for i, out := range sg.EgressRule {
		if out.RuleID.Equal(ruleID) {
			return nil, &sg.EgressRule[i]
		}
	}

	return nil, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Get the current time.

def now_time(str=False):
    """"""
    if str:
        return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return datetime.datetime.now()

public static function getCacheTime( $functionName )
    {
        static $mtime = null;
        if ( $mtime === null )
        {
            $mtime = filemtime( __FILE__ );
        }
        return $mtime;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sums two floats and returns the result.
The paramaters are set automatically from the GET request
when the API function is called. You can also use default values
as shown in this example.

@param float|int $a
@param float|int $b
@return float

public function getSum($a = 0, $b = 0)
    {
        if (!is_numeric($a) || !is_numeric($b)) {
            throw new \Exception('Given parameters need to be numeric');
        }

        return (float)($a + $b);
    }

public function addPut($url, $data = array())
    {
        if (is_array($url)) {
            $data = $url;
            $url = $this->baseUrl;
        }
        $curl = new Curl();
        $curl->setURL($url);
        $curl->setOpt(CURLOPT_CUSTOMREQUEST, 'PUT');
        $put_data = $curl->buildPostData($data);
        if (is_string($put_data)) {
            $curl->setHeader('Content-Length', strlen($put_data));
        }
        $curl->setOpt(CURLOPT_POSTFIELDS, $put_data);
        $this->addHandle($curl);
        return $curl;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetNumberOfNodes sets the NumberOfNodes field's value.

func (s *PendingModifiedValues) SetNumberOfNodes(v int64) *PendingModifiedValues {
	s.NumberOfNodes = &v
	return s
}

def get_default(self, node):

        if node.inst.properties.get("woset", False):
            return rdltypes.OnWriteType.woset
        elif node.inst.properties.get("woclr", False):
            return rdltypes.OnWriteType.woclr
        else:
            return self.default

Instruction: Given a code description, retrieve the corresponding code.


Question:
This method can execute any of the following statements: INSERT, DELETE,
UPDATE.

@param sql
the sql to be executed
@throws SQLException
if something goes wrong while accessing the Database

public void doSQL(final String sql) throws SQLException {

		LOG.info("Connecting to: " + this.dbString + " with " + this.usr
				+ " and " + this.pwd);
		LOG.info("Running: " + sql);
		Connection connection = null;
		Statement st = null;

		try {
			connection = DriverManager.getConnection(this.dbString, this.usr,
					this.pwd);

			st = connection.createStatement();
			st.executeUpdate(sql);

		} finally {

			if (st != null) {
				st.close();
			}
			if (connection != null) {
				connection.close();
			}
		}

	}

public static List<String> parseSQLStatements(String path, String name) {
		return parseSQLStatements("/" + path + "/" + name);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: Adds arrows to plotting object

def add_arrows(self, cent, direction, mag=1, **kwargs):

        direction = direction.copy()
        if cent.ndim != 2:
            cent = cent.reshape((-1, 3))

        if direction.ndim != 2:
            direction = direction.reshape((-1, 3))

        direction[:,0] *= mag
        direction[:,1] *= mag
        direction[:,2] *= mag

        pdata = vtki.vector_poly_data(cent, direction)
        # Create arrow object
        arrow = vtk.vtkArrowSource()
        arrow.Update()
        glyph3D = vtk.vtkGlyph3D()
        glyph3D.SetSourceData(arrow.GetOutput())
        glyph3D.SetInputData(pdata)
        glyph3D.SetVectorModeToUseVector()
        glyph3D.Update()

        arrows = wrap(glyph3D.GetOutput())

        return self.add_mesh(arrows, **kwargs)

def opts(self, dictobj):

		for k in dictobj:
			self.chart_opts[k] = dictobj[k]

Instruction: Given a code description, retrieve the corresponding code.


Question: Create super admin role and assign role

private function createAdmin(): void
    {
        $this->connection->beginTransaction();
        try {
            $this->userService->createUser(
                [
                    'email' => $this->email,
                    'password' => $this->password,
                    'is_active' => BoolEnum::yes()->id(),
                    'activated_at' => Carbon::now()->toDateTimeString(),
                ],
                [
                    'first_name' => 'Super',
                    'last_name' => 'Admin',
                    // TODO set admin default photo
                ],
                [
                    $this->roleRepository->getRoleSuperAdminId(),
                    $this->roleRepository->getRoleUserId()
                ]
            );
        } catch (\Throwable $exception) {
            $this->connection->rollBack();

            report($exception);

            $this->info('error:');
            $this->error($exception->getMessage());

            exit;
        }

        $this->connection->commit();
    }

def _addLocalOwnerRole(self, username):

        parent = self.getParent()
        if parent.portal_type == "Client":
            parent.manage_setLocalRoles(username, ["Owner", ])
            # reindex object security
            self._recursive_reindex_object_security(parent)

Instruction: Given a code description, retrieve the corresponding code.


Question: Move only to next tiers, to avoid double visiting of relocated entries during iteration

@Override
    public long alloc(int chunks, long prevPos, int prevChunks) {
        long ret = s.allocReturnCode(chunks);
        if (prevPos >= 0)
            s.free(prevPos, prevChunks);
        if (ret >= 0)
            return ret;
        while (true) {
            s.nextTier();
            ret = s.allocReturnCode(chunks);
            if (ret >= 0)
                return ret;
        }
    }

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

Instruction: Given a code description, retrieve the corresponding code.


Question:
Build a Prefer object with a set of included IRIs.

@param includes the IRIs to include
@return the Prefer object

public static Prefer ofInclude(final String... includes) {
        final List<String> iris = asList(includes);
        if (iris.isEmpty()) {
            return valueOf(join("=", PREFER_RETURN, PREFER_REPRESENTATION));
        }
        return valueOf(join("=", PREFER_RETURN, PREFER_REPRESENTATION) + "; " + PREFER_INCLUDE + "=\"" +
                iris.stream().collect(joining(" ")) + "\"");
    }

private function parseOptions(array $options): array
    {
        $child = $options['child'] ?? [];

        if (isset($options['header'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['header' => $options['header']]);
        }

        if (isset($options['divider'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['divider' => true]);
        }

        if (isset($options['icon'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['icon' => $options['icon']]);
        }

        if (isset($options['route']) && is_array($options['route'])) {
            $options['routeParameters'] = $options['route']['[parameters'] ?? [];
            $options['route'] = $options['route']['name'];
        }

        foreach ($this->parsers as $parser) {
            if ($result = $parser($options)) {
                $options = $result;
            }
        }

        unset($options['child']);

        return [
            'options' => $options,
            'child' => $child,
        ];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Sort the types within the stack according to the known type priorities.

function _sorter(a, b){
	// Use aid property priority.
	var bpri = aid.priority(b.property_id());
	var apri = aid.priority(a.property_id());
	return apri - bpri;
    }

public function orderBy($expression, $vector = OrderBy::ASC)
    {
        $expression = ($expression instanceof Expression) ? $expression : new Expr\Column($expression);
        $this->getOrderByStatement()->order($expression, $vector);

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Geocode returns the first point returned by OpenCage's geocoding service or an error
// if one occurs during the geocoding request.

func (g *OpenCageGeocoder) Geocode(address string) (*Point, error) {

	queryStr, err := opencageGeocodeQueryStr(address)
	if err != nil {
		return nil, err
	}

	data, err := g.Request(queryStr)
	if err != nil {
		return nil, err
	}

	res := &opencageGeocodeResponse{}
	json.Unmarshal(data, res)

	if len(res.Results) == 0 {
		return nil, opencageZeroResultsError
	}

	lat := res.Results[0].Geometry.Lat
	lng := res.Results[0].Geometry.Lng

	point := &Point{
		lat: lat,
		lng: lng,
	}

	return point, nil
}

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set World Bank url from which to retrieve countries data

        Args:
            url (str): World Bank url from which to retrieve countries data. Defaults to internal value.

        Returns:
            None

def set_ocha_url(cls, url=None):
        # type: (str) -> None

        if url is None:
            url = cls._ochaurl_int
        cls._ochaurl = url

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier.

func (s *TelegrafConfigStore) CreateTelegrafConfig(ctx context.Context, tc *platform.TelegrafConfig, userID platform.ID) error {
	return s.CreateTelegrafConfigF(ctx, tc, userID)
}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// RemovePod changes predicateMetadata assuming that the given `deletedPod` is
// deleted from the system.

func (meta *predicateMetadata) RemovePod(deletedPod *v1.Pod) error {
	deletedPodFullName := schedutil.GetPodFullName(deletedPod)
	if deletedPodFullName == schedutil.GetPodFullName(meta.pod) {
		return fmt.Errorf("deletedPod and meta.pod must not be the same")
	}
	meta.topologyPairsAntiAffinityPodsMap.removePod(deletedPod)
	// Delete pod from the matching affinity or anti-affinity topology pairs maps.
	meta.topologyPairsPotentialAffinityPods.removePod(deletedPod)
	meta.topologyPairsPotentialAntiAffinityPods.removePod(deletedPod)
	// All pods in the serviceAffinityMatchingPodList are in the same namespace.
	// So, if the namespace of the first one is not the same as the namespace of the
	// deletedPod, we don't need to check the list, as deletedPod isn't in the list.
	if meta.serviceAffinityInUse &&
		len(meta.serviceAffinityMatchingPodList) > 0 &&
		deletedPod.Namespace == meta.serviceAffinityMatchingPodList[0].Namespace {
		for i, pod := range meta.serviceAffinityMatchingPodList {
			if schedutil.GetPodFullName(pod) == deletedPodFullName {
				meta.serviceAffinityMatchingPodList = append(
					meta.serviceAffinityMatchingPodList[:i],
					meta.serviceAffinityMatchingPodList[i+1:]...)
				break
			}
		}
	}
	return nil
}

public function editAction(Request $request, $episode)
    {
        $episode = $this->get('oktolab_media')->getEpisode($episode);
        $form = $this->createForm(EpisodeType::class, $episode);
        $form->add(
            'submit',
            SubmitType::class,
            [
                'label' => 'oktolab_media.edit_episode_button',
                'attr' => ['class' => 'btn btn-primary']
            ]
        );
        if ($episode->getTechnicalStatus() != Episode::STATE_IN_PROGRESS_QUEUE) {
            $form->add(
                'submitAndEncode',
                SubmitType::class,
                [
                    'label' => 'okto_media.edit_episode_submitAndEncode_button',
                    'attr' => ['class' => 'btn btn-default']
                ]
            );
        }
        $form->add(
            'delete',
            SubmitType::class,
            [
                'label' => 'oktolab_media.delete_episode_button',
                'attr' => ['class' => 'btn btn-danger']
            ]
        );

        if ($request->getMethod() == "POST") { //sends form
            $form->handleRequest($request);
            $em = $this->getDoctrine()->getManager();
            if ($form->isValid()) { //form is valid, save or preview
                if ($form->get('submit')->isClicked()) { //save me
                    $em->persist($episode);
                    $em->flush();
                    $this->get('session')->getFlashBag()->add(
                        'success',
                        'oktolab_media.success_edit_episode'
                    );
                    return $this->redirect(
                        $this->generateUrl(
                            'oktolab_episode_show',
                            ['uniqID' => $episode->getUniqID()]
                        )
                    );
                } elseif ($form->get('submitAndEncode')->isClicked()) {
                    $em->persist($episode);
                    $em->flush();
                    $this->get('oktolab_media')->addEncodeEpisodeJob($episode->getUniqID());
                    $this->get('session')->getFlashBag()->add(
                        'success',
                        'okto_media.success_edit_and_encode_episode'
                    );
                    return $this->redirect(
                        $this->generateUrl(
                            'oktolab_episode_show',
                            ['uniqID' => $episode->getUniqID()]
                        )
                    );
                } elseif ($form->get('delete')->isClicked()) {
                    $em->remove($episode);
                    $em->flush();
                    $this->get('session')->getFlashBag()->add(
                        'success',
                        'oktolab_media.success_delete_episode'
                    );
                    if ($episode->getSeries()) {
                        return $this->redirect(
                            $this->generateUrl(
                                'oktolab_series_show',
                                ['series' => $episode->getSeries()->getUniqID()]
                            )
                        );
                    } else {
                        return $this->redirect(
                            $this->generateUrl('oktolab_series')
                        );
                    }
                } else { //???
                    $this->get('session')->getFlashBag()->add(
                        'success',
                        'oktolab_media.info_edit_episode_unknown_button'
                    );
                    return $this->redirect(
                        $this->generateUrl(
                            'oktolab_episode_show',
                            ['uniqID' => $episode->getUniqID()]
                        )
                    );
                }
            }
            $this->get('session')->getFlashBag()->add(
                'error',
                'oktolab_media.error_edit_episode'
            );
        }

        return ['form' => $form->createView()];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:346:1: typeList : type ( ',' type )* ;

public final void typeList() throws RecognitionException {
		int typeList_StartIndex = input.index();

		try {
			if ( state.backtracking>0 && alreadyParsedRule(input, 18) ) { return; }

			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:347:5: ( type ( ',' type )* )
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:347:7: type ( ',' type )*
			{
			pushFollow(FOLLOW_type_in_typeList603);
			type();
			state._fsp--;
			if (state.failed) return;
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:347:12: ( ',' type )*
			loop30:
			while (true) {
				int alt30=2;
				int LA30_0 = input.LA(1);
				if ( (LA30_0==43) ) {
					alt30=1;
				}

				switch (alt30) {
				case 1 :
					// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:347:13: ',' type
					{
					match(input,43,FOLLOW_43_in_typeList606); if (state.failed) return;
					pushFollow(FOLLOW_type_in_typeList608);
					type();
					state._fsp--;
					if (state.failed) return;
					}
					break;

				default :
					break loop30;
				}
			}

			}

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
			if ( state.backtracking>0 ) { memoize(input, 18, typeList_StartIndex); }

		}
	}

public @NotNull <T> List<T> findAll(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) {
        return findAll(cl, SqlQuery.query(sql, args));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets the cdnConfigurationType value for this CdnConfiguration.

@param cdnConfigurationType   * The type of CDN configuration represented by this {@link CdnConfiguration}.
This value is
required to create a CDN configuration

public void setCdnConfigurationType(com.google.api.ads.admanager.axis.v201811.CdnConfigurationType cdnConfigurationType) {
        this.cdnConfigurationType = cdnConfigurationType;
    }

public void marshall(EC2InstanceDetails eC2InstanceDetails, ProtocolMarshaller protocolMarshaller) {

        if (eC2InstanceDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(eC2InstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getInstanceType(), INSTANCETYPE_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getPlatform(), PLATFORM_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getTenancy(), TENANCY_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Returns schema view which renders Swagger/OpenAPI.

def get_swagger_view(title=None, url=None, generator_class=SchemaGenerator):

    return schemas.get_schema_view(
        title=title,
        url=url,
        renderer_classes=[
            CoreJSONRenderer,
            renderers.OpenAPIRenderer,
            renderers.SwaggerUIRenderer],
        generator_class=generator_class)

def get_samples_data(self):

        for obj in self.get_samples_from_request():
            yield {
                "obj": obj,
                "id": api.get_id(obj),
                "uid": api.get_uid(obj),
                "title": api.get_title(obj),
                "path": api.get_path(obj),
                "url": api.get_url(obj),
                "sample_type": obj.getSampleTypeTitle(),
                "client_title": obj.getClientTitle(),
                "date": ulocalized_time(obj.created(), long_format=True),
            }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Adds a participation to the data collector.

@param string $testIdentifier
@param string $variationIdentifier
@throws InvalidArgumentException

public function addParticipation($testIdentifier, $variationIdentifier)
    {
        Assert::string($testIdentifier, 'Test identifier must be a string');
        Assert::string($variationIdentifier, 'Variation name must be a string');

        $this->participations[$testIdentifier] = $variationIdentifier;
    }

public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException {
        return (withParam(name, value, false));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Process POST request

        if one of handler returns instance of :class:`aiogram.dispatcher.webhook.BaseResponse` return it to webhook.
        Otherwise do nothing (return 'ok')

        :return: :class:`aiohttp.web.Response`

async def post(self):

        self.validate_ip()

        # context.update_state({'CALLER': WEBHOOK,
        #                       WEBHOOK_CONNECTION: True,
        #                       WEBHOOK_REQUEST: self.request})

        dispatcher = self.get_dispatcher()
        update = await self.parse_update(dispatcher.bot)

        results = await self.process_update(update)
        response = self.get_response(results)

        if response:
            web_response = response.get_web_response()
        else:
            web_response = web.Response(text='ok')

        if self.request.app.get('RETRY_AFTER', None):
            web_response.headers['Retry-After'] = self.request.app['RETRY_AFTER']

        return web_response

public function hook(OutputInterface $output, array $response)
    {
        $this->printBoolean($output, 'OK', $response['success'], true === $response['success']);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: class to be used with fancyFail()

function AssertionError(actual, expected, phrase, base) {
  this.name = 'AssertionError';
  this.actual = actual;
  this.expected = expected;
  this.message = 'expected ' + objectDisplay(actual) + ' ' +
      phrase + ' ' +
    objectDisplay(expected);

  if (typeof actual === 'object' || typeof expected === 'object') {
    this.showDiff = true;
  }

  Error.captureStackTrace(this, base);
}

protected static function fail(
        int $errorCode = ErrorCodes::INVALID_VALUE,
        string $messageTemplate = Messages::INVALID_VALUE,
        array $messageParams = []
    ): RuleInterface {
        return new Fail($errorCode, $messageTemplate, $messageParams);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get specified argument value.

@param string $argument Argument name
@param string|null $alias Argument alias name (if exists)
@param mixed|null $default Default value if argument does not exists.
@return mixed

public function get($argument, $alias = null, $default = null)
    {
        if (isset($this->arguments[$argument])) {
            return $this->arguments[$argument];
        } else
            if (! empty($alias) && isset($this->arguments[$alias])) {
                return $this->arguments[$alias];
            } else {
                return $default;
            }
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
find cookie from request
@param request current request
@param name cookie name
@return cookie value or null

public static Cookie findCookie(HttpServletRequest request, String name) {
        if (request != null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(name)) {
                        return cookie;
                    }
                }
            }
        }
        return null;
    }

func (c *Client) Login(username, password string) error {
	var req = LoginBlock{
		Username:     username,
		Password:     password,
		CustomerName: c.CustomerName}

	var resp LoginResponse

	err := c.Do("POST", "Session", req, &resp)
	if err != nil {
		return err
	}

	c.Token = resp.Data.Token
	return nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Removes the workitem and hands it back to the flow with an error to
 raise for the participant expression that emitted the workitem.

def flunk(workitem, err_class_or_instance, *err_arguments)

      r = remove_workitem('reject', workitem)

      return flunk(workitem) if r != nil

      workitem.h.delete('_rev')

      super(workitem, err_class_or_instance, *err_arguments)
    end

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

Instruction: Given a code description, retrieve the corresponding code.


private void npnReceived(ServerHello mesg) throws IOException
    {
        NextProtoNegoExtension extension = (NextProtoNegoExtension)mesg.extensions.get(ExtensionType.EXT_NEXT_PROTOCOL_NEGOTIATION);
        if (extension != null)
        {
            protocols = extension.getProtocols();
            if (NextProtoNego.debug)
                System.err.println(new StringBuilder("[C] NPN protocols ").append(protocols).append(" received from server for ").append(conn != null ? conn : engine));
        }
        else
        {
            if (NextProtoNego.debug)
                System.err.println(new StringBuilder("[C] NPN protocols not sent by server for ").append(conn != null ? conn : engine));
        }
    }

func (s *NodeGroup) SetPrimaryEndpoint(v *Endpoint) *NodeGroup {
	s.PrimaryEndpoint = v
	return s
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
CBLDatabase+LocalDocs.m
- (CBLStatus) deleteLocalDocumentWithID: (NSString*)docID
revisionID: (NSString*)revID
obeyMVCC: (BOOL)obeyMVCC;

private Status deleteLocalDocument(
            final String inDocID, String inRevID, final boolean obeyMVCC) {
        final String docID = inDocID;
        final String revID = inRevID;

        if (docID == null || !docID.startsWith("_local/"))
            return new Status(Status.BAD_ID);
        if (obeyMVCC && revID == null)
            // Didn't specify a revision to delete: 404 or a 409, depending
            return new Status(getLocalDocument(docID, null) != null ?
                    Status.CONFLICT : Status.NOT_FOUND);

        return inTransaction(new Task() {
            @Override
            public Status run() {
                try {
                    byte[][] metaNbody = forest.rawGet("_local", docID);
                    if (metaNbody == null) {
                        return new Status(Status.NOT_FOUND);
                    } else if (obeyMVCC && revID != null &&
                            !revID.equals(new String(metaNbody[0]))) {
                        return new Status(Status.CONFLICT);
                    } else {
                        forest.rawPut("_local", docID, null, null);
                        return new Status(Status.OK);
                    }
                } catch (ForestException e) {
                    return ForestBridge.err2status(e);
                }
            }
        });
    }

private function findById($id, bool $includeData = true) : ?array
    {
        [$idField] = $fields = $this->getFields();

        if (! $includeData) {
            $key = array_search(static::DATA_FIELD, $fields);
            unset($fields[$key]);
        }

        $statement = $this->sqlite->prepare(sprintf(
            'SELECT %s FROM %s WHERE %s = :id LIMIT 1',
            implode(',', $fields),
            $this->table,
            $idField
        ));

        $statement->bindValue(':id', $id, SQLITE3_TEXT);

        $item = $statement->execute()->fetchArray(SQLITE3_ASSOC);

        if ($item === false) {
            return null;
        }

        if ($this->isExpired($item)) {
            $this->doDelete($id);

            return null;
        }

        return $item;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // RegisterAgent adds a new agent to the running instance

func (srv *Instance) RegisterAgent(ctx context.Context, name string, agent agents.Agent) error {
	return srv.agents.RegisterAgent(ctx, name, agent, srv.connector)
}

def add_actors(self, actor):

        if isinstance(actor, list):
            self.actors.extend(actor)
        elif isinstance(actor, Actor):
            self.actors.append(actor)
        return self

Instruction: Given a code description, retrieve the corresponding code.


Question:
// MultiAt2d computes 2D Multi-Octave Simplex noise. For each octave, a higher
// frequency/lower amplitude function will be added to the original. The higher
// the persistence [0, 1], the more of each succeeding octave will be added.

func MultiAt2d(oct int, p, f, x, y float64) float64 {
	var (
		total        float64
		amplitude    float64 = 1.0
		maxAmplitude float64
	)

	for i := 0; i < oct; i++ {
		total += At2d(x*f, y*f) * amplitude
		f *= 2.0
		maxAmplitude += amplitude
		amplitude *= p
	}

	return total / maxAmplitude
}

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Info for existing key.
//
// keyIdentity is the unique identifier of the Key.

func (c *Client) KeyInfo(keyIdentity string) (*Key, error) {
	var key Key
	return &key, c.Get(&key, "/account/keys/"+keyIdentity)
}

public function validateResponseSignature(\Yubikey\Response $response)
    {
        $params = array();
        foreach ($response->getProperties() as $property) {
            $value = $response->$property;
            if ($value !== null) {
                $params[$property] = $value;
            }
        }
        ksort($params);

        $signature = $this->generateSignature($params);
        return $this->hash_equals($signature, $response->getHash(true));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// getTransmitRange returns a pair of min/max values for transmit values
// represented by the current queue contents. Both values represent actual
// transmit values on the interval [0, len). You must already hold the mutex.

func (q *TransmitLimitedQueue) getTransmitRange() (minTransmit, maxTransmit int) {
	if q.lenLocked() == 0 {
		return 0, 0
	}
	minItem, maxItem := q.tq.Min(), q.tq.Max()
	if minItem == nil || maxItem == nil {
		return 0, 0
	}

	min := minItem.(*limitedBroadcast).transmits
	max := maxItem.(*limitedBroadcast).transmits

	return min, max
}

func rescanBlockFilter(filter *wsClientFilter, block *btcutil.Block, params *chaincfg.Params) []string {
	var transactions []string

	filter.mu.Lock()
	for _, tx := range block.Transactions() {
		msgTx := tx.MsgTx()

		// Keep track of whether the transaction has already been added
		// to the result.  It shouldn't be added twice.
		added := false

		// Scan inputs if not a coinbase transaction.
		if !blockchain.IsCoinBaseTx(msgTx) {
			for _, input := range msgTx.TxIn {
				if !filter.existsUnspentOutPoint(&input.PreviousOutPoint) {
					continue
				}
				if !added {
					transactions = append(
						transactions,
						txHexString(msgTx))
					added = true
				}
			}
		}

		// Scan outputs.
		for i, output := range msgTx.TxOut {
			_, addrs, _, err := txscript.ExtractPkScriptAddrs(
				output.PkScript, params)
			if err != nil {
				continue
			}
			for _, a := range addrs {
				if !filter.existsAddress(a) {
					continue
				}

				op := wire.OutPoint{
					Hash:  *tx.Hash(),
					Index: uint32(i),
				}
				filter.addUnspentOutPoint(&op)

				if !added {
					transactions = append(
						transactions,
						txHexString(msgTx))
					added = true
				}
			}
		}
	}
	filter.mu.Unlock()

	return transactions
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Walks over object and escapes string, does not touch #multi.fields
@param  {Object} obj
@return {Object}

function iterateOverObject(obj) {
  const props = keys(obj);
  const output = {};
  props.forEach(function iterateOverProps(prop) {
    const val = obj[prop];
    const type = typeof val;
    if (type === 'string' && BLACK_LIST_PROPS.indexOf(prop) === -1) {
      output[prop] = escape(val);
    } else if (type === 'object') {
      if (prop !== '#multi') {
        output[prop] = iterateOverObject(val);
      } else {
        output[prop] = val;
        val.match = escape(val.match);
      }
    } else {
      output[prop] = val;
    }
  });

  return output;
}

public static <A> CollQuery<A> from(Path<A> path, Iterable<A> col) {
        return new CollQuery<Void>().from(path, col).select(path);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetEncryptionEntities sets the EncryptionEntities field's value.

func (s *FieldLevelEncryptionProfileSummary) SetEncryptionEntities(v *EncryptionEntities) *FieldLevelEncryptionProfileSummary {
	s.EncryptionEntities = v
	return s
}

@Override
	public void cacheResult(List<CPAttachmentFileEntry> cpAttachmentFileEntries) {
		for (CPAttachmentFileEntry cpAttachmentFileEntry : cpAttachmentFileEntries) {
			if (entityCache.getResult(
						CPAttachmentFileEntryModelImpl.ENTITY_CACHE_ENABLED,
						CPAttachmentFileEntryImpl.class,
						cpAttachmentFileEntry.getPrimaryKey()) == null) {
				cacheResult(cpAttachmentFileEntry);
			}
			else {
				cpAttachmentFileEntry.resetOriginalValues();
			}
		}
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
utility function to create layout with the default font. Size and
        alignment parameters are shortcuts to according functions of the
        pango.Layout

def create_layout(self, size = None):
        """"""
        if not self.context:
            # TODO - this is rather sloppy as far as exception goes
            #        should explain better
            raise Exception("Can not create layout without existing context!")

        layout = pangocairo.create_layout(self.context)
        font_desc = pango.FontDescription(_font_desc)
        if size: font_desc.set_absolute_size(size * pango.SCALE)

        layout.set_font_description(font_desc)
        return layout

public BaseFontParameters getBaseFontParameters(String name) {
        String alias = (String)aliases.get(name);
        if (alias == null)
            return (BaseFontParameters)mapper.get(name);
        BaseFontParameters p = (BaseFontParameters)mapper.get(alias);
        if (p == null)
            return (BaseFontParameters)mapper.get(name);
        else
            return p;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return the value of the errorStyle property.

Contents: CSS style(s) to apply to any message
with a severity class of "ERROR".

public java.lang.String getErrorStyle() {
        return (java.lang.String) getStateHelper().eval(PropertyKeys.errorStyle);

    }

func (vr *ValidationResult) Log(ctx context.Context) {
	for _, msg := range vr.Messages {
		lvl := logging.Info
		switch msg.Severity {
		case "WARNING":
			lvl = logging.Warning
		case "ERROR", "CRITICAL":
			lvl = logging.Error
		}
		logging.Logf(ctx, lvl, "%s: %s", msg.Path, msg.Text)
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets product SKU combinations data
@param array $product

protected function setSkuCombinationProduct(array &$product)
    {
        if (!empty($product['combination'])) {
            foreach ($product['combination'] as &$combination) {

                $combination['path'] = $combination['thumb'] = '';

                if (!empty($product['images'][$combination['file_id']])) {
                    $combination['path'] = $product['images'][$combination['file_id']]['path'];
                    $this->setItemThumb($combination, $this->image);
                }

                $combination['price'] = $this->price->decimal($combination['price'], $product['currency']);
            }
        }
    }

protected function getShipppingData($options)
    {
        parent::addEntry(
            $options['id'],
            $options['number'],
            'shipping',
            new DateTime($options['date']),
            parent::getRoute($options['id'], 'shipping', 'details'),
            Shipping::$pdfBaseUrl
        );
    }

Instruction: Given a code description, retrieve the corresponding code.