Question:
Creates a version of the current object and saves it.

@param   ConnectionInterface $con the connection to use

@return  ChildSkillVersion A version object

public function addVersion($con = null)
    {
        $this->enforceVersion = false;

        $version = new ChildSkillVersion();
        $version->setId($this->getId());
        $version->setSportId($this->getSportId());
        $version->setName($this->getName());
        $version->setAlternativeName($this->getAlternativeName());
        $version->setSlug($this->getSlug());
        $version->setDescription($this->getDescription());
        $version->setHistory($this->getHistory());
        $version->setIsTranslation($this->getIsTranslation());
        $version->setIsRotation($this->getIsRotation());
        $version->setIsAcyclic($this->getIsAcyclic());
        $version->setIsCyclic($this->getIsCyclic());
        $version->setLongitudinalFlags($this->getLongitudinalFlags());
        $version->setLatitudinalFlags($this->getLatitudinalFlags());
        $version->setTransversalFlags($this->getTransversalFlags());
        $version->setMovementDescription($this->getMovementDescription());
        $version->setSequencePictureUrl($this->getSequencePictureUrl());
        $version->setVariationOfId($this->getVariationOfId());
        $version->setStartPositionId($this->getStartPositionId());
        $version->setEndPositionId($this->getEndPositionId());
        $version->setIsComposite($this->getIsComposite());
        $version->setIsMultiple($this->getIsMultiple());
        $version->setMultipleOfId($this->getMultipleOfId());
        $version->setMultiplier($this->getMultiplier());
        $version->setGeneration($this->getGeneration());
        $version->setImportance($this->getImportance());
        $version->setPictureId($this->getPictureId());
        $version->setVideoId($this->getVideoId());
        $version->setTutorialId($this->getTutorialId());
        $version->setKstrukturId($this->getKstrukturId());
        $version->setFunctionPhaseId($this->getFunctionPhaseId());
        $version->setObjectId($this->getObjectId());
        $version->setVersion($this->getVersion());
        $version->setVersionCreatedAt($this->getVersionCreatedAt());
        $version->setVersionComment($this->getVersionComment());
        $version->setSkill($this);
        if (($related = $this->getVariationOf(null, $con)) && $related->getVersion()) {
            $version->setVariationOfIdVersion($related->getVersion());
        }
        if (($related = $this->getMultipleOf(null, $con)) && $related->getVersion()) {
            $version->setMultipleOfIdVersion($related->getVersion());
        }
        if ($relateds = $this->getVariations(null, $con)->toKeyValue('Id', 'Version')) {
            $version->setKkTrixionarySkillIds(array_keys($relateds));
            $version->setKkTrixionarySkillVersions(array_values($relateds));
        }
        if ($relateds = $this->getMultiples(null, $con)->toKeyValue('Id', 'Version')) {
            $version->setKkTrixionarySkillIds(array_keys($relateds));
            $version->setKkTrixionarySkillVersions(array_values($relateds));
        }
        $version->save($con);

        return $version;
    }

def __load_all(self, config_filename):

        self._read_configuration_file(config_filename)
        self.connect()
        self.__find_source_files()
        self._get_column_type()
        self.__read_stored_routine_metadata()
        self.__get_constants()
        self._get_old_stored_routine_info()
        self._get_correct_sql_mode()
        self.__load_stored_routines()
        self._drop_obsolete_routines()
        self.__remove_obsolete_metadata()
        self.__write_stored_routine_metadata()
        self.disconnect()

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


Question:
returns the value.
the value maybe invalid.

@return mixed

public function getValue()
    {
        $values = [];
        foreach($this->values as $key => $value) {
            $values[$key] = $value->getValue();
        }
        return $values;
    }

protected CodeReviewAuditResponse getErrorResponse(CollectorItem repoItem, String scmBranch, String scmUrl) {
        CodeReviewAuditResponse noPRsCodeReviewAuditResponse = new CodeReviewAuditResponse();
        noPRsCodeReviewAuditResponse.addAuditStatus(COLLECTOR_ITEM_ERROR);

        noPRsCodeReviewAuditResponse.setLastUpdated(repoItem.getLastUpdated());
        noPRsCodeReviewAuditResponse.setScmBranch(scmBranch);
        noPRsCodeReviewAuditResponse.setScmUrl(scmUrl);
        noPRsCodeReviewAuditResponse.setErrorMessage(repoItem.getErrors().get(0).getErrorMessage());
        return noPRsCodeReviewAuditResponse;
    }

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


Question:
Gets the day start time with the specified time.

@param time the specified time
@return day start time

public static long getDayStartTime(final long time) {
        final Calendar start = Calendar.getInstance();
        start.setTimeInMillis(time);
        final int year = start.get(Calendar.YEAR);
        final int month = start.get(Calendar.MONTH);
        final int day = start.get(Calendar.DATE);
        start.set(year, month, day, 0, 0, 0);
        start.set(Calendar.MILLISECOND, 0);

        return start.getTimeInMillis();
    }

protected function parseDateTime($value, $key, $options = [], $bindName = null, $bindType = null)
    {
        // 获取时间字段类型
        if (strpos($key, '.')) {
            list($table, $key) = explode('.', $key);
            if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) {
                $table = $pos;
            }
        } else {
            $table = $options['table'];
        }
        $type = $this->query->getTableInfo($table, 'type');
        if (isset($type[$key])) {
            $info = $type[$key];
        }
        if (isset($info)) {
            if (is_string($value)) {
                $value = strtotime($value) ?: $value;
            }

            if (preg_match('/(datetime|timestamp)/is', $info)) {
                // 日期及时间戳类型
                $value = date('Y-m-d H:i:s', $value);
            } elseif (preg_match('/(date)/is', $info)) {
                // 日期及时间戳类型
                $value = date('Y-m-d', $value);
            }
        }
        $bindName = $bindName ?: $key;
        $this->query->bind($bindName, $value, $bindType);
        return ':' . $bindName;
    }

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


Question: Handle the execution of the instance

public void handleInstanceExecutor() {
    for (InstanceExecutor executor : taskIdToInstanceExecutor.values()) {
      boolean isLocalSpout = spoutSets.contains(executor.getComponentName());
      int taskId = executor.getTaskId();

      int items = executor.getStreamOutQueue().size();
      for (int i = 0; i < items; i++) {
        Message msg = executor.getStreamOutQueue().poll();

        if (msg instanceof HeronTuples.HeronTupleSet) {
          HeronTuples.HeronTupleSet tupleSet = (HeronTuples.HeronTupleSet) msg;

          if (tupleSet.hasData()) {
            HeronTuples.HeronDataTupleSet d = tupleSet.getData();
            TopologyAPI.StreamId streamId = d.getStream();
            for (HeronTuples.HeronDataTuple tuple : d.getTuplesList()) {
              List<Integer> outTasks = this.topologyManager.getListToSend(streamId, tuple);

              outTasks.addAll(tuple.getDestTaskIdsList());

              if (outTasks.isEmpty()) {
                LOG.severe("Nobody to send the tuple to");
              }

              copyDataOutBound(taskId, isLocalSpout, streamId, tuple, outTasks);
            }
          }

          if (tupleSet.hasControl()) {
            HeronTuples.HeronControlTupleSet c = tupleSet.getControl();
            for (HeronTuples.AckTuple ack : c.getAcksList()) {
              copyControlOutBound(tupleSet.getSrcTaskId(), ack, true);
            }

            for (HeronTuples.AckTuple fail : c.getFailsList()) {
              copyControlOutBound(tupleSet.getSrcTaskId(), fail, false);
            }
          }
        }
      }
    }
  }

public static int exec(String query, Object ... params){
        return new DB(DB.DEFAULT_NAME).exec(query, params);
    }

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


Question:
<p>
The dashboards to be deleted. This parameter is required.
</p>

@param dashboardNames
The dashboards to be deleted. This parameter is required.

