Question: Returns list of supported hooks.

protected function supportedHooks() {
    return array_map(function ($file) {
      return pathinfo($file, PATHINFO_FILENAME);
    }, array_diff(scandir($this->templatePath . '/d8/hook'), ['.', '..']));
  }

def lambda_handler(event, context):
    '''
    '''
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
    try:
        # Calls rekognition DetectFaces API to detect faces in S3 object
        response = detect_faces(bucket, key)

        # Calls rekognition DetectLabels API to detect labels in S3 object
        #response = detect_labels(bucket, key)

        # Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection
        #response = index_faces(bucket, key)

        # Print response to console.
        print(response)

        return response
    except Exception as e:
        print(e)
        print("Error processing object {} from bucket {}. ".format(key, bucket) +
              "Make sure your object and bucket exist and your bucket is in the same region as this function.")
        raise e

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


Question:
select 字段 from t_table, 不包含where子句及以后的语句
@param clazz
@param selectOnlyKey 是否只查询key
@param withSQL_CALC_FOUND_ROWS 查询是否带上SQL_CALC_FOUND_ROWS，当配合select FOUND_ROWS();时需要为true
@return

public static String getSelectSQL(Class<?> clazz, boolean selectOnlyKey, boolean withSQL_CALC_FOUND_ROWS) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		if(withSQL_CALC_FOUND_ROWS) {
			sql.append("SQL_CALC_FOUND_ROWS ");
		}

		// 处理join方式clazz
		JoinTable joinTable = DOInfoReader.getJoinTable(clazz);
		if(joinTable != null) {
			Field leftTableField = DOInfoReader.getJoinLeftTable(clazz);
			Field rightTableField = DOInfoReader.getJoinRightTable(clazz);

			JoinLeftTable joinLeftTable = leftTableField.getAnnotation(JoinLeftTable.class);
			JoinRightTable joinRightTable = rightTableField.getAnnotation(JoinRightTable.class);

	        Table table1 = DOInfoReader.getTable(leftTableField.getType());
	        List<Field> fields1 = DOInfoReader.getColumnsForSelect(leftTableField.getType(), selectOnlyKey);

	        Table table2 = DOInfoReader.getTable(rightTableField.getType());
	        List<Field> fields2 = DOInfoReader.getColumnsForSelect(rightTableField.getType(), selectOnlyKey);

	        sql.append(join(fields1, ",", joinLeftTable.alias() + "."));
	        sql.append(",");
	        sql.append(join(fields2, ",", joinRightTable.alias() + "."));
	        sql.append(" FROM ").append(getTableName(table1))
	           .append(" ").append(joinLeftTable.alias()).append(" ");
	        sql.append(joinTable.joinType().getCode()).append(" ");
	        sql.append(getTableName(table2)).append(" ").append(joinRightTable.alias());
	        if(joinTable.on() == null || joinTable.on().trim().isEmpty()) {
	        	throw new OnConditionIsNeedException("join table :" + clazz.getName());
	        }
	        sql.append(" on ").append(joinTable.on().trim());

		} else {
			Table table = DOInfoReader.getTable(clazz);
			List<Field> fields = DOInfoReader.getColumnsForSelect(clazz, selectOnlyKey);

			sql.append(join(fields, ","));
			sql.append(" FROM ").append(getTableName(table)).append(" ").append(table.alias());
		}

		return sql.toString();
	}

public function updateTable($meta, ...$args)
    {
        $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta;
        if (!$meta->canUpdate) {
            throw new Exception("Meta {$meta->id} prohibits update");
        }

        $query = Query\Update::fromParamArgs($args);
        if (!$query->set) {
            throw new \InvalidArgumentException("Query missing 'set' values");
        }

        list ($sql, $params, $setProps, $whereProps) = $query->buildQuery($meta);
        if ($setProps) {
            $params = $this->mapper->formatParams($meta, $setProps, $params);
        }
        if ($whereProps) {
            $params = $this->mapper->formatParams($meta, $whereProps, $params);
        }

        return $this->getConnector()->exec($sql, $params);
    }

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


Question: Marshall the given parameter object.

public void marshall(DeploymentGroupInfo deploymentGroupInfo, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(deploymentGroupInfo.getApplicationName(), APPLICATIONNAME_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentGroupId(), DEPLOYMENTGROUPID_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentGroupName(), DEPLOYMENTGROUPNAME_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentConfigName(), DEPLOYMENTCONFIGNAME_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getEc2TagFilters(), EC2TAGFILTERS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getOnPremisesInstanceTagFilters(), ONPREMISESINSTANCETAGFILTERS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getAutoScalingGroups(), AUTOSCALINGGROUPS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getServiceRoleArn(), SERVICEROLEARN_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getTargetRevision(), TARGETREVISION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getTriggerConfigurations(), TRIGGERCONFIGURATIONS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getAlarmConfiguration(), ALARMCONFIGURATION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getAutoRollbackConfiguration(), AUTOROLLBACKCONFIGURATION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentStyle(), DEPLOYMENTSTYLE_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getBlueGreenDeploymentConfiguration(), BLUEGREENDEPLOYMENTCONFIGURATION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getLoadBalancerInfo(), LOADBALANCERINFO_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getLastSuccessfulDeployment(), LASTSUCCESSFULDEPLOYMENT_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getLastAttemptedDeployment(), LASTATTEMPTEDDEPLOYMENT_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getEc2TagSet(), EC2TAGSET_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getOnPremisesTagSet(), ONPREMISESTAGSET_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getComputePlatform(), COMPUTEPLATFORM_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getEcsServices(), ECSSERVICES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
Decide the slices for each context according to the workload.

        Parameters
        ----------
        data_shapes : list
            list of (name, shape) specifying the shapes for the input data or label.

def decide_slices(self, data_shapes):

        assert len(data_shapes) > 0
        major_axis = [DataDesc.get_batch_axis(x.layout) for x in data_shapes]

        for (name, shape), axis in zip(data_shapes, major_axis):
            if axis == -1:
                continue

            batch_size = shape[axis]
            if self.batch_size is not None:
                assert batch_size == self.batch_size, ("all data must have the same batch size: "
                                                       + ("batch_size = %d, but " % self.batch_size)
                                                       + ("%s has shape %s" % (name, shape)))
            else:
                self.batch_size = batch_size
                self.slices = _split_input_slice(self.batch_size, self.workload)

        return major_axis

def lstm_attention_base():
  """"""
  hparams = lstm_seq2seq()
  hparams.add_hparam("attention_layer_size", hparams.hidden_size)
  hparams.add_hparam("output_attention", True)
  hparams.add_hparam("num_heads", 1)
  return hparams

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


Question: Generate a resource for ``create`` or ``update``.

def _build_resource(self):
        """"""
        resource = {"name": self.name}

        if self.dns_name is not None:
            resource["dnsName"] = self.dns_name

        if self.description is not None:
            resource["description"] = self.description

        if self.name_server_set is not None:
            resource["nameServerSet"] = self.name_server_set

        return resource

func (m *MockProviderClient) ApplyResourceChange(arg0 context.Context, arg1 *tfplugin5.ApplyResourceChange_Request, arg2 ...grpc.CallOption) (*tfplugin5.ApplyResourceChange_Response, error) {
	m.ctrl.T.Helper()
	varargs := []interface{}{arg0, arg1}
	for _, a := range arg2 {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "ApplyResourceChange", varargs...)
	ret0, _ := ret[0].(*tfplugin5.ApplyResourceChange_Response)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

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


Question:
Retrieves information about the file entry.

    Returns:
      VFSStat: a stat object or None if not available.

def _GetStat(self):

    stat_object = super(OSFileEntry, self)._GetStat()

    if not self._is_windows_device:
      # File data stat information.
      stat_object.size = self._stat_info.st_size

      # Ownership and permissions stat information.
      stat_object.mode = stat.S_IMODE(self._stat_info.st_mode)
      stat_object.uid = self._stat_info.st_uid
      stat_object.gid = self._stat_info.st_gid

      # Other stat information.
      stat_object.ino = self._stat_info.st_ino
      # stat_info.st_dev
      # stat_info.st_nlink

    return stat_object

def char(self, char):

        font_files = fc.query()
        if self._display['group']:
            font_files = self._getCharFont(font_files, char)
            font_families = self._groupFontByFamily(font_files)
            for font_family in sorted(font_families):
                print(font_family)
                if self._display['list']:
                    for font_file in font_families[font_family]:
                        print('  '+font_file)
            self._fontSummary(len(font_files), len(font_families))
        else:
            font_files = self._getCharFont(font_files, char)
            for font_file in sorted(font_files):
                print(font_file)
            self._fontSummary(len(font_files))

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


Question: helper for gap encoding.

private static byte[] bitSetToByteArray(BitSet bitSet) {

    while (bitSet.length() % 8 != 0) { bitSet.set(bitSet.length(), true); }

    byte[] array = new byte[bitSet.length()/8];

    for (int i = 0; i < array.length; i++) {
      int offset = i * 8;

      int index = 0;
      for (int j = 0; j < 8; j++) {
        index <<= 1;
        if (bitSet.get(offset+j)) { index++; }
      }

      array[i] = (byte)(index - 128);
    }

    return array;
  }

def pkcs7_unpad(buf):
    # type: (bytes) -> bytes

    unpadder = cryptography.hazmat.primitives.padding.PKCS7(
        cryptography.hazmat.primitives.ciphers.
        algorithms.AES.block_size).unpadder()
    return unpadder.update(buf) + unpadder.finalize()

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


Question: (Internal) Attempts to initialise all ismods and start the event loop

function(){
		if(shuttingDown == true)
			return;
		modules.logger.log("startup","ISNode System > Loading Dependencies...");
		loadCriticalModules();
		loadNonCriticalModules();
		loadInterfaceModules();
		startEventLoop();
		return true;
	}

final public function init() {
		if ($this->request_initted)
			return;
		$this->init_request();
		if ($this->auto_shutdown)
			register_shutdown_function([$this, 'shutdown']);
		$this->request_initted = true;
		return $this;
	}

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


Question: Serializes the {@code message} into a byte array using the given {@code schema}.

public static <T> byte[] toByteArray(T message, Schema<T> schema, boolean numeric)
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try
        {
            writeTo(baos, message, schema, numeric);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Serializing to a byte array threw an IOException " +
                    "(should never happen).", e);
        }
        return baos.toByteArray();
    }

def capture_setting(self, sbp_msg, **metadata):

        if sbp_msg.msg_type == SBP_MSG_SETTINGS_READ_RESP:
            section, setting, value = sbp_msg.payload.split(b'\0')[:3]
            self.settings.append((section, setting, value))

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


Question:
@param ElementVersion         $elementVersion
@param string                 $language
@param TreeNodeInterface|null $node

@return array

public function fetch(ElementVersion $elementVersion, $language, TreeNodeInterface $node = null)
    {
        /* @var $links ElementLink[] */
        $links = $this->linkManager->findBy(['elementVersion' => $elementVersion, 'language' => $language]);

        if ($node) {
            foreach ($this->linkManager->findBy(['type' => 'link-internal', 'language' => $language, 'target' => $node->getId()]) as $link) {
                $incomingLink = clone $link;
                $incomingLink->setType('link-incoming');
                $links[] = $incomingLink;
            }
        }

        $results = array();

        foreach ($links as $link) {
            $data = [
                'id' => $link->getId(),
                'iconCls' => 'p-element-component-icon',
                'language' => $link->getLanguage(),
                'type' => $link->getType(),
                'title' => $link->getField(),
                'content' => $link->getTarget(),
                'link' => [],
                'raw' => $link->getTarget(),
                'payload' => [],
            ];

            $results[] = $this->linkTransformer->transform($link, $data);
        }

        return $results;
    }

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question:
Load a set of relationship counts onto the collection.

@param  array|string  $relations
@return $this

public function loadCount($relations)
    {
        if ($this->isEmpty()) {
            return $this;
        }

        $models = $this->first()->newModelQuery()
            ->whereKey($this->modelKeys())
            ->select($this->first()->getKeyName())
            ->withCount(...func_get_args())
            ->get();

        $attributes = Arr::except(
            array_keys($models->first()->getAttributes()),
            $models->first()->getKeyName()
        );

        $models->each(function ($model) use ($attributes) {
            $this->find($model->getKey())->forceFill(
                Arr::only($model->getAttributes(), $attributes)
            )->syncOriginalAttributes($attributes);
        });

        return $this;
    }

public static function addTags($tags)
    {
        self::updateAllCounters(['frequency' => 1], ['name' => $tags]);

        foreach ($tags as $name) {
            if (!self::find()->where(['name' => $name])->exists()) {
                (new self([
                    'name' => $name,
                    'frequency' => 1
                ]))->save();
            }
        }
    }

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


Question: Generate single key pair

function generateKeyPair (pub, prv) {
  try {
    mkdirp.sync(path.dirname(pub))
    mkdirp.sync(path.dirname(prv))

    childProcess.execFileSync('openssl', [
      'genrsa',
      '-out',
      prv,
      '4096'
    ], {
      stdio: 'ignore'
    })

    childProcess.execFileSync('openssl', [
      'rsa',
      '-pubout',
      '-in',
      prv,
      '-out',
      pub
    ], {
      stdio: 'ignore'
    })
  } catch (e) {
    throw new Error(
      'Failed to generate keys using OpenSSL. Please ensure you have OpenSSL ' +
      'installed and configured on your system.'
    )
  }
}

public function sealRequest(
        RequestInterface $request,
        SealingPublicKey $publicKey
    ): RequestInterface {
        $sealed = Simple::seal(
            (string) $request->getBody(),
            $publicKey
        );
        return $request->withBody(
            $this->adapter->stringToStream(
                Base64UrlSafe::encode($sealed)
            )
        );
    }

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


Question: This method defines some items which are declared by CodeIgniter

protected static function defineCharsetConstants()
    {
        /**
         * See vendor/codeigniter/framework/system/core/CodeIgniter.php for
         * details of what/why this is happening.
         */

        $sCharset = strtoupper(config_item('charset'));
        ini_set('default_charset', $sCharset);

        if (extension_loaded('mbstring')) {
            define('MB_ENABLED', true);
            @ini_set('mbstring.internal_encoding', $sCharset);
            mb_substitute_character('none');
        } else {
            define('MB_ENABLED', false);
        }

        if (extension_loaded('iconv')) {
            define('ICONV_ENABLED', true);
            @ini_set('iconv.internal_encoding', $sCharset);
        } else {
            define('ICONV_ENABLED', false);
        }

        if (is_php('5.6')) {
            ini_set('php.internal_encoding', $sCharset);
        }
    }

public function addCalculator(string $name, string $validation): void{
        $this->calculators[$name] = $validation;
    }

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


Question:
@return array

@throws AjaxException

protected function executeUpdateRecursive()
    {
        if (empty($this->postVar['pid']) || empty($this->postVar['field'])) {

            throw new AjaxException(
                'message.warning.incomplete_data_received.message',
                '[0x4FBF3C04]',
                HttpUtility::HTTP_STATUS_BAD_REQUEST
            );
        }

        $pid         = $this->postVar['pid'];
        $sysLanguage = (int)$this->postVar['sysLanguage'];

        $page = $this->getPageSeoDao()->getPageById($pid);

        $list = $this->getPageSeoDao()->index($page, 999, $sysLanguage, array());

        $count = 0;
        foreach ($list as $key => $page) {
            $this->postVar['pid'] = $key;
            $this->executeUpdate();
            $count++;
        }

        return array(
            'updateCount' => $count,  //not in use yet
        );
    }

public static function retError($value, $http_code = HttpCodes::HTTP_BAD_REQUEST, $prettyPrint = false)
    {
        $response = self::buildResponse($value, false, $http_code);

        return self::retJSON($response, $prettyPrint);
    }

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


Question: // SetDateCreated sets the DateCreated field's value.

func (s *LifecyclePolicy) SetDateCreated(v time.Time) *LifecyclePolicy {
	s.DateCreated = &v
	return s
}

function created($new = null)
    {
        if (isset($new) && ($this->_attributes['created'] != $new)){
            $this->change('created', (int)$new);
        }
        return $this->_attributes['created'];
    }

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


Question: Return a dict of Tensors from a serialized tensorflow.Example.

def decode_example(self, serialized_example):
    """"""
    data_fields, data_items_to_decoders = self.example_reading_spec()
    # Necessary to rejoin examples in the correct order with the Cloud ML Engine
    # batch prediction API.
    data_fields["batch_prediction_key"] = tf.FixedLenFeature([1], tf.int64, 0)
    if data_items_to_decoders is None:
      data_items_to_decoders = {
          field: tf.contrib.slim.tfexample_decoder.Tensor(field)
          for field in data_fields
      }

    decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(
        data_fields, data_items_to_decoders)

    decode_items = list(sorted(data_items_to_decoders))
    decoded = decoder.decode(serialized_example, items=decode_items)
    return dict(zip(decode_items, decoded))

def write_to_directory(self, dataset_info_dir):
    """"""
    # Save the metadata from the features (vocabulary, labels,...)
    if self.features:
      self.features.save_metadata(dataset_info_dir)

    if self.redistribution_info.license:
      with tf.io.gfile.GFile(self._license_filename(dataset_info_dir),
                             "w") as f:
        f.write(self.redistribution_info.license)

    with tf.io.gfile.GFile(self._dataset_info_filename(dataset_info_dir),
                           "w") as f:
      f.write(self.as_json)

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


Question:
Initializes object with SORT command response

@param string $data IMAP response string

public function add($result)
    {
        $this->sets[] = $result;

        if ($result->count()) {
            $this->append_result($result);
        }
        else if ($result->incomplete) {
            $this->incomplete = true;
        }
    }

func (mmap MarshalMap) Array(key string) ([]interface{}, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	arrayValue, isArray := val.([]interface{})
	if !isArray {
		return nil, fmt.Errorf(`"%s" is expected to be an array`, key)
	}
	return arrayValue, nil
}

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


Question: /*Line 797 - 'AtomControl.js'

function (element, key, value, twoWays, vf, events) {

/*Line 799 - 'AtomControl.js' */                if (value == null) {
/*Line 800 - 'AtomControl.js' */                    // remove existing binding...
/*Line 801 - 'AtomControl.js' */                    this.clearBinding(element, key);
/*Line 802 - 'AtomControl.js' */                    return;
/*Line 803 - 'AtomControl.js' */                }

/*Line 805 - 'AtomControl.js' */                var target = this;
/*Line 806 - 'AtomControl.js' */                if (value && value.constructor == String && /^window\./g.test(value)) {
/*Line 807 - 'AtomControl.js' */                    target = window;
/*Line 808 - 'AtomControl.js' */                }

/*Line 810 - 'AtomControl.js' */                var thisElement = this.get_element();

/*Line 812 - 'AtomControl.js' */                var jq = thisElement != element;

/*Line 814 - 'AtomControl.js' */                if (!jq) {
/*Line 815 - 'AtomControl.js' */                    var f = this["get_" + key];
/*Line 816 - 'AtomControl.js' */                    if (f == undefined || f == null) {
/*Line 817 - 'AtomControl.js' */                        jq = true;
/*Line 818 - 'AtomControl.js' */                    }
/*Line 819 - 'AtomControl.js' */                }

/*Line 821 - 'AtomControl.js' */                switch (key) {
/*Line 822 - 'AtomControl.js' */                    case "value":
/*Line 823 - 'AtomControl.js' */                        if (/input/gi.test(element.nodeName)) { jq = true; }
/*Line 824 - 'AtomControl.js' */                        this.addBinding(target, element, "value", value, twoWays, jq, vf, events);
/*Line 825 - 'AtomControl.js' */                        break;
/*Line 826 - 'AtomControl.js' */                    case "text":
/*Line 827 - 'AtomControl.js' */                        this.addBinding(target, element, "text", value, false, true, vf, events);
/*Line 828 - 'AtomControl.js' */                        break;
/*Line 829 - 'AtomControl.js' */                    default:
/*Line 830 - 'AtomControl.js' */                        this.addBinding(target, element, key, value, twoWays, jq, vf, events);
/*Line 831 - 'AtomControl.js' */                        break;
/*Line 832 - 'AtomControl.js' */                }

/*Line 834 - 'AtomControl.js' */            }