public void setDashboardNames(java.util.Collection<String> dashboardNames) {
        if (dashboardNames == null) {
            this.dashboardNames = null;
            return;
        }

        this.dashboardNames = new com.amazonaws.internal.SdkInternalList<String>(dashboardNames);
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question:
Post a subscriptionfor the given netid
    and category_code

def update_catagory(netid, category_code, status):

    url = "{0}/category".format(url_version())
    body = {
        "categoryCode": category_code,
        "status": status,
        "categoryList": [{"netid": netid}]
    }

    response = post_resource(url, json.dumps(body))
    return json.loads(response)

def confd_state_ha_master_node_id(self, **kwargs):

        config = ET.Element("config")
        confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
        ha = ET.SubElement(confd_state, "ha")
        master_node_id = ET.SubElement(ha, "master-node-id")
        master_node_id.text = kwargs.pop('master_node_id')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question:
Match a URL to a registered pattern.

        :param url: URL
        :return: Matched route
        :raises kua.RouteError: If there is no match

def match(self, url: str) -> RouteResolved:

        url = normalize_url(url)
        parts = self._deconstruct_url(url)
        return self._match(parts)

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: // CreateUser creates a platform user and sets b.ID.

func (c *Client) CreateUser(ctx context.Context, u *platform.User) error {
	err := c.db.Update(func(tx *bolt.Tx) error {
		unique := c.uniqueUserName(ctx, tx, u)

		if !unique {
			return &platform.Error{
				Code: platform.EConflict,
				Msg:  fmt.Sprintf("user with name %s already exists", u.Name),
			}
		}

		u.ID = c.IDGenerator.ID()

		if err := c.appendUserEventToLog(ctx, tx, u.ID, userCreatedEvent); err != nil {
			return err
		}

		return c.putUser(ctx, tx, u)
	})
	if err != nil {
		return &platform.Error{
			Err: err,
			Op:  getOp(platform.OpCreateUser),
		}
	}
	return nil
}

private CmsUUID getProjectIdForContext(CmsDbContext dbc) {

        CmsUUID projectId = dbc.getProjectId();
        if (projectId.isNullUUID()) {
            projectId = dbc.currentProject().getUuid();
        }
        return projectId;
    }

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


Question:
Return list of DynamoDB tables available from AWS

    :returns: list -- List of DynamoDB tables

def list_tables():

    tables = []

    try:
        table_list = DYNAMODB_CONNECTION.list_tables()
        while True:
            for table_name in table_list[u'TableNames']:
                tables.append(get_table(table_name))

            if u'LastEvaluatedTableName' in table_list:
                table_list = DYNAMODB_CONNECTION.list_tables(
                    table_list[u'LastEvaluatedTableName'])
            else:
                break

    except DynamoDBResponseError as error:
        dynamodb_error = error.body['__type'].rsplit('#', 1)[1]

        if dynamodb_error == 'ResourceNotFoundException':
            logger.error('No tables found')
        elif dynamodb_error == 'AccessDeniedException':
            logger.debug(
                'Your AWS API keys lack access to listing tables. '
                'That is an issue if you are trying to use regular '
                'expressions in your table configuration.')
        elif dynamodb_error == 'UnrecognizedClientException':
            logger.error(
                'Invalid security token. Are your AWS API keys correct?')
        else:
            logger.error(
                (
                    'Unhandled exception: {0}: {1}. '
                    'Please file a bug report at '
                    'https://github.com/sebdah/dynamic-dynamodb/issues'
                ).format(
                    dynamodb_error,
                    error.body['message']))

    except JSONResponseError as error:
        logger.error('Communication error: {0}'.format(error))
        sys.exit(1)

    return tables

public static function getOptions(DataTablesWrapperInterface $dtWrapper) {

        $output = [];

        if (null !== $dtWrapper->getOptions()) {
            $output = $dtWrapper->getOptions()->getOptions();
        }

        $output["ajax"]         = [];
        $output["ajax"]["type"] = $dtWrapper->getMethod();
        $output["ajax"]["url"]  = $dtWrapper->getUrl();
        $output["columns"]      = [];
        $output["order"]        = $dtWrapper->getOrder();
        $output["processing"]   = $dtWrapper->getProcessing();
        $output["serverSide"]   = $dtWrapper->getServerSide();

        foreach ($dtWrapper->getColumns() as $current) {
            $output["columns"][] = DataTablesNormalizer::normalizeColumn($current);
        }

        return $output;
    }

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


Question: Returns index of collection item matching the match dictionary.

def _collection_match_to_index(pspath, colfilter, name, match):
    '''

    '''
    collection = get_webconfiguration_settings(pspath, [{'name': name, 'filter': colfilter}])[0]['value']
    for idx, collect_dict in enumerate(collection):
        if all(item in collect_dict.items() for item in match.items()):
            return idx
    return -1

func (i *smallIndex) load() {
	it := i.db.NewIterator(util.BytesPrefix(i.prefix), nil)
	defer it.Release()
	for it.Next() {
		val := string(it.Value())
		id := binary.BigEndian.Uint32(it.Key()[len(i.prefix):])
		if val != "" {
			// Empty value means the entry has been deleted.
			i.id2val[id] = val
			i.val2id[val] = id
		}
		if id >= i.nextID {
			i.nextID = id + 1
		}
	}
}

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


Question:
Returns the Widget Admin View.

@return string

public function getView()
    {
        if (view()->exists(static::$view)) {
            return static::$view;
        }

        if (view()->exists('admin.widgets.'.static::safeTitle().'.widget')) {
            return 'admin.widgets.'.static::safeTitle().'.widget';
        }

        if (view()->exists('admin.widgets.'.static::safeTitle())) {
            return 'admin.widgets.'.static::safeTitle();
        }

        if (view()->exists('admin.'.static::safeTitle())) {
            return 'admin.'.static::safeTitle();
        }

        if (view()->exists('flare::'.self::$view)) {
            return 'flare::'.self::$view;
        }
    }

public function show($id)
    {
        if(Request::isAjax()){
            $user = null;
            $message = '';

            try{
                $user = Sentry::findUserById($id);
            }catch(Exception $e){
                $message = $e->getMessage();
            }

            Response::headers()->set('Content-Type', 'application/json');
            Response::setBody(json_encode(
                array(
                    'success'   => !is_null($user),
                    'data'      => !is_null($user) ? $user->toArray() : $user,
                    'message'   => $message,
                    'code'      => is_null($user) ? 404 : 200
                )
            ));
        }else{

        }
    }

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


Question:
// GetCachedCoordinate returns the network coordinate for the node with the given
// name. This will only be valid if DisableCoordinates is set to false.

func (s *Serf) GetCachedCoordinate(name string) (coord *coordinate.Coordinate, ok bool) {
	if !s.config.DisableCoordinates {
		s.coordCacheLock.RLock()
		defer s.coordCacheLock.RUnlock()
		if coord, ok = s.coordCache[name]; ok {
			return coord, true
		}

		return nil, false
	}

	return nil, false
}

private static function resolveLogLocation(array &$context) {
        if (!key_exists('trace', $context))
            self::generateStackTrace($context);
        $trace = $context['trace'];

        foreach ($trace as $i => $frame) {                  // find the first frame with "file"
            if (isset($frame['file'])) {                    // skip internal PHP functions
                $context['file'] = $frame['file'];
                $context['line'] = $frame['line'];
                break;
            }
        }

        if (!key_exists('file', $context)) {
            $context['file'] = '(unknown)';
            $context['line'] = '(?)';
        }
    }

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


Question: // GetURL returns the URL field if it's non-nil, zero value otherwise.

func (n *Notification) GetURL() string {
	if n == nil || n.URL == nil {
		return ""
	}
	return *n.URL
}

def add_reference(self, subj: Node, val: str) -> None:

        match = FHIR_RESOURCE_RE.match(val)
        ref_uri_str = res_type = None
        if match:
            ref_uri_str = val if match.group(FHIR_RE_BASE) else (self._base_uri + urllib.parse.quote(val))
            res_type = match.group(FHIR_RE_RESOURCE)
        elif '://' in val:
            ref_uri_str = val
            res_type = "Resource"
        elif self._base_uri and not val.startswith('#') and not val.startswith('/'):
            ref_uri_str = self._base_uri + urllib.parse.quote(val)
            res_type = val.split('/', 1)[0] if '/' in val else "Resource"
        if ref_uri_str:
            ref_uri = URIRef(ref_uri_str)
            self.add(subj, FHIR.link, ref_uri)
            self.add(ref_uri, RDF.type, FHIR[res_type])

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


Question:
@param object $anEventSourcedAggregateRoot

@return Message[]

public function extractPendingStreamEvents($anEventSourcedAggregateRoot): array
    {
        if (null === $this->pendingEventsExtractor) {
            $callInterceptor = $this->flavour;

            $this->pendingEventsExtractor = function () use ($callInterceptor): array {
                return \array_map(function (Message $event) use ($callInterceptor) {
                    return $callInterceptor->prepareNetworkTransmission($event);
                }, $this->popRecordedEvents());
            };
        }

        return $this->pendingEventsExtractor->call($anEventSourcedAggregateRoot);
    }

function createLogRequest(logger, utils, path, environment, emitter, failureCallback) {

  'use strict';

  logger.logEnter('createLogRequest ' + path);

  var options = environment.elasticsearchOptions('POST', path);

  var respConsumer = utils.responseConsumer(logger, 'after posting events', 200, failureCallback ? failureCallback : emitter, null, 201, options, path);

  var request = environment.request(options, respConsumer);

  request.once('error', function (e) {
    emitter.emit('error', 'Error while reporting events: ' + e);
  });

  request.setHeader('Content-Type', 'text/plain');

  logger.logExit('createLogRequest');

  return request;
}

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


Question:
Get URL from route name.

@param  string      $locale
@param  string      $defaultLocale
@param  string      $transKey
@param  array       $attributes
@param  bool|false  $defaultHidden
@param  bool|false  $showHiddenLocale

@return string

public function getUrlFromRouteName(
        $locale, $defaultLocale, $transKey, $attributes = [], $defaultHidden = false, $showHiddenLocale = false
    ) {
        if ( ! is_string($locale))
            $locale = $defaultLocale;

        $url = '';

        if ( ! ($locale === $defaultLocale && $defaultHidden) || $showHiddenLocale)
            $url = '/'.$locale;

        if ($this->hasTranslation($transKey, $locale))
            $url = Url::substituteAttributes($attributes, $url.'/'.$this->trans($transKey, $locale));

        return $url;
    }

public function setParam(string $key, $value): Mapping
    {
        $this->_mapping[$key] = $value;

        return $this;
    }

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


Question: // httpParseRequestLine parses http request line like "GET / HTTP/1.0".

func httpParseRequestLine(line []byte) (req httpRequestLine, err error) {
	var proto []byte
	req.method, req.uri, proto = bsplit3(line, ' ')

	var ok bool
	req.major, req.minor, ok = httpParseVersion(proto)
	if !ok {
		err = ErrMalformedRequest
		return
	}

	return
}

public String serviceName_quota_PUT(String serviceName, Long quota) throws IOException {
		String qPath = "/metrics/{serviceName}/quota";
		StringBuilder sb = path(qPath, serviceName);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "quota", quota);
		String resp = exec(qPath, "PUT", sb.toString(), o);
		return convertTo(resp, String.class);
	}

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