function() {
    var ce=this.childElements;
    if (!ce || !ce.length) {
      return;
    }
    var cw;
    for (var i=0,sz=ce.length;sz>i;i++) {
      cw=ce[i].ctlWrapper;
      if (cw && !cw.initialized) {
        cw.init(null,this.controller);
      }
    }
  }

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


Question:
Scroll to the next page. To process the scrolling by pages LayoutScroller must be constructed
with a pageSize greater than zero.
@return the new current item after the scrolling processed.

public int scrollToNextPage() {
        Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "scrollToNextPage getCurrentPage() = %d currentIndex = %d",
                getCurrentPage(), mCurrentItemIndex);

        if (mSupportScrollByPage) {
            scrollToPage(getCurrentPage() + 1);
        } else {
            Log.w(TAG, "Pagination is not enabled!");
        }

        return mCurrentItemIndex;
	}

protected void breakUpContainer() {

        List<String> clientIds = new ArrayList<String>();
        for (Widget w : getGroupContainerWidget()) {
            if (w instanceof CmsContainerPageElementPanel) {
                CmsContainerPageElementPanel elementWidget = (CmsContainerPageElementPanel)w;
                if ((elementWidget.getInheritanceInfo() == null) || elementWidget.getInheritanceInfo().isVisible()) {
                    clientIds.add(elementWidget.getId());
                }
            }
        }
        int index = getIndexPosition();
        for (String clientId : clientIds) {
            try {
                CmsContainerElementData elementData = getController().getCachedElement(clientId);
                CmsContainerPageElementPanel containerElement = getController().getContainerpageUtil().createElement(
                    elementData,
                    getParentContainer(),
                    false);
                getParentContainer().insert(containerElement, index);
                index++;
            } catch (Exception e) {
                CmsDebugLog.getInstance().printLine(e.getMessage());
            }
        }
        getController().addToRecentList(getGroupContainerWidget().getId(), null);
        getController().unlockResource(
            new CmsUUID(CmsContainerpageController.getServerId(m_elementData.getClientId())));
        closeDialog(true);
        getController().setPageChanged();
    }

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


Question:
Creates the sub query from group hit.

@param subHit
the sub hit
@param reverse
the reverse
@param field
the field
@return the mtas span query

private static MtasSpanQuery createSubQueryFromGroupHit(List<String>[] subHit,
      boolean reverse, String field) {
    MtasSpanQuery query = null;
    if (subHit != null && subHit.length > 0) {
      List<MtasSpanSequenceItem> items = new ArrayList<>();
      List<String> subHitItem;
      for (int i = 0; i < subHit.length; i++) {
        MtasSpanQuery item = null;
        if (reverse) {
          subHitItem = subHit[(subHit.length - i - 1)];
        } else {
          subHitItem = subHit[i];
        }
        if (subHitItem.isEmpty()) {
          item = new MtasSpanMatchAllQuery(field);
        } else if (subHitItem.size() == 1) {
          Term term = new Term(field, subHitItem.get(0));
          item = new MtasSpanTermQuery(term);
        } else {
          MtasSpanQuery[] subList = new MtasSpanQuery[subHitItem.size()];
          for (int j = 0; j < subHitItem.size(); j++) {
            Term term = new Term(field, subHitItem.get(j));
            subList[j] = new MtasSpanTermQuery(term);
          }
          item = new MtasSpanAndQuery(subList);
        }
        items.add(new MtasSpanSequenceItem(item, false));
      }
      query = new MtasSpanSequenceQuery(items, null, null);
    }
    return query;
  }

def check_meta(pfeed, *, as_df=False, include_warnings=False):

    table = 'meta'
    problems = []

    # Preliminary checks
    if pfeed.meta is None:
        problems.append(['error', 'Missing table', table, []])
    else:
        f = pfeed.meta.copy()
        problems = check_for_required_columns(problems, table, f)
    if problems:
        return gt.format_problems(problems, as_df=as_df)

    if include_warnings:
        problems = check_for_invalid_columns(problems, table, f)

    if f.shape[0] > 1:
        problems.append(['error', 'Meta must have only one row',
          table, list(range(1, f.shape[0]))])

    # Check agency_name
    problems = gt.check_column(problems, table, f, 'agency_name', gt.valid_str)

    # Check agency_url
    problems = gt.check_column(problems, table, f, 'agency_url', gt.valid_url)

    # Check agency_timezone
    problems = gt.check_column(problems, table, f, 'agency_timezone',
      gt.valid_timezone)

    # Check start_date and end_date
    for col in ['start_date', 'end_date']:
        problems = gt.check_column(problems, table, f, col, gt.valid_date)

    # Check default_route_speed
    problems = gt.check_column(problems, table, f, 'default_route_speed',
      valid_speed)

    return gt.format_problems(problems, as_df=as_df)

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


Question: we elevate every node to an entity and set parent pointers

protected function convertNodes(Array $nodes, $em) {
    // our test project (this) is defined to have only de as i18n but dont get confused, these are english wordings
    $navigationNodes = array();

    foreach ($nodes as $node) {
      $node = (object) $node;
      $navigationNode = $this->createNode(array('de'=>$node->title));
      $navigationNode->setContext($this->context);
      $navigationNode->generateSlugs();

      $page = $this->createPage($navigationNode->getSlug('de'));
      $page->setActive(TRUE);
      $em->persist($page);

      $navigationNode->setPage($page);

      $navigationNodes[$navigationNode->getTitle('de')] = $navigationNode;
    }

    foreach ($nodes as $node) {
      $node = (object) $node;

      if (isset($node->parent)) {
        $navigationNodes[$node->title]->setParent($navigationNodes[$node->parent]);
      }
    }

    return $navigationNodes;
  }

protected function createNodeArray( \Aimeos\MShop\Locale\Item\Site\Iface $item )
	{
		$result = $item->toArray( true );

		if( method_exists( $item, 'getChildren' ) )
		{
			foreach( $item->getChildren() as $child ) {
				$result['children'][] = $this->createNodeArray( $child );
			}
		}

		return (object) $result;
	}

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


Question:
// PasscodePrompt returns a prompt to tell the user where to get a passcode from.
// If not present in the metadata (PCF installation don't seem to return it), will attempt to
// contruct a plausible URL.

func (md *Metadata) PasscodePrompt() string {
	// Give default in case server doesn't tell us
	if len(md.Prompts.Passcode) == 2 && md.Prompts.Passcode[1] != "" {
		return md.Prompts.Passcode[1]
	}
	var loginURL string
	if md.Links.Login != "" {
		loginURL = md.Links.Login
	} else {
		loginURL = "https://login.system.example.com"
	}
	return fmt.Sprintf("One Time Code ( Get one at %s/passcode )", loginURL)
}

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question:
// validateArgs is a checker to ensure tests are not running commands which are
// not supported on platforms. Specifically on Windows this is 'busybox top'.

func validateArgs(args ...string) error {
	if testEnv.OSType != "windows" {
		return nil
	}
	foundBusybox := -1
	for key, value := range args {
		if strings.ToLower(value) == "busybox" {
			foundBusybox = key
		}
		if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
			return errors.New("cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
		}
	}
	return nil
}

public SassValue invoke(List<?> arguments) {
    try {
      ArrayList<Object> values = new ArrayList<>(argumentConverters.size());

      for (ArgumentConverter argumentConverter : argumentConverters) {
        Object value = argumentConverter.convert(arguments, importStack, context);
        values.add(value);
      }

      Object result = method.invoke(object, values.toArray());

      return TypeUtils.convertToSassValue(result);
    } catch (Throwable throwable) {
      StringWriter stringWriter = new StringWriter();
      PrintWriter printWriter = new PrintWriter(stringWriter);

      String message = throwable.getMessage();
      if (StringUtils.isNotEmpty(message)) {
        printWriter.append(message).append(System.lineSeparator());
      }
      throwable.printStackTrace(printWriter);

      return new SassError(stringWriter.toString());
    }
  }

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


Question: // SetInputCaptions sets the InputCaptions field's value.

func (s *JobInput) SetInputCaptions(v *InputCaptions) *JobInput {
	s.InputCaptions = v
	return s
}

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


Question: // MarshalBinary interface implementation

func (m *Client) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