Question:
// checkCache checks the cache for metric types.
// returns:
//  - array of metrics that need to be collected
//  - array of metrics that were returned from the cache

func (cb *configBased) CheckCache(mts []core.Metric, id string) ([]core.Metric, []core.Metric) {
	if _, ok := cb.metricCache[id]; !ok {
		cb.metricCache[id] = NewCache(cb.cacheTTL)
	}
	return cb.metricCache[id].checkCache(mts)
}

public function clear()
    {
        $cleared = false;
        try {
            /* @todo Not at all sure about this... do we really want to flush()? What happens if the storage supports
            /*       namespaces, but none has been provided? */
            $options = $this->storage->getOptions();
            $namespace = $options->getNamespace();
            if ($this->storage instanceof ClearByNamespaceInterface && $namespace) {
                $cleared = $this->storage->clearByNamespace($namespace);
            } elseif ($this->storage instanceof FlushableInterface) {
                $cleared = $this->storage->flush();
            } else {
                throw new CacheException(sprintf("Storage %s does not support clear()", get_class($this->storage)));
            }
        } catch (Exception\InvalidArgumentException $e) {
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);

        } catch (Exception\ExceptionInterface $e) {
            throw new CacheException($e->getMessage(), $e->getCode(), $e);
        }

        return $cleared;
    }

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


Question:
Invokes the request and returns the response.

@param request the request
@return the response

public SwitchYardServiceResponse invoke(SwitchYardServiceRequest request) {
        Map<String, Object> contextOut = new HashMap<String, Object>();
        Object contentOut = null;
        Object fault = null;
        try {
            QName serviceName = request.getServiceName();
            if (serviceName == null) {
                throw CommonKnowledgeMessages.MESSAGES.serviceNameNull();
            } else if (Strings.trimToNull(serviceName.getNamespaceURI()) == null) {
                String tns = getTargetNamespace();
                if (tns != null) {
                    serviceName = XMLHelper.createQName(tns, serviceName.getLocalPart());
                }
            }
            ServiceDomain serviceDomain = getServiceDomain();
            if (serviceDomain == null) {
                throw CommonKnowledgeMessages.MESSAGES.serviceDomainNull();
            }
            ServiceReference serviceReference = serviceDomain.getServiceReference(serviceName);
            if (serviceReference == null) {
                throw CommonKnowledgeMessages.MESSAGES.serviceReferenceNull(serviceName.toString());
            }
            final Exchange exchangeIn;
            FaultHandler handler = new FaultHandler();
            String operationName = request.getOperationName();
            if (operationName != null) {
                exchangeIn = serviceReference.createExchange(operationName, handler);
            } else {
                exchangeIn = serviceReference.createExchange(handler);
            }
            Message messageIn = exchangeIn.createMessage();
            Context contextIn = exchangeIn.getContext(messageIn);
            for (Map.Entry<String, Object> entry : request.getContext().entrySet()) {
                contextIn.setProperty(entry.getKey(), entry.getValue());
            }
            Object contentIn = request.getContent();
            if (contentIn != null) {
                messageIn.setContent(contentIn);
            }
            exchangeIn.send(messageIn);
            if (ExchangePattern.IN_OUT.equals(exchangeIn.getContract().getConsumerOperation().getExchangePattern())) {
                Exchange exchangeOut = handler.waitForOut();
                Message messageOut = exchangeOut.getMessage();
                contentOut = messageOut.getContent();
                for (Property property : exchangeOut.getContext(messageOut).getProperties()) {
                    contextOut.put(property.getName(), property.getValue());
                }
            }
            fault = handler.getFault();
        } catch (Throwable t) {
            fault = t;
        }
        return new SwitchYardServiceResponse(contentOut, contextOut, fault);
    }

public function build(): SetRequestInterceptionRequest
	{
		$instance = new SetRequestInterceptionRequest();
		if ($this->patterns === null) {
			throw new BuilderException('Property [patterns] is required.');
		}
		$instance->patterns = $this->patterns;
		return $instance;
	}

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


Question: // TriggerCurrentWeatherEvent triggers all current weather events

func (mod *OpenweathermapBee) TriggerCurrentWeatherEvent() {
	ev := bees.Event{
		Bee:  mod.Name(),
		Name: "current_weather",
		Options: []bees.Placeholder{
			{
				Name:  "geo_pos_longitude",
				Type:  "float64",
				Value: mod.current.GeoPos.Longitude,
			},
			{
				Name:  "geo_pos_latitude",
				Type:  "float64",
				Value: mod.current.GeoPos.Latitude,
			},
			{
				Name:  "sys_type",
				Type:  "int",
				Value: mod.current.Sys.Type,
			},
			{
				Name:  "sys_id",
				Type:  "int",
				Value: mod.current.Sys.ID,
			},
			{
				Name:  "sys_message",
				Type:  "float64",
				Value: mod.current.Sys.Message,
			},
			{
				Name:  "sys_country",
				Type:  "string",
				Value: mod.current.Sys.Country,
			},
			{
				Name:  "sys_sunrise",
				Type:  "int",
				Value: mod.current.Sys.Sunrise,
			},
			{
				Name:  "sys_sunset",
				Type:  "int",
				Value: mod.current.Sys.Sunset,
			},
			{
				Name:  "base",
				Type:  "string",
				Value: mod.current.Base,
			},
			{
				Name:  "main_temp",
				Type:  "float64",
				Value: mod.current.Main.Temp,
			},
			{
				Name:  "main_temp_min",
				Type:  "float64",
				Value: mod.current.Main.TempMin,
			},
			{
				Name:  "main_temp_max",
				Type:  "float64",
				Value: mod.current.Main.TempMax,
			},
			{
				Name:  "main_pressure",
				Type:  "float64",
				Value: mod.current.Main.Pressure,
			},
			{
				Name:  "main_sealevel",
				Type:  "float64",
				Value: mod.current.Main.SeaLevel,
			},
			{
				Name:  "main_grndlevel",
				Type:  "float64",
				Value: mod.current.Main.GrndLevel,
			},
			{
				Name:  "main_humidity",
				Type:  "float64",
				Value: mod.current.Main.Humidity,
			},
			{
				Name:  "wind_speed",
				Type:  "float64",
				Value: mod.current.Wind.Speed,
			},
			{
				Name:  "wind_deg",
				Type:  "float64",
				Value: mod.current.Wind.Deg,
			},
			{
				Name:  "clouds_all",
				Type:  "int",
				Value: mod.current.Clouds.All,
			},
			{
				Name:  "rain",
				Type:  "map[string]float64",
				Value: mod.current.Rain,
			},
			{
				Name:  "snow",
				Type:  "map[string]float64",
				Value: mod.current.Snow,
			},
			{
				Name:  "dt",
				Type:  "int",
				Value: mod.current.Dt,
			},
			{
				Name:  "id",
				Type:  "int",
				Value: mod.current.ID,
			},
			{
				Name:  "name",
				Type:  "string",
				Value: mod.current.Name,
			},
			{
				Name:  "cod",
				Type:  "int",
				Value: mod.current.Cod,
			},
			{
				Name:  "unit",
				Type:  "string",
				Value: mod.current.Unit,
			},
			{
				Name:  "lang",
				Type:  "string",
				Value: mod.current.Lang,
			},
			{
				Name:  "key",
				Type:  "string",
				Value: mod.current.Key,
			},
		},
	}
	mod.evchan <- ev

	for _, v := range mod.current.Weather {
		mod.TriggerWeatherInformationEvent(&v)
	}
}

public function updateMajorInfo(
        Title $title,
        EventType $eventType,
        Location $location,
        CalendarInterface $calendar,
        Theme $theme = null
    ) {
        $this->apply(new MajorInfoUpdated($this->eventId, $title, $eventType, $location, $calendar, $theme));
    }

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


Question:
transform.

@param obj a {@link java.lang.Object} object.
@return a {@link java.lang.Object} object.

@SuppressWarnings("unchecked")
    public Object transform(final Object obj) {
        if (obj != null && !(obj instanceof BeanMap)) {
            Class clazz = obj.getClass();
            if (clazz.isArray()) {
                return _transform((Object[]) obj);
            } else if (obj instanceof Map) {
                return _transform((Map) obj);
            } else if (obj instanceof List) {
                return _transform((List) obj);
            } else if (obj instanceof Set) {
                return _transform((Set) obj);
            } else if (obj instanceof Collection) {
                return _transform((Collection) obj);
            } else if (obj instanceof Iterable) {
                return _transform((Iterable) obj);
            } else if (obj instanceof Iterator) {
                return _transform((Iterator) obj);
            } else if (needTransform(obj)) {
                return onTransform(obj);
            }
        }
        return obj;
    }

public void warn (String msg, Object... args) {
    warn(format(msg, args), getCause(args));
  }

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


Question:
Supports the writing of Array types, so that you can implement
array methods, like Rabbitmq's HA parameters

@param AMQPArray|array $a Instance of AMQPArray or PHP array WITHOUT format hints (unlike write_table())
@return self

public function write_array($a)
    {
        if (!($a instanceof AMQPArray)) {
            $a = new AMQPArray($a);
        }
        $data = new self();

        foreach ($a as $v) {
            $data->write_value($v[0], $v[1]);
        }

        $data = $data->getvalue();
        $this->write_long(mb_strlen($data, 'ASCII'));
        $this->write($data);

        return $this;
    }