func (eui *EUI64) UnmarshalBinary(data []byte) error {
	if len(data) != 8 {
		return errors.New("ttn/core: Invalid length for EUI64")
	}
	copy(eui[:], data)
	return nil
}

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


Question: Re-initialize the sampler.

def reset(self):
        """"""

        # sampling
        self.it = 1
        self.batch = 0
        self.ncall = 0
        self.bound = []
        self.eff = 1.
        self.base = False

        # results
        self.saved_id = []
        self.saved_u = []
        self.saved_v = []
        self.saved_logl = []
        self.saved_logvol = []
        self.saved_logwt = []
        self.saved_logz = []
        self.saved_logzvar = []
        self.saved_h = []
        self.saved_nc = []
        self.saved_boundidx = []
        self.saved_it = []
        self.saved_n = []
        self.saved_bounditer = []
        self.saved_scale = []
        self.saved_batch = []
        self.saved_batch_nlive = []
        self.saved_batch_bounds = []

        # results from our base run
        self.base_id = []
        self.base_u = []
        self.base_v = []
        self.base_logl = []
        self.base_logvol = []
        self.base_logwt = []
        self.base_logz = []
        self.base_logzvar = []
        self.base_h = []
        self.base_nc = []
        self.base_boundidx = []
        self.base_it = []
        self.base_n = []
        self.base_bounditer = []
        self.base_scale = []

        # results from our most recent addition
        self.new_id = []
        self.new_u = []
        self.new_v = []
        self.new_logl = []
        self.new_nc = []
        self.new_it = []
        self.new_n = []
        self.new_boundidx = []
        self.new_bounditer = []
        self.new_scale = []
        self.new_logl_min, self.new_logl_max = -np.inf, np.inf

@Override
  public void invoke(InboxAmp inbox, StubAmp actor)
  {
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();

    try {
      thread.setContextClassLoader(_loader);

      getDelegate().invoke(inbox, actor);
    } finally {
      thread.setContextClassLoader(oldLoader);
    }
  }

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


Question:
Build a factory

@param string  $name   factory name
@param boolean $create create factory

@return mixed factory

public static function build($name, $create = false)
    {
        self::load();
        $data = self::attributes_for($name);
        if (!$data) {
            return null;
        }

        // if is a different class ...
        if (is_array(self::$_options[$name])
            && array_key_exists("class_name", self::$_options[$name])
        ) {
            $name = self::$_options[$name]["class_name"];
        }

        $cls = ucfirst(strtolower($name));
        $obj = new $cls();
        $pk  = $obj::getPK();

        if (!array_key_exists($pk, $data)) {
            $data[$pk] = null;
        }

        $obj = new $cls($data);
        if ($create) {
            if (!$obj->isValid()) {
                return null;
            }
            $obj->save();
        }
        return $obj;
    }

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:
@param MediaInterface $media
@param string         $filename

@return array|bool

protected function getAmazonBuilder(MediaInterface $media, $filename)
    {
        $adapter = $this->container->get($media->getProviderName())->getFilesystem()->getAdapter();

        //handle special Replicate adapter
        if ($adapter instanceof Replicate) {
            $adapterClassNames = $adapter->getAdapterClassNames();
        } else {
            $adapterClassNames = [\get_class($adapter)];
        }

        //for amazon s3
        if ((!\in_array(AmazonS3::class, $adapterClassNames, true) && !\in_array(AwsS3::class, $adapterClassNames, true)) || !$this->container->has('sonata.media.metadata.amazon')) {
            return false;
        }

        return $this->container->get('sonata.media.metadata.amazon')->get($media, $filename);
    }

public function output($image_type = null, $quality = null)
    {
        $image_type = $image_type ?: $this->source_type;

        header('Content-Type: ' . image_type_to_mime_type($image_type));

        $this->save(null, $image_type, $quality);
    }

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


Question:
Set a new Route or merge an existing group of routes.

@param Group|Route $route
@return self

public function set($route)
    {
        if ($route instanceof Group) {
            foreach ($route->all() as $r)
                $this->routes[] = $r;
        } else  $this->routes[] = $route;
        return  $this;
    }

protected function generateStandardUrl(array $urlParameters = array(), $absolute = false)
    {
        $urlParameters = $this->addRequestVariablesToUrlParameters($urlParameters);

        $anchor = '';
        if ($this->hasAnchor())
        {
            $anchor = '#'.$this->getAnchor();
        }

        return $this->getRouter()->generate($this->getRouteName(), $urlParameters, $absolute) . $anchor;
    }

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


Question: // SetEcsClusterName sets the EcsClusterName field's value.

func (s *EcsCluster) SetEcsClusterName(v string) *EcsCluster {
	s.EcsClusterName = &v
	return s
}

@Given("^I( securely)? connect to '(Cassandra|Mongo|Elasticsearch)' cluster at '(.+)'$")
    public void connect(String secured, String clusterType, String url) throws DBException, UnknownHostException {
        switch (clusterType) {
            case "Cassandra":
                commonspec.getCassandraClient().setHost(url);
                commonspec.getCassandraClient().connect(secured);
                break;
            case "Mongo":
                commonspec.getMongoDBClient().connect();
                break;
            case "Elasticsearch":
                LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>();
                settings_map.put("cluster.name", System.getProperty("ES_CLUSTER", ES_DEFAULT_CLUSTER_NAME));
                commonspec.getElasticSearchClient().setSettings(settings_map);
                commonspec.getElasticSearchClient().connect();
                break;
            default:
                throw new DBException("Unknown cluster type");
        }
    }

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


Question:
:return:
            The SHA1 hash of the DER-encoded bytes of this public key info

def sha1(self):

        if self._sha1 is None:
            self._sha1 = hashlib.sha1(byte_cls(self['public_key'])).digest()
        return self._sha1

def sign_response(challenge)
      client_data_json = client_data(::U2F::ClientData::AUTHENTICATION_TYP, challenge)
      JSON.dump(
        clientData: ::U2F.urlsafe_encode64(client_data_json),
        keyHandle: ::U2F.urlsafe_encode64(key_handle_raw),
        signatureData: auth_signature_data(client_data_json)
      )
    end

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


Question:
Used when archiving to serialize the Row's properties.
@return array
@ignore

public function export()
    {
        return array(
            self::COLUMNS => $this->getArrayCopy(),
            self::METADATA => $this->metadata,
            self::DATATABLE_ASSOCIATED => $this->subtableId,
        );
    }

protected function store(Request $request, Response $response)
    {
        try {
            $this->store->write($request, $response);

            $this->record($request, 'store');

            $response->headers->set('Age', $response->getAge());
        } catch (\Exception $e) {
            $this->record($request, 'store-failed');

            if ($this->options['debug']) {
                throw $e;
            }
        }

        // now that the response is cached, release the lock
        $this->store->unlock($request);
    }

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