public function basic_publish(
        $msg,
        $exchange = '',
        $routing_key = '',
        $mandatory = false,
        $immediate = false,
        $ticket = null
    ) {
        $pkt = new AMQPWriter();
        $pkt->write($this->pre_publish($exchange, $routing_key, $mandatory, $immediate, $ticket));

        try {
            $this->connection->send_content(
                $this->channel_id,
                60,
                0,
                mb_strlen($msg->body, 'ASCII'),
                $msg->serialize_properties(),
                $msg->body,
                $pkt
            );
        } catch (AMQPConnectionClosedException $e) {
            $this->do_close();
            throw $e;
        }

        if ($this->next_delivery_tag > 0) {
            $this->published_messages[$this->next_delivery_tag] = $msg;
            $this->next_delivery_tag = bcadd($this->next_delivery_tag, '1', 0);
        }
    }

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


Question: yii\base\Component -----

public function behaviors() {

		$behaviours	= parent::behaviors();

		$behaviours[ 'verbs' ][ 'actions' ][ 'index' ] = [ 'get' ];
		$behaviours[ 'verbs' ][ 'actions' ][ 'maintenance' ] = [ 'get' ];
		$behaviours[ 'verbs' ][ 'actions' ][ 'register' ] = [ 'get', 'post' ];
		$behaviours[ 'verbs' ][ 'actions' ][ 'confirm-account' ] = [ 'get', 'post' ];
		$behaviours[ 'verbs' ][ 'actions' ][ 'join-site' ] = [ 'get', 'post' ];
		$behaviours[ 'verbs' ][ 'actions' ][ 'feedback' ] = [ 'get' ];
		$behaviours[ 'verbs' ][ 'actions' ][ 'testimonial' ] = [ 'get' ];

		return $behaviours;
	}

private function dateTypeBuilder(DateTimeTypeBase $type) : DateFieldBuilder
    {
        $this->type($type);

        return new DateFieldBuilder($type, $this);
    }

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


Question: Implementation of Reporter callback.

def do_handle_log(self, workunit, level, *msg_elements):
    """"""

    entry_info = {
      'level': self._log_level_str[level],
      'messages': self._render_messages(*msg_elements),
    }

    root_id = str(workunit.root().id)
    current_stack = self._root_id_to_workunit_stack[root_id]
    if current_stack:
      current_stack[-1]['log_entries'].append(entry_info)
    else:
      self.results[root_id]['log_entries'].append(entry_info)

public static String getSql(Report report) {
		String sql;
		if (report.getSql() != null) {
			sql = report.getSql();
		} else {
			sql = report.getQuery().toString();
		}
		return sql;
	}

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


Question:
Converts a queue URL into a queue ARN.

@param string $queueUrl The queue URL to perform the action on.
Retrieved when the queue is first created.

@return string An ARN representation of the queue URL.

public function getQueueArn($queueUrl)
    {
        $queueArn = strtr($queueUrl, array(
            'http://'        => 'arn:aws:',
            'https://'       => 'arn:aws:',
            '.amazonaws.com' => '',
            '/'              => ':',
            '.'              => ':',
        ));

        // Cope with SQS' .fifo / :fifo arn inconsistency
        if (substr($queueArn, -5) === ':fifo') {
            $queueArn = substr_replace($queueArn, '.fifo', -5);
        }
        return $queueArn;
    }

def normalized_query(*flags)
      return nil unless self.query
      return @normalized_query if defined?(@normalized_query)
      @normalized_query ||= begin
        modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup
        # Make sure possible key-value pair delimiters are escaped.
        modified_query_class.sub!("\\&", "").sub!("\\;", "")
        pairs = (self.query || "").split("&", -1)
        pairs.sort! if flags.include?(:sorted)
        component = pairs.map do |pair|
          Addressable::URI.normalize_component(pair, modified_query_class, "+")
        end.join("&")
        component == "" ? nil : component
      end
      # All normalized values should be UTF-8
      @normalized_query.force_encoding(Encoding::UTF_8) if @normalized_query
      @normalized_query
    end

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


Question:
@param string|int $id
@param array $parameters

@return string

public function getEditUrl($id, array $parameters = [])
    {
        array_unshift($parameters, $this->getAlias(), $id);

        return route('admin.model.edit', $parameters);
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: modeled on implementation in Zhang Le's maxent kit

private double gaussianUpdate(int predicate, int oid, double correctionConstant) {
        double param = params[predicate].getParameters()[oid];
        double x0 = 0.0;
        double modelValue = modelExpects[0][predicate].getParameters()[oid];
        double observedValue = observedExpects[predicate].getParameters()[oid];
        for (int i = 0; i < 50; i++) {
            double tmp = modelValue * Math.exp(correctionConstant * x0);
            double f = tmp + (param + x0) / sigma - observedValue;
            double fp = tmp * correctionConstant + 1 / sigma;
            if (fp == 0) {
                break;
            }
            double x = x0 - f / fp;
            if (Math.abs(x - x0) < 0.000001) {
                x0 = x;
                break;
            }
            x0 = x;
        }
        return x0;
    }

public function train(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This estimator requires a'
                . ' labeled training set.');
        }

        $this->network = new FeedForward(
            new Placeholder1D($dataset->numColumns()),
            [],
            new Continuous($this->alpha, $this->costFn),
            $this->optimizer
        );

        $this->steps = [];

        $this->partial($dataset);
    }

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


Question:
// createVirtualMachine creates a virtual machine and related resources.
//
// All resources created are tagged with the specified "vmTags", so if
// this function fails then all resources can be deleted by tag.

func (env *azureEnviron) createVirtualMachine(
	ctx context.ProviderCallContext,
	vmName string,
	vmTags, envTags map[string]string,
	instanceSpec *instances.InstanceSpec,
	instanceConfig *instancecfg.InstanceConfig,
	storageAccountType string,
) error {
	deploymentsClient := resources.DeploymentsClient{
		BaseClient: env.resources,
	}
	apiPorts := make([]int, 0, 2)
	if instanceConfig.Controller != nil {
		apiPorts = append(apiPorts, instanceConfig.Controller.Config.APIPort())
		if instanceConfig.Controller.Config.AutocertDNSName() != "" {
			// Open port 80 as well as it handles Let's Encrypt HTTP challenge.
			apiPorts = append(apiPorts, 80)
		}
	} else {
		ports := instanceConfig.APIInfo.Ports()
		if len(ports) != 1 {
			return errors.Errorf("expected one API port, found %v", ports)
		}
		apiPorts = append(apiPorts, ports[0])
	}

	var nicDependsOn, vmDependsOn []string
	var resources []armtemplates.Resource
	createCommonResources := instanceConfig.Bootstrap != nil
	if createCommonResources {
		// We're starting the bootstrap machine, so we will create the
		// common resources in the same deployment.
		resources = append(resources,
			networkTemplateResources(env.location, envTags, apiPorts, nil)...,
		)
		nicDependsOn = append(nicDependsOn, fmt.Sprintf(
			`[resourceId('Microsoft.Network/virtualNetworks', '%s')]`,
			internalNetworkName,
		))
	} else {
		// Wait for the common resource deployment to complete.
		if err := env.waitCommonResourcesCreated(); err != nil {
			return errors.Annotate(
				err, "waiting for common resources to be created",
			)
		}
	}

	maybeStorageAccount, err := env.getStorageAccount()
	if errors.IsNotFound(err) {
		// Only models created prior to Juju 2.3 will have a storage
		// account. Juju 2.3 onwards exclusively uses managed disks
		// for all new models, and handles both managed and unmanaged
		// disks for upgraded models.
		maybeStorageAccount = nil
	} else if err != nil {
		return errors.Trace(err)
	}

	osProfile, seriesOS, err := newOSProfile(
		vmName, instanceConfig,
		env.provider.config.RandomWindowsAdminPassword,
		env.provider.config.GenerateSSHKey,
	)
	if err != nil {
		return errors.Annotate(err, "creating OS profile")
	}
	storageProfile, err := newStorageProfile(
		vmName,
		maybeStorageAccount,
		storageAccountType,
		instanceSpec,
	)
	if err != nil {
		return errors.Annotate(err, "creating storage profile")
	}

	var availabilitySetSubResource *compute.SubResource
	availabilitySetName, err := availabilitySetName(
		vmName, vmTags, instanceConfig.Controller != nil,
	)
	if err != nil {
		return errors.Annotate(err, "getting availability set name")
	}
	if availabilitySetName != "" {
		availabilitySetId := fmt.Sprintf(
			`[resourceId('Microsoft.Compute/availabilitySets','%s')]`,
			availabilitySetName,
		)
		var (
			availabilitySetProperties  interface{}
			availabilityStorageOptions *storage.Sku
		)
		if maybeStorageAccount == nil {
			// This model uses managed disks; we must create
			// the availability set as "aligned" to support
			// them.
			availabilitySetProperties = &compute.AvailabilitySetProperties{
				// Azure complains when the fault domain count
				// is not specified, even though it is meant
				// to be optional and default to the maximum.
				// The maximum depends on the location, and
				// there is no API to query it.
				PlatformFaultDomainCount: to.Int32Ptr(maxFaultDomains(env.location)),
			}
			// Availability needs to be 'Aligned' to support managed disks.
			availabilityStorageOptions = &storage.Sku{
				Name: "Aligned",
			}
		}
		resources = append(resources, armtemplates.Resource{
			APIVersion: computeAPIVersion,
			Type:       "Microsoft.Compute/availabilitySets",
			Name:       availabilitySetName,
			Location:   env.location,
			Tags:       envTags,
			Properties: availabilitySetProperties,
			StorageSku: availabilityStorageOptions,
		})
		availabilitySetSubResource = &compute.SubResource{
			ID: to.StringPtr(availabilitySetId),
		}
		vmDependsOn = append(vmDependsOn, availabilitySetId)
	}

	publicIPAddressName := vmName + "-public-ip"
	publicIPAddressId := fmt.Sprintf(`[resourceId('Microsoft.Network/publicIPAddresses', '%s')]`, publicIPAddressName)
	resources = append(resources, armtemplates.Resource{
		APIVersion: networkAPIVersion,
		Type:       "Microsoft.Network/publicIPAddresses",
		Name:       publicIPAddressName,
		Location:   env.location,
		Tags:       vmTags,
		StorageSku: &storage.Sku{Name: "Standard", Tier: "Regional"},
		Properties: &network.PublicIPAddressPropertiesFormat{
			PublicIPAddressVersion:   network.IPv4,
			PublicIPAllocationMethod: network.Static,
		},
	})

	// Controller and non-controller machines are assigned to separate
	// subnets. This enables us to create controller-specific NSG rules
	// just by targeting the controller subnet.
	subnetName := internalSubnetName
	subnetPrefix := internalSubnetPrefix
	if instanceConfig.Controller != nil {
		subnetName = controllerSubnetName
		subnetPrefix = controllerSubnetPrefix
	}
	subnetId := fmt.Sprintf(
		`[concat(resourceId('Microsoft.Network/virtualNetworks', '%s'), '/subnets/%s')]`,
		internalNetworkName, subnetName,
	)

	privateIP, err := machineSubnetIP(subnetPrefix, instanceConfig.MachineId)
	if err != nil {
		return errors.Annotatef(err, "computing private IP address")
	}
	nicName := vmName + "-primary"
	nicId := fmt.Sprintf(`[resourceId('Microsoft.Network/networkInterfaces', '%s')]`, nicName)
	nicDependsOn = append(nicDependsOn, publicIPAddressId)
	ipConfigurations := []network.InterfaceIPConfiguration{{
		Name: to.StringPtr("primary"),
		InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
			Primary:                   to.BoolPtr(true),
			PrivateIPAddress:          to.StringPtr(privateIP.String()),
			PrivateIPAllocationMethod: network.Static,
			Subnet:                    &network.Subnet{ID: to.StringPtr(subnetId)},
			PublicIPAddress: &network.PublicIPAddress{
				ID: to.StringPtr(publicIPAddressId),
			},
		},
	}}
	resources = append(resources, armtemplates.Resource{
		APIVersion: networkAPIVersion,
		Type:       "Microsoft.Network/networkInterfaces",
		Name:       nicName,
		Location:   env.location,
		Tags:       vmTags,
		Properties: &network.InterfacePropertiesFormat{
			IPConfigurations: &ipConfigurations,
		},
		DependsOn: nicDependsOn,
	})

	nics := []compute.NetworkInterfaceReference{{
		ID: to.StringPtr(nicId),
		NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
			Primary: to.BoolPtr(true),
		},
	}}
	vmDependsOn = append(vmDependsOn, nicId)
	resources = append(resources, armtemplates.Resource{
		APIVersion: computeAPIVersion,
		Type:       "Microsoft.Compute/virtualMachines",
		Name:       vmName,
		Location:   env.location,
		Tags:       vmTags,
		Properties: &compute.VirtualMachineProperties{
			HardwareProfile: &compute.HardwareProfile{
				VMSize: compute.VirtualMachineSizeTypes(
					instanceSpec.InstanceType.Name,
				),
			},
			StorageProfile: storageProfile,
			OsProfile:      osProfile,
			NetworkProfile: &compute.NetworkProfile{
				&nics,
			},
			AvailabilitySet: availabilitySetSubResource,
		},
		DependsOn: vmDependsOn,
	})

	// On Windows and CentOS, we must add the CustomScript VM
	// extension to run the CustomData script.
	switch seriesOS {
	case os.Windows, os.CentOS:
		properties, err := vmExtensionProperties(seriesOS)
		if err != nil {
			return errors.Annotate(
				err, "creating virtual machine extension",
			)
		}
		resources = append(resources, armtemplates.Resource{
			APIVersion: computeAPIVersion,
			Type:       "Microsoft.Compute/virtualMachines/extensions",
			Name:       vmName + "/" + extensionName,
			Location:   env.location,
			Tags:       vmTags,
			Properties: properties,
			DependsOn:  []string{"Microsoft.Compute/virtualMachines/" + vmName},
		})
	}

	logger.Debugf("- creating virtual machine deployment")
	template := armtemplates.Template{Resources: resources}
	// NOTE(axw) VMs take a long time to go to "Succeeded", so we do not
	// block waiting for them to be fully provisioned. This means we won't
	// return an error from StartInstance if the VM fails provisioning;
	// we will instead report the error via the instance's status.
	deploymentsClient.ResponseInspector = asyncCreationRespondDecorator(
		deploymentsClient.ResponseInspector,
	)
	if err := createDeployment(
		ctx,
		deploymentsClient,
		env.resourceGroup,
		vmName, // deployment name
		template,
	); err != nil {
		return errors.Trace(err)
	}
	return nil
}

def tools_path_identifier(path)
      path_identifier = rvm(:tools, "path-identifier", path.to_s)
      if path_identifier.exit_status == 2
        error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms."
        error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1."
        raise ErrorLoadingRVMRC, error_message
      end
      return normalize(path_identifier.stdout)
    end

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


Question:
Execute the console command.

@return mixed