Question:
/*
Actually constructs a Jide document component from the page component

private DocumentComponent constructDocumentComponent(final PageComponent pageComponent) {
    	String id = pageComponent.getId();
		String title = pageComponent.getDisplayName();
		Icon icon = pageComponent.getIcon();
		DocumentComponent document = new DocumentComponent(
				pageComponent.getContext().getPane().getControl(),
				id, title, icon);
		document.setTooltip(pageComponent.getDescription());
    	return document;
    }

public static boolean showDocument(URL url) {
        return showDocumentViaDesktop(url)
            || showDocumentViaExec(url)
            || JavaWebStart.showViaWebStart(url);
    }

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


Question:
Hydrate the update form for this object, before passing it to the update template

@param mixed $object

protected function hydrateObjectForm($object)
    {
        $data = array(
            "id" => $object->getId(),
            "visible" => (bool) $object->getVisible(),
            "code" => $object->getCode(),
            "title" => $object->getTitle(),
            "type" => $object->getType(),
            "entity" => $object->getEntity(),
            "serialized_columns" => $object->getSerializedColumns(),
            "serialized_condition" => $object->getSerializedCondition(),
            "index_engine_driver_configuration_id" => $object->getIndexEngineDriverConfigurationId(),
        );

        return $this->getUpdateForm($data);
    }

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
Find out if an associated Table has the Trash behaviour and it's records can be trashed

@param \Cake\ORM\Association $association The table association
@param \Cake\ORM\Table $table The table instance to check
@return bool

protected function _isRecursable(Association $association, Table $table)
    {
        if ($association->getTarget()->hasBehavior('Trash')
            && $association->isOwningSide($table)
            && $association->getDependent()
            && $association->getCascadeCallbacks()
        ) {
            return true;
        }

        return false;
    }

public function delete($options=array()) {
        $this->model  =   $options['model'];
        $this->parseBind(!empty($options['bind'])?$options['bind']:array());
        $sql   = 'DELETE FROM '
            .$this->parseTable($options['table'])
            .$this->parseWhere(!empty($options['where'])?$options['where']:'')
            .$this->parseLock(isset($options['lock'])?$options['lock']:false)
            .$this->parseComment(!empty($options['comment'])?$options['comment']:'');
        return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);
    }

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


Question:
Validate an images dimensions.

@param array $input
@param string $type
@param int $size
@return bool

public static function dimensions($input, $type, $size) {
        if (static::file($input)) {
            $input = $input['tmp_name'];
        }

        if (!file_exists($input)) {
            return false;
        }

        if ($file = getimagesize($input)) {
            $width = $file[0];
            $height = $file[1];

            switch ($type) {
                case 'width':       return ($width == $size);
                case 'height':      return ($height == $size);
                case 'maxWidth':    return ($width <= $size);
                case 'maxHeight':   return ($height <= $size);
                case 'minWidth':    return ($width >= $size);
                case 'minHeight':   return ($height >= $size);
            }
        }

        return false;
    }

function hasRegexp()
	{
		if ( !is_null( $this->attribute('passwordvalidationregexp' ) ) &&
			( $this->attribute( 'passwordvalidationregexp' ) != self::NOT_DEFINED ) &&
			( $this->attribute( 'passwordvalidationregexp' ) != '' ) )
		{
			return true;
		}
		else
		{
		    return false;
		}
	}

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


Question:
Returns or Creates a Vertex mapped by key.

    Args:
      key: A string reference for a vertex.  May refer to a new Vertex in which
      case it will be created.

    Returns:
      A the Vertex mapped to by key.

def get_vertex(self, key):

    if key in self.vertex_map:
      return self.vertex_map[key]
    vertex = self.new_vertex()
    self.vertex_map[key] = vertex
    return vertex

public static Result convert(final Object res) throws QConnectorException {
		if (res == null) {
			return new EmptyResult();
		}
		// table
		if (res instanceof c.Flip) {
			return new FlipResult("", (c.Flip) res);
		}
		// dict
		if (res instanceof c.Dict) {
			final c.Dict dict = (c.Dict) res;
			if ((dict.x instanceof c.Flip) && (dict.y instanceof c.Flip)) {
				final c.Flip key = (c.Flip) dict.x;
				final c.Flip data = (c.Flip) dict.y;
				return new FlipFlipResult("", key, data);
			}
		}
		if (res instanceof Object[]) {
			final Object[] oa = (Object[]) res;
			if ((oa.length == 2) && (oa[0] instanceof String) && (oa[1] instanceof c.Flip)) {
				final String table = (String) oa[0];
				final c.Flip flip = (c.Flip) oa[1];
				return new FlipResult(table, flip);
			} else if ((oa.length == 3) && (oa[1] instanceof String) && (oa[2] instanceof c.Flip)) {
				final String table = (String) oa[1];
				final c.Flip flip = (c.Flip) oa[2];
				return new FlipResult(table, flip);
			} else {
				return new ListResult<Object>(oa);
			}
		}
		// list
		if (res instanceof byte[]) {
			return new ListResult<Byte>(ArrayUtils.toObject((byte[]) res));
		}

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


Question:
@param \eZ\Publish\SPI\Persistence\Content $content

@return array|\eZ\Publish\SPI\Search\Document[]

private function getContentSubdocuments(Content $content)
    {
        if ($this->contentSubdocumentMapper->accept($content)) {
            return $this->contentSubdocumentMapper->mapDocuments($content);
        }

        return [];
    }

func processPredicate(ce ConsumedElement) (*predicate.Predicate, string, string, bool, error) {
	var (
		nP             *predicate.Predicate
		pID            string
		pAnchorBinding string
		temporal       bool
	)
	raw := ce.Token().Text
	p, err := predicate.Parse(raw)
	if err == nil {
		// A fully specified predicate was provided.
		nP = p
		return nP, pID, pAnchorBinding, nP.Type() == predicate.Temporal, nil
	}
	// The predicate may have a binding on the anchor.
	cmps := predicateRegexp.FindAllStringSubmatch(raw, 2)
	if len(cmps) != 1 || (len(cmps) == 1 && len(cmps[0]) != 3) {
		return nil, "", "", false, fmt.Errorf("failed to extract partially defined predicate %q, got %v instead", raw, cmps)
	}
	id, ta := cmps[0][1], cmps[0][2]
	pID = id
	if ta != "" {
		pAnchorBinding = ta
		temporal = true
	}
	return nil, pID, pAnchorBinding, temporal, nil
}

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


Question:
// DataFilled returns true if the request's data for response deserialization
// target has been set and is a valid. False is returned if data is not
// set, or is invalid.

func (r *Request) DataFilled() bool {
	return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid()
}

function(packedValue)
    {

        var result;

        var t = typeof(packedValue);
        if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
        {
            result = this.handleError(packedValue);
        }
        else if (packedValue instanceof Array)
        {
            result = [];
            for (var i = 0; i < packedValue.length; i++)
            {
                result[i] = this.deserialize(packedValue[i]);
            }
        }
        else if (t == "object")
        {
            for(var i = 0; i < packedValue.newTypes.length; i++)
            {
                this.addTypeDataToCache(packedValue.newTypes[i]);
            }
            for (var aRefID in packedValue.newRefs)
            {
                this.createProxy(aRefID, packedValue.newRefs[aRefID]);
            }
            if (packedValue.type == FABridge.TYPE_PRIMITIVE)
            {
                result = packedValue.value;
            }
            else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
            {
                result = this.getFunctionProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
            {
                result = this.getProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
            {
                result = packedValue.value;
            }
        }
        return result;
    }

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


Question:
Render pages and pattern-collection pages.

@param {Object} drizzleData  All data built so far
@return {Promise} resolving to drizzleData

function render(drizzleData) {
  return Promise.all([
    renderPages(drizzleData),
    renderCollections(drizzleData)
  ]).then(
    allData => {
      return {
        data: drizzleData.data,
        pages: allData[0],
        patterns: allData[1],
        templates: drizzleData.templates,
        options: drizzleData.options,
        tree: drizzleData.tree
      };
    },
    error => DrizzleError.error(error, drizzleData.options.debug)
  );
}

function __populate(jsonSchema, populate) {
  var pTree = normailizePopulationTree(populate);
  var path, model, subDoc, jss;
  for (path of pTree) {

    jss = findPath(jsonSchema, path.path);

    if (!jss.spec) continue;

    model = jss.spec['x-ref'] || path.model;
    if (!model) continue;
    try {
      if (typeof model === 'string') model = this.base.model(model);
    } catch(e) {
      continue;
    }
    subDoc = model.jsonSchema(path.select, path.populate);
    subDoc['x-ref'] = jss.spec['x-ref'];
    if (jss.spec.description) subDoc.description = jss.spec.description;
    if (jss.isArray) {
      jss.cont.items = subDoc;
    } else {
      jss.cont[jss.prop] = subDoc;
    }
  }
  return jsonSchema;
}

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


Question: // SetRange sets the Range field's value.

func (s *GetJobOutputInput) SetRange(v string) *GetJobOutputInput {
	s.Range = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question: Encodes a SemaphoreStr

def encode_str(s, mutable=False):
    """"""
    rv = ffi.new("SemaphoreStr *")
    if isinstance(s, text_type):
        s = s.encode("utf-8")
    if mutable:
        s = bytearray(s)
    rv.data = ffi.from_buffer(s)
    rv.len = len(s)
    # we have to hold a weak reference here to ensure our string does not
    # get collected before the string is used.
    attached_refs[rv] = s
    return rv

public static String[] getMethodSigsCache(String serviceName, String methodName) {
        ConcurrentHashMap<String, String[]> methods = NOT_OVERLOAD_METHOD_SIGS_CACHE.get(serviceName);
        return methods == null ? null : methods.get(methodName);
    }

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


Question:
for_stmt : FOR ident EQ expr SEMI stmt_list END_STMT
             | FOR LPAREN ident EQ expr RPAREN SEMI stmt_list END_STMT
             | FOR matrix EQ expr SEMI stmt_list END_STMT

def p_for_stmt(p):

    if len(p) == 8:
        if not isinstance(p[2], node.ident):
            raise_exception(SyntaxError, "Not implemented: for loop", new_lexer)
        p[2].props = "I"  # I= for-loop iteration variable
        p[0] = node.for_stmt(ident=p[2], expr=p[4], stmt_list=p[6])

def predicates(predicate, collection, klass, column_name, value)
      case predicate
      when :between
        klass.arel_table[column_name].between(value.first..value.last)
      when :does_not_match
        klass.arel_table[column_name].does_not_match("%#{value}%")
      when :does_not_match_all
        klass.arel_table[column_name].does_not_match_all(value)
      when :does_not_match_any
        klass.arel_table[column_name].does_not_match_any(value)
      when :eq
        klass.arel_table[column_name].eq(value)
      when :eq_all
        klass.arel_table[column_name].eq_all(value)
      when :eq_any
        klass.arel_table[column_name].eq_any(value)
      when :gt
        klass.arel_table[column_name].gt(value)
      when :gt_all
        klass.arel_table[column_name].gt_all(value)
      when :gt_any
        klass.arel_table[column_name].gt_any(value)
      when :gteq
        klass.arel_table[column_name].gteq(value)
      when :gteq_all
        klass.arel_table[column_name].gteq_all(value)
      when :gteq_any
        klass.arel_table[column_name].gteq_any(value)
      when :in
        klass.arel_table[column_name].in(value)
      when :in_all
        klass.arel_table[column_name].in_all(value)
      when :in_any
        klass.arel_table[column_name].in_any(value)
      when :lt
        klass.arel_table[column_name].lt(value)
      when :lt_all
        klass.arel_table[column_name].lt_all(value)
      when :lt_any
        klass.arel_table[column_name].lt_any(value)
      when :lteq
        klass.arel_table[column_name].lteq(value)
      when :lteq_all
        klass.arel_table[column_name].lteq_all(value)
      when :lteq_any
        klass.arel_table[column_name].lteq_any(value)
      when :ilike
        klass.arel_table[column_name].matches("%#{value}%")
      when :matches
        klass.arel_table[column_name].matches(value)
      when :matches_all
        klass.arel_table[column_name].matches_all(value)
      when :matches_any
        klass.arel_table[column_name].matches_any(value)
      when :not_between
        klass.arel_table[column_name].not_between(value.first..value.last)
      when :not_eq
        klass.arel_table[column_name].not_eq(value)
      when :not_eq_all
        klass.arel_table[column_name].not_eq_all(value)
      when :not_eq_any
        klass.arel_table[column_name].not_eq_any(value)
      when :not_in
        klass.arel_table[column_name].not_in(value)
      when :not_in_all
        klass.arel_table[column_name].not_in_all(value)
      when :not_in_any
        klass.arel_table[column_name].not_in_any(value)
      else
        unless predicate.respond_to?(:call)
          raise ArgumentError,
                "unsupported predicate `#{predicate}`"
        end

        predicate.call(collection, value)
      end
    end

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


Question:
@param      $rule
@param null $error_message

@return $this
@throws \Exception

protected function _rule($rule, $error_message = null) {
        if (!$this->field) {
            throw new \Exception('Not specified fieldname');
        }
        $this->rules[$this->field][$rule] = $rule;
        if ($error_message) {
            $this->message($rule, $error_message, $this->field);
        }

        return $this;
    }

private function configureFormatter(OutputFormatter $formatter)
    {
        $style = new OutputFormatterStyle('yellow', null, ['bold']);
        $formatter->setStyle('pathbold', $style);

        $style = new OutputFormatterStyle('green');
        $formatter->setStyle('localname', $style);

        $style = new OutputFormatterStyle(null, null, ['bold']);
        $formatter->setStyle('node', $style);

        $style = new OutputFormatterStyle('blue', null, ['bold']);
        $formatter->setStyle('templatenode', $style);

        $style = new OutputFormatterStyle('blue', null, []);
        $formatter->setStyle('templateproperty', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property', $style);

        $style = new OutputFormatterStyle('magenta', null, ['bold']);
        $formatter->setStyle('node-type', $style);

        $style = new OutputFormatterStyle('magenta', null, []);
        $formatter->setStyle('property-type', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property-value', $style);

        $style = new OutputFormatterStyle(null, 'red', []);
        $formatter->setStyle('exception', $style);
    }

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


Question: // Wrap an existing transport.

func Wrap(rwc io.ReadWriteCloser) (rv *Client, err error) {
	return &Client{
		conn:    rwc,
		healthy: true,
		hdrBuf:  make([]byte, gomemcached.HDR_LEN),
	}, nil
}

public Topology getNewInstance(final Class<? extends Name<String>> operatorName,
                                 final Class<? extends Topology> topologyClass) throws InjectionException {
    final Injector newInjector = injector.forkInjector();
    newInjector.bindVolatileParameter(OperatorNameClass.class, operatorName);
    return newInjector.getInstance(topologyClass);
  }

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


Question:
// Release releases the port back to the pool. Releasing an
// unallocated port or a port out of the range is a no-op and
// returns no error.

func (r *PortAllocator) Release(port int) error {
	ok, offset := r.contains(port)
	if !ok {
		klog.Warningf("port is not in the range when release it. port: %v", port)
		return nil
	}

	return r.alloc.Release(offset)
}

func (info DefaultNodeInfo) CompatibleWith(other_ NodeInfo) error {
	other, ok := other_.(DefaultNodeInfo)
	if !ok {
		return fmt.Errorf("wrong NodeInfo type. Expected DefaultNodeInfo, got %v", reflect.TypeOf(other_))
	}

	if info.ProtocolVersion.Block != other.ProtocolVersion.Block {
		return fmt.Errorf("Peer is on a different Block version. Got %v, expected %v",
			other.ProtocolVersion.Block, info.ProtocolVersion.Block)
	}

	// nodes must be on the same network
	if info.Network != other.Network {
		return fmt.Errorf("Peer is on a different network. Got %v, expected %v", other.Network, info.Network)
	}

	// if we have no channels, we're just testing
	if len(info.Channels) == 0 {
		return nil
	}

	// for each of our channels, check if they have it
	found := false
OUTER_LOOP:
	for _, ch1 := range info.Channels {
		for _, ch2 := range other.Channels {
			if ch1 == ch2 {
				found = true
				break OUTER_LOOP // only need one
			}
		}
	}
	if !found {
		return fmt.Errorf("Peer has no common channels. Our channels: %v ; Peer channels: %v", info.Channels, other.Channels)
	}
	return nil
}

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


Question: // Retrieve The non-vendor specific generic component model for a hardware component model.

func (r Hardware_Component_Model) GetHardwareGenericComponentModel() (resp datatypes.Hardware_Component_Model_Generic, err error) {
	err = r.Session.DoRequest("SoftLayer_Hardware_Component_Model", "getHardwareGenericComponentModel", nil, &r.Options, &resp)
	return
}

func (c *Client) GetLights() (lights []common.Light, err error) {
	devices, err := c.GetDevices()
	if err != nil {
		return lights, err
	}

	for _, dev := range devices {
		if light, ok := dev.(common.Light); ok {
			lights = append(lights, light)
		}
	}

	if len(lights) == 0 {
		return lights, common.ErrNotFound
	}

	return lights, nil
}

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


Question: // SetDBInstanceAutomatedBackup sets the DBInstanceAutomatedBackup field's value.

func (s *DeleteDBInstanceAutomatedBackupOutput) SetDBInstanceAutomatedBackup(v *DBInstanceAutomatedBackup) *DeleteDBInstanceAutomatedBackupOutput {
	s.DBInstanceAutomatedBackup = v
	return s
}

def loggin(self, user_id, mdp, autolog):
        """"""
        r = sql.abstractRequetesSQL.check_mdp_user(user_id, mdp)
        if r():
            # update auto-log params
            self.autolog[user_id] = autolog and mdp or False
            self.modules = self.users[user_id]["modules"]  # load modules list

            dic = {"autolog": self.autolog, "modules": self.modules}
            s = json.dumps(dic, indent=4, ensure_ascii=False)
            b = security.protege_data(s, True)
            with open("local/init", "wb") as f:
                f.write(b)

            self.mode_online = True  # authorization to execute bakground tasks
            return True
        else:
            logging.debug("Bad password !")

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


Question:
Determine if the currently logged in use has the given ability.

@param $user
@param string|null                              $ability
@param \Illuminate\Database\Eloquent\Model|null $model

@return bool

protected function hasRequiredAbility($user, $ability = null, $model = null)
    {
        if (!$user) {
            return false;
        }

        if (is_null($ability)) {
            return true;
        }

        /*
         * Some gates may check on number of arguments given. If model
         * is null, don't pass it as an argument.
         */
        if (is_null($model)) {
            return $user->can($ability);
        }

        return $user->can($ability, $model);
    }

public function withParameters(array $parameters): self
    {
        $query = $this;

        foreach ($parameters as $key => $parameter) {
            $query = $query->withParameter($key, $parameter);
        }

        return $query;
    }

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


Question: Handles request for getting an account by username

@RequestMapping(value = "/findByUsername", method = RequestMethod.GET)
	public @ResponseBody
	ResponseAccount findByUsername(
			@RequestParam(value = "username", required = true) String username) {
		logger.debug("Received request to get account by username");

		ResponseAccount acconut = accountService.getAccountByUsername(username);

		return acconut;

	}

func NewCreateUsersWithListInput(ctx *middleware.Context, handler CreateUsersWithListInputHandler) *CreateUsersWithListInput {
	return &CreateUsersWithListInput{Context: ctx, Handler: handler}
}

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


Question:
@EXT\Route("/indexing", name="claro_admin_parameters_indexing")
@EXT\Template
@SEC\PreAuthorize("canOpenAdminTool('platform_parameters')")

@return \Symfony\Component\HttpFoundation\RedirectResponse

public function indexingFormAction()
    {
        $form = $this->formFactory->create(
            new AdminForm\IndexingType($this->configHandler->getLockedParamaters()),
            $this->configHandler->getPlatformConfig()
        );

        if ($this->request->getMethod() === 'POST') {
            $form->handleRequest($this->request);

            if ($form->isValid()) {
                $this->configHandler->setParameter('google_meta_tag', $form['google_meta_tag']->getData());

                $this->addFlashMessage('parameters_save_success');

                return $this->redirect($this->generateUrl('claro_admin_index'));
            }
        }

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

protected function make($ctx)
    {
      // ENV or raw args
      if (!is_object($ctx)) {
        $this->user_id = $ctx['BANDWIDTH_USER_ID'];
        $this->token = $ctx['BANDWIDTH_API_TOKEN'];
        $this->secret = $ctx['BANDWIDTH_API_SECRET'];
        $this->application_id = $ctx->get('BANDWIDTH_APPLICATION_ID');
      } else {
        $this->user_id = $ctx->get('BANDWIDTH_USER_ID');
        $this->token = $ctx->get('BANDWIDTH_API_TOKEN');
        $this->secret = $ctx->get('BANDWIDTH_API_SECRET');
        $this->application_id = $ctx->get('BANDWIDTH_APPLICATION_ID');
      }

      if (!isset($this->user_id)
         ||!isset($this->token)
         ||!isset($this->secret))
              throw new \CatapultApiException("Credentials were improperly configured");

      $this->started = TRUE;

      return (self::$CLIENT = new RESTClient($this->user_id, array($this->token, $this->secret), $this->application_id));
    }

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


Question:
Convert this object to a dictionary with formatting appropriate for a PIF.

        :returns: Dictionary with the content of this object formatted for a PIF.

def as_dictionary(self):

        return {to_camel_case(i): Serializable._convert_to_dictionary(self.__dict__[i])
                for i in self.__dict__ if self.__dict__[i] is not None}

def to_dict(self):
        ''''''
        d = {'connectorId': self.connector_id,
                'name': self.name,
                'dataType': self.data_type,
                'interfaceType': self.interface_type,
                'dataflowType': self.data_flow_type,
                'sourceDataPort': self.source_data_port.to_dict(),
                'targetDataPort': self.target_data_port.to_dict()}
        if self.visible != True:
            d[RTS_EXT_NS_YAML + 'visible'] = self.visible
        if self.subscription_type:
            d['subscriptionType'] = self.subscription_type
        if self.push_interval:
            d['pushInterval'] = self.push_interval
        if self.comment:
            d[RTS_EXT_NS_YAML + 'comment'] = self.comment
        props = []
        for name in self.properties:
            p = {'name': name}
            if self.properties[name]:
                p['value'] = str(self.properties[name])
            props.append(p)
        if props:
            d[RTS_EXT_NS_YAML + 'properties'] = props
        return d

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


Question:
Handles an execute request.

@param request the execute request
@return future to be completed with an execute response

public CompletableFuture<ExecuteResponse> execute(ExecuteRequest request) {
    ComposableFuture<ExecuteResponse> future = new ComposableFuture<>();
    threadContext.execute(() -> {
      role.execute(request).whenComplete(future);
    });
    return future;
  }

public function setCallbacks() {
        if ($this->jasperClient) {
            //Get the entity manager
            $em = $this->container->get('doctrine')->getManager($this->entityManager);
            $this->jasperClient->addPostReportExecutionCallback(new PostReportExecution($em, $this->container->get('security.context')));
            $this->jasperClient->addPostReportCacheCallback(new PostReportCache($em));
        }
    }

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


Question:
[normalizePath description]
@param  {String} href  [path to the file]
@param  {String} _root [context]
@param  {String} _from [relative file]
@return {String}       [absolute path to file]

function normalizePath(href, _root, _from) {
	/* istanbul ignore next */
	return href ? path.join(path.isAbsolute(href) ? _root : path.dirname(_from), href) : _from;
}

public function parse(string $path, array $options = []): \stdClass
    {
        $data = $this->getEmptyResult();

        if (!empty($options)) {
            $this->setConfig($options);
        }

        try {
            $result = $this->getDataFromPath($path);
            $data = Convert::dataToJson($result, $this->getConfig('lint'));
            if ($this->getConfig('validate') === true) {
                $this->validate($data);
            }
        } catch (ParsingException $e) {
            $message = sprintf("File: %s\n%s", $path, $e->getMessage());
            $this->errors[] = $message;

            throw new InvalidArgumentException($message, 0, $e);
        } catch (InvalidArgumentException $e) {
            $this->errors[] = $e->getMessage();

            throw $e;
        } catch (JsonValidationException $e) {
            $schemaFile = explode(DIRECTORY_SEPARATOR, $path);

            throw new InvalidArgumentException(sprintf('[%s] : %s', end($schemaFile), $e->getMessage()), 0, $e);
        }

        return $data;
    }

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


Question: Return a new pqict mapping keys from an iterable to the same value.

def fromkeys(cls, iterable, value, **kwargs):

        return cls(((k, value) for k in iterable), **kwargs)

function populateOriginalKeyDetails (json, originalKey) {
  const properties = [
    'id',
    'name'
  ]

  properties
    .filter(jsonProp => !json.hasOwnProperty(jsonProp))
    .forEach(jsonProp => {
      json[jsonProp] = originalKey
    })
}

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


Question:
Send an RPC to a device.

        See :meth:`AbstractDeviceAdapter.send_rpc`.

async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):

        self._ensure_connection(conn_id, True)
        connection_string = self._get_property(conn_id, "connection_string")

        msg = dict(address=address, rpc_id=rpc_id, payload=base64.b64encode(payload),
                   timeout=timeout, connection_string=connection_string)

        response = await self._send_command(OPERATIONS.SEND_RPC, msg, COMMANDS.SendRPCResponse,
                                            timeout=timeout)

        return unpack_rpc_response(response.get('status'), response.get('payload'),
                                   rpc_id=rpc_id, address=address)