public function handle()
    {
        $this->showWelcomeMessage();
        $this->userSetup();
        $this->triggerPublish();
        $this->call('dashboard:fresh');
        $this->setupSeedStubs();
        $this->triggerMigrations();
        $this->createDefaultUser();
        $this->info('Setup is complete. Keep coding!');
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question:
Runs and parses stty -a if it's available, suppressing any error output.

@return string|null

private function getSttyColumns()
    {
        if (!function_exists('proc_open')) {
            return null;
        }

        $spec = [
            1 => ['pipe', 'w'],
            2 => ['pipe', 'w'],
        ];

        $process = proc_open('stty -a | grep columns', $spec, $pipes, null, null, ['suppress_errors' => true]);
        if (is_resource($process)) {
            $info = stream_get_contents($pipes[1]);
            fclose($pipes[1]);
            fclose($pipes[2]);
            proc_close($process);

            return $info;
        }

        return null;
    }

static function execute($cmd)
    {
        $result = '';
        echo 'Executing ' . $cmd . PHP_EOL;
        $result = shell_exec($cmd);
        echo($result);
        return $result;
    }

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


Question: Make sure the current language is selected.

def get_queryset(self, request):

        qs = super(BaseTranslatableAdmin, self).get_queryset(request)

        if self._has_translatable_model():
            if not isinstance(qs, TranslatableQuerySet):
                raise ImproperlyConfigured("{0} class does not inherit from TranslatableQuerySet".format(qs.__class__.__name__))

            # Apply a consistent language to all objects.
            qs_language = self.get_queryset_language(request)
            if qs_language:
                qs = qs.language(qs_language)

        return qs

function () {
			// create i18n model
			var oI18nModel = new ResourceModel({
				bundleName: "sap.ui.core.messagebundle"
			});
			this._oDialog.setModel(oI18nModel, "i18n");
			this._oDialog.setModel(this._createViewModel(), "view");

			// set compact/cozy style class
			this._oDialog.addStyleClass(this._getContentDensityClass());
		}

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


Question: Load directory of package into members scope.

private void fillIn(PackageSymbol p) throws IOException {
        if (p.members_field == null)
            p.members_field = WriteableScope.create(p);

        ModuleSymbol msym = p.modle;

        Assert.checkNonNull(msym, p::toString);

        msym.complete();

        if (msym == syms.noModule) {
            preferCurrent = false;
            if (userPathsFirst) {
                scanUserPaths(p, true);
                preferCurrent = true;
                scanPlatformPath(p);
            } else {
                scanPlatformPath(p);
                scanUserPaths(p, true);
            }
        } else if (msym.classLocation == StandardLocation.CLASS_PATH) {
            scanUserPaths(p, msym.sourceLocation == StandardLocation.SOURCE_PATH);
        } else {
            scanModulePaths(p, msym);
        }
    }

public static function init($path)
    {
        pake_mkdirs($path);

        pake_sh(escapeshellarg(pake_which('hg')).' init -q '.escapeshellarg($path));

        return new pakeMercurial($path);
    }

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


Question:
Adds new remote repository

@param $name string
@param $url string
@param $params array|NULL

@return static

public function addRemote($name, $url, array $params = null) {
		return $this
			->begin()
			->run('git remote add', $params, $name, $url)
			->end();
	}

protected function computeInPathParameters()
	{
		foreach ($this->openApiFileContent['paths'] as $path => $operations) {
			foreach ($operations as $httpMethod => $operation) {
				if (isset($operation['tags'])) {
					$extractedTags = [];
					foreach ($operation['tags'] as $tag) {
						$split = explode(':', $tag);
						if (count($split) == 2) {
							switch ($split[0]) {
								case 'Manager' :
									if (!isset($extractedTags['Managers'])) {
										$extractedTags['Managers'] = [];
									}
									$extractedTags['Managers'][] = $split[1];
									break;
								case 'Resource' :
									if (!isset($extractedTags['Resources'])) {
										$extractedTags['Resources'] = [];
									}
									$extractedTags['Resources'][] = $split[1];
									break;
							}
						}
					}

					foreach ($extractedTags as $tagType => $typeTags) {
						foreach ($typeTags as $typeTag) {
							switch ($tagType) {
								case 'Managers' :
									$this->prepareManager($typeTag);
									$this->managersData[ucfirst($typeTag)]['routes'][$operation['operationId']]['inPathParameters'] = $this->getRouteOperationInPathParameters($operation);
									break;

								case 'Resources' :
									$this->prepareResource($typeTag);
									$this->resourcesData[ucfirst($typeTag)]['routes'][$operation['operationId']]['inPathParameters'] = $this->getRouteOperationInPathParameters($operation, ucfirst($typeTag), $this->resourcesData[ucfirst($typeTag)]['properties']);
									break;
							}
						}
					}
				}
			}
		}
	}

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


Question:
Handle this message.
Basically, if I get a message that the current record changed, I re-read the record.
@param The message to handle.
@return An error code.

public int handleMessage(BaseMessage message)
    {
            try   {
                int iMessageType = Integer.parseInt((String)message.get(MessageConstants.MESSAGE_TYPE_PARAM));
                if ((iMessageType == Constants.AFTER_UPDATE_TYPE)
                        || (iMessageType == Constants.CACHE_UPDATE_TYPE))
                    { // Record updated - be very careful, you are running in an independent thread.
                        SwingUtilities.invokeLater(new UpdateScreenRecord(iMessageType));
                    }
            } catch (NumberFormatException ex)  {
                // Ignore
            }
        return super.handleMessage(message);
    }

func (broker *Broker) ClientMsg(sender string, msg []string) {
	//  Service name + body
	if len(msg) < 2 {
		panic("len(msg) < 2")
	}

	service_frame, msg := popStr(msg)
	service := broker.ServiceRequire(service_frame)

	//  Set reply return identity to client sender
	m := []string{sender, ""}
	msg = append(m, msg...)

	//  If we got a MMI service request, process that internally
	if len(service_frame) >= 4 && service_frame[:4] == "mmi." {
		var return_code string
		if service_frame == "mmi.service" {
			name := msg[len(msg)-1]
			service, ok := broker.services[name]
			if ok && len(service.waiting) > 0 {
				return_code = "200"
			} else {
				return_code = "404"
			}
		} else {
			return_code = "501"
		}

		msg[len(msg)-1] = return_code

		//  Remove & save client return envelope and insert the
		//  protocol header and service name, then rewrap envelope.
		client, msg := unwrap(msg)
		broker.socket.SendMessage(client, "", mdapi.MDPC_CLIENT, service_frame, msg)
	} else {
		//  Else dispatch the message to the requested service
		service.Dispatch(msg)
	}
}

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


Question: // SetMeta is used to set arbitrary k/v pairs of metadata on a job.

func (j *Job) SetMeta(key, val string) *Job {
	if j.Meta == nil {
		j.Meta = make(map[string]string)
	}
	j.Meta[key] = val
	return j
}

def extract_metas(bs4):

    meta_tags = []

    metas = bs4.select('meta')

    for meta in metas:

        meta_content = {}

        meta_attrs = [
            'charset',
            'name',
            'content',
            'property',
            'http-equiv',
            'itemprop'
        ]

        for attr in meta_attrs:
            if meta.has_attr(attr):
                meta_content.update({attr: meta[attr]})

        meta_tags.append(meta_content)

    return meta_tags

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


Question:
Reads pipes for the freshest output.

@param string $caller   The name of the method that needs fresh outputs
@param bool   $blocking Whether to use blocking calls or not

@throws LogicException in case output has been disabled or process is not started

private function readPipesForOutput($caller, $blocking = false)
    {
        if ($this->outputDisabled) {
            throw new LogicException('Output has been disabled.');
        }

        $this->requireProcessIsStarted($caller);

        $this->updateStatus($blocking);
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end

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


Question:
Dump a GeoJSON-like LineString object to WKT.

    Input parameters and return value are the LINESTRING equivalent to
    :func:`_dump_point`.

def _dump_linestring(obj, decimals):

    coords = obj['coordinates']
    ls = 'LINESTRING (%s)'
    ls %= ', '.join(' '.join(_round_and_pad(c, decimals)
                             for c in pt) for pt in coords)
    return ls

def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)

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


Question:
Create the migration.

@return bool

protected function createMigration()
    {
        $migrationFile = base_path("/database/migrations") . "/" . date('Y_m_d_His')
            . "_create_settings_table.php";

        $output = $this->laravel->view->make('settings::generators.migration')->render();

        if (!file_exists($migrationFile) && $fs = fopen($migrationFile, 'x')) {
            fwrite($fs, $output);
            fclose($fs);

            return true;
        }

        return false;
    }

private function checkResultCount(array $result, $query)
    {
        if (count($result) === 0) {
            throw new RowNotFoundException('Row not found for query: ' . $query);
        }

        if (count($result) > 1) {
            throw new MultipleRowFoundException('Multiple row found for query: ' . $query);
        }
    }

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


Question: // raftConfig returns a new Raft config for the store.

func (s *Store) raftConfig() *raft.Config {
	config := raft.DefaultConfig()
	if s.SnapshotThreshold != 0 {
		config.SnapshotThreshold = s.SnapshotThreshold
	}
	if s.SnapshotInterval != 0 {
		config.SnapshotInterval = s.SnapshotInterval
	}
	if s.HeartbeatTimeout != 0 {
		config.HeartbeatTimeout = s.HeartbeatTimeout
	}
	return config
}

def rack_options # :nodoc:
      symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options|
        rack_options[:environment] = environment
        rack_options[:Port] = rack_options.delete :port
        rack_options[:Host] = rack_options.delete :host
        rack_options[:app] = machined
      end
    end

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


Question: Protected Single Meta

protected function _singleMeta($name, $content)
    {
        if( stripos($name, 'http:') === 0 )
        {
            $name = ' http-equiv="'.str_ireplace('http:', NULL, $name).'"';
        }
        elseif( stripos($name, 'property:') === 0 )
        {
            $name = ' property="'.str_ireplace('property:', NULL, $name).'"';
        }
        else
        {
            $name = ' name="'.str_ireplace('name:', NULL, $name).'"';
        }

        if( ! empty($content) )
        {
            $content = ' content="'.$content.'"';
        }
        else
        {
            $content = '';
        }

        return '<meta' . $name . $content . ' />' . EOL;
    }

public static function isAlreadyProcessed($classMetadata)
    {
        $path_hub = self::PATH_HUB;
        $path_mask = self::PATH_MASK_BY_HUB;

        return (!empty($classMetadata->$path_hub) || !empty($classMetadata->$path_mask));
    }

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


Question: // UserAgent echoes the incoming User-Agent header

func (h *HTTPBin) UserAgent(w http.ResponseWriter, r *http.Request) {
	body, _ := json.Marshal(&userAgentResponse{
		UserAgent: r.Header.Get("User-Agent"),
	})
	writeJSON(w, body, http.StatusOK)
}

public static function UrlExsist ($url, $timeout = 30, $protocol_version = self::VERSION_1_1) {
		$result = static::HeadRequest($url, $timeout, $protocol_version);
		return isset($result['http']['status']['code']) && $result['http']['status']['code'] !== '404';
	}

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


Question:
Validates the non-severity options passed to a rule, based on its schema.
@param {{create: Function}} rule The rule to validate
@param {Array} localOptions The options for the rule, excluding severity
@returns {void}

function validateRuleSchema(rule, localOptions) {
    if (!ruleValidators.has(rule)) {
        const schema = getRuleOptionsSchema(rule);

        if (schema) {
            ruleValidators.set(rule, ajv.compile(schema));
        }
    }

    const validateRule = ruleValidators.get(rule);

    if (validateRule) {
        validateRule(localOptions);
        if (validateRule.errors) {
            throw new Error(validateRule.errors.map(
                error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
            ).join(""));
        }
    }
}

function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) {
            var result;
            var lastLocation;
            var propertyWithInvalidInitializer;
            var errorLocation = location;
            var grandparent;
            var isInExternalModule = false;
            loop: while (location) {
                // Locals of a source file are not in scope (because they get merged into the global symbol table)
                if (location.locals && !isGlobalSourceFile(location)) {
                    if (result = getSymbol(location.locals, name, meaning)) {
                        var useResult = true;
                        if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
                            // symbol lookup restrictions for function-like declarations
                            // - Type parameters of a function are in scope in the entire function declaration, including the parameter
                            //   list and return type. However, local types are only in scope in the function body.
                            // - parameters are only in the scope of function body
                            // This restriction does not apply to JSDoc comment types because they are parented
                            // at a higher level than type parameters would normally be
                            if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 273 /* JSDocComment */) {
                                useResult = result.flags & 262144 /* TypeParameter */
                                    ? lastLocation === location.type ||
                                        lastLocation.kind === 142 /* Parameter */ ||
                                        lastLocation.kind === 141 /* TypeParameter */
                                    : false;
                            }
                            if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) {
                                // parameters are visible only inside function body, parameter list and return type
                                // technically for parameter list case here we might mix parameters and variables declared in function,
                                // however it is detected separately when checking initializers of parameters
                                // to make sure that they reference no variables declared after them.
                                useResult =
                                    lastLocation.kind === 142 /* Parameter */ ||
                                        (lastLocation === location.type &&
                                            result.valueDeclaration.kind === 142 /* Parameter */);
                            }
                        }
                        if (useResult) {
                            break loop;
                        }
                        else {
                            result = undefined;
                        }
                    }
                }
                switch (location.kind) {
                    case 256 /* SourceFile */:
                        if (!ts.isExternalOrCommonJsModule(location))
                            break;
                        isInExternalModule = true;
                    case 225 /* ModuleDeclaration */:
                        var moduleExports = getSymbolOfNode(location).exports;
                        if (location.kind === 256 /* SourceFile */ || ts.isAmbientModule(location)) {
                            // It's an external module. First see if the module has an export default and if the local
                            // name of that export default matches.
                            if (result = moduleExports["default"]) {
                                var localSymbol = ts.getLocalSymbolForExportDefault(result);
                                if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
                                    break loop;
                                }
                                result = undefined;
                            }
                            // Because of module/namespace merging, a module's exports are in scope,
                            // yet we never want to treat an export specifier as putting a member in scope.
                            // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
                            // Two things to note about this:
                            //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
                            //        on an export specifier is that it might find the export specifier itself, and try to
                            //        resolve it as an alias. This will cause the checker to consider the export specifier
                            //        a circular alias reference when it might not be.
                            //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
                            //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
                            //        which is not the desired behavior.
                            if (moduleExports[name] &&
                                moduleExports[name].flags === 8388608 /* Alias */ &&
                                ts.getDeclarationOfKind(moduleExports[name], 238 /* ExportSpecifier */)) {
                                break;
                            }
                        }
                        if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) {
                            break loop;
                        }
                        break;
                    case 224 /* EnumDeclaration */:
                        if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
                            break loop;
                        }
                        break;
                    case 145 /* PropertyDeclaration */:
                    case 144 /* PropertySignature */:
                        // TypeScript 1.0 spec (April 2014): 8.4.1
                        // Initializer expressions for instance member variables are evaluated in the scope
                        // of the class constructor body but are not permitted to reference parameters or
                        // local variables of the constructor. This effectively means that entities from outer scopes
                        // by the same name as a constructor parameter or local variable are inaccessible
                        // in initializer expressions for instance member variables.
                        if (ts.isClassLike(location.parent) && !(location.flags & 32 /* Static */)) {
                            var ctor = findConstructorDeclaration(location.parent);
                            if (ctor && ctor.locals) {
                                if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) {
                                    // Remember the property node, it will be used later to report appropriate error
                                    propertyWithInvalidInitializer = location;
                                }
                            }
                        }
                        break;
                    case 221 /* ClassDeclaration */:
                    case 192 /* ClassExpression */:
                    case 222 /* InterfaceDeclaration */:
                        if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) {
                            if (lastLocation && lastLocation.flags & 32 /* Static */) {
                                // TypeScript 1.0 spec (April 2014): 3.4.1
                                // The scope of a type parameter extends over the entire declaration with which the type
                                // parameter list is associated, with the exception of static member declarations in classes.
                                error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
                                return undefined;
                            }
                            break loop;
                        }
                        if (location.kind === 192 /* ClassExpression */ && meaning & 32 /* Class */) {
                            var className = location.name;
                            if (className && name === className.text) {
                                result = location.symbol;
                                break loop;
                            }
                        }
                        break;
                    // It is not legal to reference a class's own type parameters from a computed property name that
                    // belongs to the class. For example:
                    //
                    //   function foo<T>() { return '' }
                    //   class C<T> { // <-- Class's own type parameter T
                    //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
                    //   }
                    //
                    case 140 /* ComputedPropertyName */:
                        grandparent = location.parent.parent;
                        if (ts.isClassLike(grandparent) || grandparent.kind === 222 /* InterfaceDeclaration */) {
                            // A reference to this grandparent's type parameters would be an error
                            if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) {
                                error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
                                return undefined;
                            }
                        }
                        break;
                    case 147 /* MethodDeclaration */:
                    case 146 /* MethodSignature */:
                    case 148 /* Constructor */:
                    case 149 /* GetAccessor */:
                    case 150 /* SetAccessor */:
                    case 220 /* FunctionDeclaration */:
                    case 180 /* ArrowFunction */:
                        if (meaning & 3 /* Variable */ && name === "arguments") {
                            result = argumentsSymbol;
                            break loop;
                        }
                        break;
                    case 179 /* FunctionExpression */:
                        if (meaning & 3 /* Variable */ && name === "arguments") {
                            result = argumentsSymbol;
                            break loop;
                        }
                        if (meaning & 16 /* Function */) {
                            var functionName = location.name;
                            if (functionName && name === functionName.text) {
                                result = location.symbol;
                                break loop;
                            }
                        }
                        break;
                    case 143 /* Decorator */:
                        // Decorators are resolved at the class declaration. Resolving at the parameter
                        // or member would result in looking up locals in the method.
                        //
                        //   function y() {}
                        //   class C {
                        //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
                        //   }
                        //
                        if (location.parent && location.parent.kind === 142 /* Parameter */) {
                            location = location.parent;
                        }
                        //
                        //   function y() {}
                        //   class C {
                        //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
                        //   }
                        //
                        if (location.parent && ts.isClassElement(location.parent)) {
                            location = location.parent;
                        }
                        break;
                }
                lastLocation = location;
                location = location.parent;
            }
            if (result && nameNotFoundMessage && noUnusedIdentifiers) {
                result.isReferenced = true;
            }
            if (!result) {
                result = getSymbol(globals, name, meaning);
            }
            if (!result) {
                if (nameNotFoundMessage) {
                    if (!errorLocation ||
                        !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) &&
                            !checkAndReportErrorForExtendingInterface(errorLocation)) {
                        error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg));
                    }
                }
                return undefined;
            }
            // Perform extra checks only if error reporting was requested
            if (nameNotFoundMessage) {
                if (propertyWithInvalidInitializer) {
                    // We have a match, but the reference occurred within a property initializer and the identifier also binds
                    // to a local variable in the constructor where the code will be emitted.
                    var propertyName = propertyWithInvalidInitializer.name;
                    error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg));
                    return undefined;
                }
                // Only check for block-scoped variable if we are looking for the
                // name with variable meaning
                //      For example,
                //          declare module foo {
                //              interface bar {}
                //          }
                //      const foo/*1*/: foo/*2*/.bar;
                // The foo at /*1*/ and /*2*/ will share same symbol with two meaning
                // block - scope variable and namespace module. However, only when we
                // try to resolve name in /*1*/ which is used in variable position,
                // we want to check for block- scoped
                if (meaning & 2 /* BlockScopedVariable */) {
                    var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
                    if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */) {
                        checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
                    }
                }
                // If we're in an external module, we can't reference value symbols created from UMD export declarations
                if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) {
                    var decls = result.declarations;
                    if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) {
                        error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name);
                    }
                }
            }
            return result;
        }

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


Question:
/*
Checks if node name matches debugger host/domain.

function isExactDomainMatch(part: string, debuggeeHost: string): boolean {
  return part.startsWith("www.")
    ? part.substr("www.".length) === debuggeeHost
    : part === debuggeeHost;
}

public function andLeftnodeEquals($leftnode, $alias = null)
    {
        list($alias, $suffix) = $this->getAliasAndSuffix($alias);

        return $this->andWhere($alias.'._leftnode = :leftnode'.$suffix)
                        ->setParameter('leftnode'.$suffix, $leftnode);
    }

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


Question:
Returns the number of words in $value.

@param string $value

@return int

private static function numWords($value)
    {
        $value = preg_replace('/<.[^<>]*?>/', ' ', $value);
        $value = preg_replace('/ | /i', ' ', $value);
        $value = preg_replace('/[.(),;:!?%#$\'\"_+=\/\-“”’]*/', '', $value);
        preg_match_all('/\b\w+\b/', $value, $words);

        return count($words[0]);
    }

func (p *Parameter) StoreStrLen_or_IndPtr(v api.SQLLEN) *api.SQLLEN {
	p.StrLen_or_IndPtr = v
	return &p.StrLen_or_IndPtr

}

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


Question:
Create a matrix which contains the delta between each XY position and
        each UV position.

def build_xy_zeropoint(imgxy, refxy, searchrad=3.0, histplot=False,
                       figure_id=1, plotname=None, interactive=True):

    print('Computing initial guess for X and Y shifts...')

    # run C function to create ZP matrix
    zpmat = cdriz.arrxyzero(imgxy.astype(np.float32), refxy.astype(np.float32),
                            searchrad)

    xp, yp, flux, zpqual = find_xy_peak(zpmat, center=(searchrad, searchrad))
    if zpqual is not None:
        print('Found initial X and Y shifts of ', xp, yp)
        print('    with significance of ', zpqual, 'and ', flux, ' matches')
    else:
        # try with a lower sigma to detect a peak in a sparse set of sources
        xp, yp, flux, zpqual = find_xy_peak(
            zpmat, center=(searchrad, searchrad), sigma=1.0
        )
        if zpqual:
            print('Found initial X and Y shifts of ', xp, yp)
            print('    with significance of ', zpqual, 'and ',
                  flux, ' matches')
        else:
            print('!' * 80)
            print('!')
            print('! WARNING: No valid shift found within a search radius of ',
                  searchrad, ' pixels.')
            print('!')
            print('!' * 80)

    if histplot:
        zpstd = flux // 5
        if zpstd < 10:
            zpstd = 10
        if zpqual is None:
            zpstd = 10

        title_str = ("Histogram of offsets: Peak has %d matches at "
                     "(%0.4g, %0.4g)" % (flux, xp, yp))

        plot_pars = {'data': zpmat, 'figure_id': figure_id, 'vmax': zpstd,
                     'xp': xp, 'yp': yp, 'searchrad': searchrad,
                     'title_str': title_str, 'plotname': plotname,
                     'interactive': interactive}

        plot_zeropoint(plot_pars)

    return xp, yp, flux, zpqual

private void drawThumbShadow(float screenCoord, Canvas canvas) {
        thumbShadowMatrix.setTranslate(screenCoord + thumbShadowXOffset, textOffset + thumbHalfHeight + thumbShadowYOffset);
        translatedThumbShadowPath.set(thumbShadowPath);
        translatedThumbShadowPath.transform(thumbShadowMatrix);
        canvas.drawPath(translatedThumbShadowPath, shadowPaint);
    }

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


Question:
Throw exception with given message with actual helper class name before
@param string $msg
@return void