public void marshall(AddThingToThingGroupRequest addThingToThingGroupRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingGroupName(), THINGGROUPNAME_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingGroupArn(), THINGGROUPARN_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingName(), THINGNAME_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingArn(), THINGARN_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getOverrideDynamicGroups(), OVERRIDEDYNAMICGROUPS_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: shutdown the AnnisService - ensure that current work load finishes

public void shutdown()
  {
    log.info("Shutting down...");
    isShutdownRequested = true;

    try
    {
      mainThread.join();
    }
    catch (InterruptedException e)
    {
      log.error(
        "Interrupted which waiting on main daemon thread to complete.");
    }
  }

func (wsc *wsConnection) OnStop() {
	// Both read and write loops close the websocket connection when they exit their loops.
	// The writeChan is never closed, to allow WriteRPCResponse() to fail.

	if wsc.onDisconnect != nil {
		wsc.onDisconnect(wsc.remoteAddr)
	}

	if wsc.ctx != nil {
		wsc.cancel()
	}
}

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


Question:
Writes the complete Morse-Smale merge hierarchy to a string
            object.
            @ Out, a string object storing the entire merge hierarchy of
            all minima and maxima.

def to_json(self):

        capsule = {}
        capsule["Hierarchy"] = []
        for (
            dying,
            (persistence, surviving, saddle),
        ) in self.merge_sequence.items():
            capsule["Hierarchy"].append(
                {
                    "Dying": dying,
                    "Persistence": persistence,
                    "Surviving": surviving,
                    "Saddle": saddle,
                }
            )
        capsule["Partitions"] = []
        base = np.array([None, None] * len(self.Y)).reshape(-1, 2)
        for (min_index, max_index), items in self.base_partitions.items():
            base[items, :] = [min_index, max_index]
        capsule["Partitions"] = base.tolist()

        return json.dumps(capsule)

public void encodeData(AsnOutputStream asnOs) throws MAPException {

        if (this.ssCode == null)
            throw new MAPException("Error while encoding " + _PrimitiveName + ": ssCode required.");

        if (this.callBarringFeatureList == null)
            throw new MAPException("Error while encoding " + _PrimitiveName + ": callBarringFeatureList required.");

        if (this.callBarringFeatureList.size() < 1 || this.callBarringFeatureList.size() > 32) {
            throw new MAPException("Error while encoding " + _PrimitiveName
                    + ": Parameter callBarringFeatureList size must be from 1 to 32, found: "
                    + this.callBarringFeatureList.size());
        }

        try {

            ((SSCodeImpl) this.ssCode).encodeAll(asnOs);

            asnOs.writeTag(Tag.CLASS_UNIVERSAL, false, Tag.SEQUENCE);
            int pos = asnOs.StartContentDefiniteLength();
            for (ExtCallBarringFeature featureItem : this.callBarringFeatureList) {
                ((ExtCallBarringFeatureImpl) featureItem).encodeAll(asnOs);
            }
            asnOs.FinalizeContent(pos);

            if (this.extensionContainer != null)
                ((MAPExtensionContainerImpl) this.extensionContainer).encodeAll(asnOs);
        } catch (AsnException e) {
            throw new MAPException("AsnException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
        }
    }

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


Question:
// GetRootServices returns the value of RootServices if it is set or its
// zero value if it is unset.

func (v *GenerateServiceRequest) GetRootServices() (o []ServiceID) {
	if v != nil {
		o = v.RootServices
	}
	return
}

protected function setCountryCity($country_code)
    {
        $this->data_country = $this->country->get($country_code);

        if (empty($this->data_country)) {
            $this->outputHttpStatus(404);
        }
    }

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


Question: // SetPageToken sets the PageToken field's value.

func (s *ListTagOptionsOutput) SetPageToken(v string) *ListTagOptionsOutput {
	s.PageToken = &v
	return s
}

def _credentials_found_in_envars():

        return any([os.getenv('PAN_ACCESS_TOKEN'),
                    os.getenv('PAN_CLIENT_ID'),
                    os.getenv('PAN_CLIENT_SECRET'),
                    os.getenv('PAN_REFRESH_TOKEN')])

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


Question:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) INetworkAdaptergetGenericDriver(request *INetworkAdaptergetGenericDriver) (*INetworkAdaptergetGenericDriverResponse, error) {
	response := new(INetworkAdaptergetGenericDriverResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

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


Question: // SetMetricName sets the MetricName field's value.

func (s *RateBasedRule) SetMetricName(v string) *RateBasedRule {
	s.MetricName = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question: // compileConstantValue compiles a constant value AST into a ConstantValue.

func compileConstantValue(v ast.ConstantValue) ConstantValue {
	if v == nil {
		return nil
	}

	// TODO(abg): Support typedefs

	switch src := v.(type) {
	case ast.ConstantReference:
		return constantReference(src)
	case ast.ConstantMap:
		return compileConstantMap(src)
	case ast.ConstantList:
		return compileConstantList(src)
	case ast.ConstantBoolean:
		return ConstantBool(src)
	case ast.ConstantInteger:
		return ConstantInt(src)
	case ast.ConstantString:
		return ConstantString(src)
	case ast.ConstantDouble:
		return ConstantDouble(src)
	default:
		panic(fmt.Sprintf("unknown constant value of type %T: %v", src, src))
	}
}

func Convert_v1_BuildSource_To_build_BuildSource(in *v1.BuildSource, out *build.BuildSource, s conversion.Scope) error {
	return autoConvert_v1_BuildSource_To_build_BuildSource(in, out, s)
}

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


Question: Calculates the request payload size

def calculate_size(name, index):

    data_size = 0
    data_size += calculate_size_str(name)
    data_size += INT_SIZE_IN_BYTES
    return data_size

protected function createStringPayload($job, $data)
    {
        return [
            'displayName' => is_string($job) ? explode('@', $job)[0] : null,
            'job' => $job, 'maxTries' => null,
            'timeout' => null, 'data' => $data,
        ];
    }

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


Question:
Determines if the given offset exists.

@param  string  $key
@return bool

public function offsetExists($key)
    {
        $this->executeBeforeCallback();

        if (isset($this->items[$key])) {
            return true;
        }

        return false;
    }

protected function containsForeignConstraint(array $properties)
    {
        return Helpers::isKeyExists($properties, 'foreign-constraint')
        && is_array($properties['foreign-constraint'])
        && Helpers::isKeyExists($properties['foreign-constraint'], 'field', 'references', 'on');
    }

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


Question:
**************************
Class: Graph Node
*************************

function GraphNode() {
        this.position = new Float32Array(2);

        this.force = vec2.create();
        this.forcePrev = vec2.create();

        // If repulsionByDegree is true
        //  mass = inDegree + outDegree + 1
        // Else
        //  mass is manually set
        this.mass = 1;

        this.inDegree = 0;
        this.outDegree = 0;

        // Optional
        // this.size = 1;
    }

private void calculateNodeScores(List<TreeNode> sphereNodes) throws CDKException {
        TreeNode treeNode = null;
        for (int i = 0; i < sphereNodes.size(); i++) {
            treeNode = (TreeNode) sphereNodes.get(i);
            treeNode.score += getElementRank(treeNode.symbol);
            if (treeNode.bondType <= 4) {
                treeNode.score += bondRankings[(int) treeNode.bondType];
            } else {
                throw new CDKException("Unknown bond type encountered in HOSECodeGenerator");
            }
        }
    }

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


Question:
Get urls method.

        Returns:
            list: the list of url objects.

def get_urls(self):

        urls = super(DashboardSite, self).get_urls()
        custom_urls = [
            url(r'^$',
                self.admin_view(HomeView.as_view()),
                name='index'),
            url(r'^logs/', include(logs_urlpatterns(self.admin_view))),
        ]

        custom_urls += get_realtime_urls(self.admin_view)

        del urls[0]
        return custom_urls + urls

def search_links(selector)
      uri2links = {}
      search_all_links(selector).each do |link|
        target_uri = link.uri
        uri2links[target_uri.to_s] = link if same_domain? uri, target_uri
      end
      # enforcing deterministicity for testing and debugging
      uri2links.values.sort_by {|link| link.uri.to_s }
    end

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


Question:
Start.
@param  string $key
@return void
@throws Oppa\Exception\InvalidKeyException

public function start(string $key): void
    {
        $start = microtime(true);
        switch ($key) {
            case 'connection':
                $this->profiles[$key] = [
                    'start' => $start, 'end' => 0.00, 'time' => 0.00
                ];
                break;
            case 'query':
                $i = $this->queryCount;
                if (isset($this->profiles[$key][$i])) {
                    $this->profiles[$key][$i] += [
                        'start' => $start, 'end' => 0.00, 'time' => 0.00
                    ];
                }
                break;
            default:
                throw new InvalidKeyException("Unimplemented key '{$key}' given, available keys are"
                    ." 'connection,query' only!");
        }
    }

func (o *UpdateJSONWebKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewUpdateJSONWebKeyOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 401:
		result := NewUpdateJSONWebKeyUnauthorized()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 403:
		result := NewUpdateJSONWebKeyForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 500:
		result := NewUpdateJSONWebKeyInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("unknown error", response, response.Code())
	}
}

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


Question:
Creates and returns a JavaScript line that sets a cookie with the specified name and value. For example, a cookie name
of "test" and value of "123" would return {@code document.cookie="test=123;";}. Note: The name and value will be
HTML-encoded.

public String getJavaScriptHtmlCookieString(String name, String value) {
        return getJavaScriptHtmlCookieString(name, value, null);
    }

function( mockHandler, requestSettings ) {
			if ( mockHandler.logging === false ||
				 ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
				return;
			}
			if ( window.console && console.log ) {
				var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
				var request = $.extend({}, requestSettings);

				if (typeof console.log === 'function') {
					console.log(message, request);
				} else {
					try {
						console.log( message + ' ' + JSON.stringify(request) );
					} catch (e) {
						console.log(message);
					}
				}
			}
		}

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


Question:
Returns a request attribute scoped Map of portlets that are rendering for the current
request.

@SuppressWarnings("unchecked")
    protected Map<IPortletWindowId, IPortletRenderExecutionWorker> getPortletHeaderRenderingMap(
            HttpServletRequest request) {
        synchronized (PortalWebUtils.getRequestAttributeMutex(request)) {
            Map<IPortletWindowId, IPortletRenderExecutionWorker> portletRenderingMap =
                    (Map<IPortletWindowId, IPortletRenderExecutionWorker>)
                            request.getAttribute(PORTLET_HEADER_RENDERING_MAP);
            if (portletRenderingMap == null) {
                portletRenderingMap =
                        new ConcurrentHashMap<IPortletWindowId, IPortletRenderExecutionWorker>();
                request.setAttribute(PORTLET_HEADER_RENDERING_MAP, portletRenderingMap);
            }
            return portletRenderingMap;
        }
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question: TaskManager use only

public String start(String taskId) {
        long now = System.currentTimeMillis();
        return insert("INSERT INTO TaskLogs (taskId, resultType, startDate) VALUES (?, ?, ?)",
                Integer.parseInt(taskId), TaskLog.INCOMPLETE, now);
    }

public static void main(String[] args) throws Throwable {
		CliArguments arguments = CliArguments.parse(args);
		if (arguments.isSet() && !arguments.isUsageMode()) {
			CliRunner runner = new CliRunner(arguments);
			try {
				runner.run();
			} finally {
				runner.close();
			}
		} else {
			PrintWriter out = new PrintWriter(System.out);
			printUsage(out);
			FileHelper.safeClose(out);
		}
	}

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


Question:
Inject the list errors in the first resource, and return the this first resource.

@param ResourceListInterface $resources The resource list

@return ResourceInterface The first resource

public static function oneAction(ResourceListInterface $resources)
    {
        $resources->get(0)->getErrors()->addAll($resources->getErrors());

        return $resources->get(0);
    }

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question:
Transform a standard log record for a user.

@param object $record The record.
@param int $userid The user ID.
@return array

public static function transform_standard_log_record_for_userid($record, $userid) {

        // Restore the event to try to get the name, description and other field.
        $restoredevent = static::restore_event_from_standard_record($record);
        if ($restoredevent) {
            $name = $restoredevent->get_name();
            $description = $restoredevent->get_description();
            $other = $restoredevent->other;

        } else {
            $name = $record->eventname;
            $description = "Unknown event ({$name})";
            $other = \tool_log\helper\reader::decode_other($record->other);
        }

        $realuserid = $record->realuserid;
        $isauthor = $record->userid == $userid;
        $isrelated = $record->relateduserid == $userid;
        $isrealuser = $realuserid == $userid;
        $ismasqueraded = $realuserid !== null && $record->userid != $realuserid;
        $ismasquerading = $isrealuser && !$isauthor;
        $isanonymous = $record->anonymous;

        $data = [
            'name' => $name,
            'description' => $description,
            'timecreated' => transform::datetime($record->timecreated),
            'origin' => static::transform_origin($record->origin),
            'ip' => $isauthor ? $record->ip : '',
            'other' => $other ? $other : []
        ];

        if ($isanonymous) {
            $data['action_was_done_anonymously'] = transform::yesno($isanonymous);
        }
        if ($isauthor || !$isanonymous) {
            $data['authorid'] = transform::user($record->userid);
            $data['author_of_the_action_was_you'] = transform::yesno($isauthor);
        }

        if ($record->relateduserid) {
            $data['relateduserid'] = transform::user($record->relateduserid);
            $data['related_user_was_you'] = transform::yesno($isrelated);
        }

        if ($ismasqueraded) {
            $data['author_of_the_action_was_masqueraded'] = transform::yesno(true);
            if ($ismasquerading || !$isanonymous) {
                $data['masqueradinguserid'] = transform::user($realuserid);
                $data['masquerading_user_was_you'] = transform::yesno($ismasquerading);
            }
        }

        return $data;
    }

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
Creates an instance representing the value of {@code timestamp}.

@throws IllegalArgumentException if the timestamp is outside the representable range

public static Timestamp of(java.sql.Timestamp timestamp) {
    return ofTimeSecondsAndNanos(timestamp.getTime() / 1000, timestamp.getNanos());
  }

public void set_point( int point, int tick, int ampl ) {
		if( point >= 0 && point < ticks.length ) {
			if( point == 0 ) {
				tick = 0;
			}
			if( point > 0 ) {
				if( tick < ticks[ point - 1 ] ) {
					/* Simple guess at where the point is supposed to be.*/
					tick += 256;
				}
				if( tick <= ticks[ point - 1 ] ) {
					System.out.println( "Envelope: Point not valid (" + tick + " <= " + ticks[ point - 1 ] + ")");
					tick = ticks[ point - 1 ] + 1;
				}
			}
			ticks[ point ] = tick;
			ampls[ point ] = ampl;
			point += 1;
			while( point < ticks.length ) {
				ticks[ point ] = ticks[ point - 1 ] + 1;
				ampls[ point ] = 0;
				point += 1;
			}
		}
	}

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