protected function warning ($msg) {
		if (self::$loggingAndExceptions) {
			\MvcCore\Debug::BarDump('[' . get_class($this) . '] ' . $msg, \MvcCore\IDebug::DEBUG);
		}
	}

public static function createFromArray($statusCode, array $data = [])
    {
        $response = new static($statusCode);

        if (isset($data['body']) && \is_array($data['body'])) {
            foreach ($data['body'] as $key => $bodyData) {
                $response->addBody(Body::createFromArray($key, $bodyData ?: []));
            }
        }

        if (isset($data['description'])) {
            $response->setDescription($data['description']);
        }

        if (isset($data['headers'])) {
            foreach ($data['headers'] as $key => $header) {
                $response->addHeader(NamedParameter::createFromArray($key, $header));
            }
        }

        return $response;
    }

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


Question: // openPackageURL reads package info from a HTTP URL

func openPackageURL(path string) (*PackageFile, error) {
	resp, err := http.Get(path)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	p, err := ReadPackageFile(resp.Body)
	if err != nil {
		return nil, err
	}
	p.path = path
	p.fileSize = uint64(resp.ContentLength)
	if lm := resp.Header.Get("Last-Modified"); len(lm) > 0 {
		t, _ := time.Parse(time.RFC1123, lm) // ignore malformed timestamps
		p.fileTime = t
	}
	return p, nil
}

public static BufferedReader newBufferedReader(Path path, Charset charset) throws IOException {
        return new BufferedReader(new InputStreamReader(newInputStream(path), charset));
    }

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


Question:
Get a list of a user's playlists on Last.fm
@deprecated as of march 15 2016, 'user.getplaylists' method is not available
@param array $methodVars An array with the following required values: <i>user</i>
@return array

public function getPlaylists($methodVars)
    {
        // Check for required variables
        if (!empty($methodVars['user'])) {
            $vars = array(
                'method' => 'user.getplaylists',
                'api_key' => $this->auth->apiKey
            );
            $vars = array_merge($vars, $methodVars);

            if ($call = $this->apiGetCall($vars)) {
                if (count($call->playlists->playlist) > 0) {
                    $i = 0;
                    foreach ($call->playlists->playlist as $playlist) {
                        $playlists[$i]['id'] = (string) $playlist->id;
                        $playlists[$i]['title'] = (string) $playlist->title;
                        $playlists[$i]['date'] = strtotime(trim((string) $playlist->date));
                        $playlists[$i]['size'] = (string) $playlist->size;
                        $playlists[$i]['streamalbe'] = (string) $playlist->streamable;
                        $playlists[$i]['creator'] = (string) $playlist->creator;
                        $i++;
                    }

                    return $playlists;
                } else {
                    throw new NoResultsException('This user has no past events');
                }
            } else {
                return false;
            }
        } else {
            throw new InvalidArgumentException('You must include artist variable in the call for this method');
        }
    }

protected function convertParam($platform, $param, $type = null)
    {
        if (is_object($param)) {
            if (!method_exists($param, '__toString')) {
                if ($param instanceof DateTimeInterface) {
                    $param = $param->format('Y-m-d H:i:s');
                } elseif (Type::hasType($type)) {
                    $type  = Type::getType($type);
                    $param = $type->convertToDatabaseValue($param, $platform);
                } else {
                    throw new Exception('Given query param is an instance of ' . get_class($param) . ' and could not be converted to a string');
                }
            }
        } elseif (is_array($param)) {
            if ($this->isNestedArray($param)) {
                $param = json_encode($param, JSON_UNESCAPED_UNICODE);
            } else {
                $param = implode(
                    ', ',
                    array_map(
                        function ($part) {
                            return '"' . (string) $part . '"';
                        },
                        $param
                    )
                );

                return '(' . $param . ')';
            }
        } else {
            $param = e($param);
        }

        return '"' . (string) $param . '"';
    }

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


Question: // WatchMinionReports implements ModelMigration.

func (mig *modelMigration) WatchMinionReports() (NotifyWatcher, error) {
	phase, err := mig.Phase()
	if err != nil {
		return nil, errors.Annotate(err, "retrieving phase")
	}
	prefix := mig.minionReportId(phase, "")
	filter := func(rawId interface{}) bool {
		id, ok := rawId.(string)
		if !ok {
			return false
		}
		return strings.HasPrefix(id, prefix)
	}
	return newNotifyCollWatcher(mig.st, migrationsMinionSyncC, filter), nil
}

public function addModule(Module $module)
    {
        if ($this->db !== $module->getDB())
            throw new MigrationException("The DB instances should be the same");

        $name = self::normalizeModule($module->getModule());
        $this->modules[$name] = $module;
        return $this;
    }

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


Question: Determine whether the element is a member of the set. The set is an object that maps namespaces to objects. The objects then map local tagnames to the value true if that tag is part of the set

function isA(elt, set) {
  if (typeof set === 'string') {
    // convenience case for testing a particular HTML element
    return elt.namespaceURI === NAMESPACE.HTML &&
      elt.localName === set;
  }
  var tagnames = set[elt.namespaceURI];
  return tagnames && tagnames[elt.localName];
}

boolean matchText(
            final boolean blockMatching,
            final int markupLevel, final int markupBlockIndex) {

        checkMarkupLevel(markupLevel);

        if (this.markupSelectorItem.anyLevel() || markupLevel == 0 || (this.prev != null && this.prev.matchedMarkupLevels[markupLevel - 1])) {
            // This text has not matched yet, but might match, so we should check

            this.matchesThisLevel = this.markupSelectorItem.matchesText(markupBlockIndex, this.markupBlockMatchingCounter);

            if (matchesPreviousOrCurrentLevel(markupLevel)) {
                // This filter was already matched by a previous level (through an "open" event), so just delegate to next.

                if (this.next != null) {
                    return this.next.matchText(blockMatching, markupLevel, markupBlockIndex);
                }
                return (blockMatching? true : this.matchesThisLevel);

            } else if (this.matchesThisLevel) {
                // This filter was not matched before. So the fact that it matches now means we need to consume it,
                // therefore not delegating.

                return (this.next == null);

            }

        } else if (matchesPreviousOrCurrentLevel(markupLevel)) {
            // This filter was already matched by a previous level (through an "open" event), so just delegate to next.

            if (this.next != null) {
                return this.next.matchText(blockMatching, markupLevel, markupBlockIndex);
            }
            return blockMatching;

        }

        return false;

    }

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


Question:
Transforms an Array to a 2D Array of chunks

@method chunk
@param  {Array}  obj  Array to parse
@param  {Number} size Chunk size ( integer )
@return {Array}       Chunked Array

function ( obj, size ) {
		var result = [],
		    nth    = number.round( ( obj.length / size ), "up" ),
		    start  = 0,
		    i      = -1;

		while ( ++i < nth ) {
			start = i * size;
			result.push( array.limit( obj, start, size ) );
		}

		return result;
	}

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(searchRequest.getCursor(), CURSOR_BINDING);
            protocolMarshaller.marshall(searchRequest.getExpr(), EXPR_BINDING);
            protocolMarshaller.marshall(searchRequest.getFacet(), FACET_BINDING);
            protocolMarshaller.marshall(searchRequest.getFilterQuery(), FILTERQUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getHighlight(), HIGHLIGHT_BINDING);
            protocolMarshaller.marshall(searchRequest.getPartial(), PARTIAL_BINDING);
            protocolMarshaller.marshall(searchRequest.getQuery(), QUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryOptions(), QUERYOPTIONS_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryParser(), QUERYPARSER_BINDING);
            protocolMarshaller.marshall(searchRequest.getReturn(), RETURN_BINDING);
            protocolMarshaller.marshall(searchRequest.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(searchRequest.getSort(), SORT_BINDING);
            protocolMarshaller.marshall(searchRequest.getStart(), START_BINDING);
            protocolMarshaller.marshall(searchRequest.getStats(), STATS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Returns true for limit anchored in element and placed between text nodes.  v
[text node] [text node]
 -> true  v
 [text node]
 -> false  v
[text node][text node]
 -> false (limit is anchored in text node)

function betweenTextNodes( container, offset ) {
				// Not anchored in element or limit is on the edge.
				if ( container.type != CKEDITOR.NODE_ELEMENT || offset === 0 || offset == container.getChildCount() )
					return 0;

				return container.getChild( offset - 1 ).type == CKEDITOR.NODE_TEXT &&
					container.getChild( offset ).type == CKEDITOR.NODE_TEXT;
			}

def consume_at_rule(input = @tokens)
      rule = {}

      rule[:tokens] = input.collect do
        rule[:name]    = input.consume[:value]
        rule[:prelude] = []

        while token = input.consume
          node = token[:node]

          if node == :comment # Non-standard.
            next

          elsif node == :semicolon
            break

          elsif node === :'{'
            # Note: The spec says the block should _be_ the consumed simple
            # block, but Simon Sapin's CSS parsing tests and tinycss2 expect
            # only the _value_ of the consumed simple block here. I assume I'm
            # interpreting the spec too literally, so I'm going with the
            # tinycss2 behavior.
            rule[:block] = consume_simple_block(input)[:value]
            break

          elsif node == :simple_block && token[:start] == '{'
            # Note: The spec says the block should _be_ the simple block, but
            # Simon Sapin's CSS parsing tests and tinycss2 expect only the
            # _value_ of the simple block here. I assume I'm interpreting the
            # spec too literally, so I'm going with the tinycss2 behavior.
            rule[:block] = token[:value]
            break

          else
            input.reconsume
            rule[:prelude] << consume_component_value(input)
          end
        end
      end

      create_node(:at_rule, rule)
    end

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