Question:
@param ConfigureEvent $event

@throws NotFoundHttpException

public function onConfigureTreeNode(ConfigureEvent $event)
    {
        $configuration = $event->getConfiguration();
        $request = $configuration->get('request');
        $node = $configuration->get('treeNode');

        $language = $request->getLocale();
        $countryCode = $request->attributes->get('_country');

        if (!$countryCode) {
            return;
        }

        if (!$this->countries->contains($countryCode)) {
            throw new NotFoundHttpException("Country $countryCode not configured.");
        }

        $country = $this->countries->get($countryCode);

        if (!$country->getLanguages()->contains($language)) {
            throw new NotFoundHttpException("Language $language not configured for country $country.");
        }

        if (!$this->nodeChecker->isAllowed($node, $countryCode, $language)) {
            throw new NotFoundHttpException("Language $language not allowed for country $country.");
        }
    }

public function catchError(array $error_files)
    {
        $this->app->set(Web::ERROR_VIEWS, $error_files);
        $whoops = new Run;
        if ($this->debug) {
            error_reporting(E_ALL);
            $whoops->pushHandler(new PrettyPageHandler);
        } else {
            error_reporting(E_ERROR);
            $whoops->pushHandler($this->getErrorView());
        }
        $whoops->register();
        return $this;
    }

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


Question:
@param string|array $authorization
@param string $url
@param string $text

@return $this

public function linkIfCan($authorization, string $url, string $text)
    {
        return $this->addIfCan($authorization, Link::to($url, $text));
    }

def authenticate( username, password, hours = nil )

      @username, @password, @hours = username, password, hours

      if username and password

         @ticket = nil
         if @hours
            xmlRequestData = toXML( :hours, @hours )
            sendRequest( :authenticate, xmlRequestData )
         else
            sendRequest( :authenticate )
         end

         @userid = getResponseValue( :userid )
         return self if @chainAPIcalls
         return @ticket, @userid

      elsif username or password
         raise "authenticate: missing username or password"
      elsif @ticket
         raise "authenticate: #{username} is already authenticated"
      end
   end

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


Question:
Lists all of the pools in the specified account.

@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<CloudPool> object

public Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>> listWithServiceResponseAsync() {
        return listSinglePageAsync()
            .concatMap(new Func1<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>, Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>>>() {
                @Override
                public Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>> call(ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink, null));
                }
            });
    }

public function exists($params, $optParams = [])
    {
        if (is_string($params)) {
            $params = ['publicId' => $params];
        }

        return $this->sendRequest(['cloudId', 'publicId'], [
            'restAction' => 'exists',
            'uri' => '/c/<cloudId>/o/<publicId>',
            'params' => $params,
            'getParams' => $optParams,
        ], function ($response) {
            return $response->success;
        });
    }

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


Question:
Undocumented function

@param string $optionsOrMethod
@param string|mixed $path
@param string|mixed $handler
@return \Cabal\Route\Route

public function map($optionsOrMethod, $path, $handler)
    {
        $route = new Route();
        $route->map($optionsOrMethod, $path, $handler);
        $this->routes[] = $route;
        return $route;
    }

func (r Resources) upsert(method string, route string, resource *Resource) error {
	currentNode := r

	parts := strings.Split(route, "/")
	if len(parts) > 0 {
		last := len(parts) - 1

		// Upsert route of the resource.
		for _, part := range parts[:last] {
			if part == "" {
				continue
			}
			part = "/" + part

			node, found := currentNode[part]
			if !found {
				node = &Resource{
					Resources: Resources{},
					Responses: Responses{},
				}

				currentNode[part] = node
			}
			currentNode = node.Resources
		}

		if parts[last] != "" {
			// Upsert resource into the very bottom of the node tree.
			part := "/" + parts[last]
			node, found := currentNode[part]
			if !found {
				node = &Resource{
					Resources: Resources{},
					Responses: Responses{},
				}
			}
			currentNode[part] = node
			currentNode = node.Resources
		}
	}

	method = strings.ToLower(method)
	if _, found := currentNode[method]; found {
		return nil
		// return fmt.Errorf("duplicated method route: %v %v", method, route)
	}

	currentNode[method] = resource

	return nil
}

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


Question: // String returns a string representation of this invocation chain

func (ic InvocationChain) String() string {
	s, _ := json.Marshal(ic)
	return string(s)
}

public Collection<ProposalResponse> queryByChaincode(QueryByChaincodeRequest queryByChaincodeRequest, Collection<Peer> peers) throws InvalidArgumentException, ProposalException {
        return sendProposal(queryByChaincodeRequest, peers);
    }

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


Question: // SetPriority sets the Priority field's value.

func (s *CreateJobInput) SetPriority(v int64) *CreateJobInput {
	s.Priority = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Check if profiler is enabled.

@static
@return bool

public static function isEnabled()
    {
        if (!self::$_checkedEnabled) {
            self::$_checkedEnabled = true;

            $conf = self::getConfiguration();

            $enabled = false;
            if (strtolower($conf->trigger) == 'always') {
                $enabled = true;
            } elseif (strtolower($conf->trigger) == 'parameter') {
                if ((isset($_GET['profile']) && $_GET['profile'] == true) || (isset($_COOKIE['profile']) && $_COOKIE['profile'] == true)) {
                    $enabled = true;
                }
            }

            // Process filters
            if ($enabled && $conf->enableFilters) {

                // sampling filter
                if ($enabled && rand(0,100000) > $conf->filters->sampling * 1000) {
                    $enabled = false;
                }

                // request uri whitelist/blacklist
                $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; // TODO: use script name instead for cli?
                if ($enabled && $conf->filters->requestUriWhiteList && !preg_match($conf->filters->requestUriWhiteList, $requestUri)) {
                    $enabled = false;
                }
                if ($enabled && $conf->filters->requestUriBlackList && preg_match($conf->filters->requestUriBlackList, $requestUri)) {
                    $enabled = false;
                }

                // note: timeThreshold and memoryThreshold will be checked before persisting records. In these cases data will still be recorded during the request
            }

            if ($enabled) {
                self::enable();
            }
        }
        return self::$_enabled;
    }

public function addBooleanAccessorOpen(&$script, Column $column)
    {
        $name = self::getBooleanAccessorName($column);
        $visibility = $column->getAccessorVisibility();

        $script .= "
    ".$visibility." function $name(";
        if ($column->isLazyLoad()) {
            $script .= "ConnectionInterface \$con = null";
        }

        $script .= ")
    {";
    }

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


Question:
If the upload task is initialized with a notification configuration, this handles its
creation.

@param uploadInfo upload information and statistics

private void createNotification(UploadInfo uploadInfo) {
        if (params.notificationConfig == null || params.notificationConfig.getProgress().message == null)
            return;

        UploadNotificationStatusConfig statusConfig = params.notificationConfig.getProgress();
        notificationCreationTimeMillis = System.currentTimeMillis();

        NotificationCompat.Builder notification = new NotificationCompat.Builder(service, params.notificationConfig.getNotificationChannelId())
                .setWhen(notificationCreationTimeMillis)
                .setContentTitle(Placeholders.replace(statusConfig.title, uploadInfo))
                .setContentText(Placeholders.replace(statusConfig.message, uploadInfo))
                .setContentIntent(statusConfig.getClickIntent(service))
                .setSmallIcon(statusConfig.iconResourceID)
                .setLargeIcon(statusConfig.largeIcon)
                .setColor(statusConfig.iconColorResourceID)
                .setGroup(UploadService.NAMESPACE)
                .setProgress(100, 0, true)
                .setOngoing(true);

        statusConfig.addActionsToNotificationBuilder(notification);

        Notification builtNotification = notification.build();

        if (service.holdForegroundNotification(params.id, builtNotification)) {
            notificationManager.cancel(notificationId);
        } else {
            notificationManager.notify(notificationId, builtNotification);
        }
    }

private void parseMultipartFormData() {
        String multipartFormDataParser = getSetting(MULTIPART_FORM_DATA_PARSER_SETTING_NAME);
        if (multipartFormDataParser == null) {
            throw new MultipartRequestParseException("The setting name 'multipartFormDataParser' for multipart " +
                    "form data parsing is not specified. Please specify 'multipartFormDataParser' via Aspect so " +
                    "that Translet can parse multipart form data.");
        }

        MultipartFormDataParser parser = getBean(multipartFormDataParser);
        if (parser == null) {
            throw new MultipartRequestParseException("No bean named '" + multipartFormDataParser + "' is defined");
        }
        parser.parse(getRequestAdapter());
    }

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


Question:
convert a array to object

@param $array
@return stdClass

public static function arrayToObject($array)
    {
        $obj = new \stdClass();
        foreach($array as $k => $v)
        {
            if(strlen($k))
            {
                if(is_array($v) && count($v) > 0)
                {
                    // recursive
                    $instance = new static;
                    $obj->{$k} = $instance->arrayToObject($v);
                }
                else
                {
                    $obj->{$k} = $v;
                }
            }
        }
        return $obj;
    }

public function withHolder(Holder $holder): self
    {
        $obj = clone $this;
        $obj->_holder = $holder;
        return $obj;
    }

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


Question:
Detects Named Entities in a {@link Dictionaries} by NE type ignoring case.

@param tokens
the tokenized sentence
@return spans of the Named Entities

public final Span[] nercToSpans(final String[] tokens) {
    final List<Span> neSpans = new ArrayList<Span>();
    for (final Map<String, String> neDict : this.dictionaries
        .getIgnoreCaseDictionaries()) {
      for (final Map.Entry<String, String> neEntry : neDict.entrySet()) {
        final String neForm = neEntry.getKey();
        final String neType = neEntry.getValue();
        final List<Integer> neIds = StringUtils
            .exactTokenFinderIgnoreCase(neForm, tokens);
        if (!neIds.isEmpty()) {
          for (int i = 0; i < neIds.size(); i += 2) {
            final Span neSpan = new Span(neIds.get(i), neIds.get(i + 1),
                neType);
            neSpans.add(neSpan);
            if (this.debug) {
              System.err.println(neSpans.toString());
            }
          }
        }
      }
    }
    return neSpans.toArray(new Span[neSpans.size()]);
  }

def text(self, cls = 'current', retaintokenisation=False, previousdelimiter="",strict=False, correctionhandling=CorrectionHandling.CURRENT, normalize_spaces=False):
        """"""
        if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
        if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandling.EITHER):
            for e in self:
                if isinstance(e, New) or isinstance(e, Current):
                    s = previousdelimiter + e.text(cls, retaintokenisation,"", strict, correctionhandling)
                    if normalize_spaces:
                        return norm_spaces(s)
                    else:
                        return s
        if correctionhandling in (CorrectionHandling.ORIGINAL, CorrectionHandling.EITHER):
            for e in self:
                if isinstance(e, Original):
                    s =  previousdelimiter + e.text(cls, retaintokenisation,"", strict, correctionhandling)
                    if normalize_spaces:
                        return norm_spaces(s)
                    else:
                        return s
        raise NoSuchText

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


Question:
Creates a KLV streaming parser. Options are:

keyLength: specify the length of the KLV key
emitData: if true then values will be emitted as data events

function(options) {
    this.writable = true;
    this.readable = true;

    // Default key length is 16
    this.keyLength = (options && options.keyLength) || 16;

    // Check whether KLV values should be emitted as data
    this.emitData = Boolean(options && options.emitData);

    this.buffer = new Buffer(0);
    this.state = KLV_STATES.KEY;
    this.valueLength = 0;
}

public void marshall(VpcLink vpcLink, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(vpcLink.getId(), ID_BINDING);
            protocolMarshaller.marshall(vpcLink.getName(), NAME_BINDING);
            protocolMarshaller.marshall(vpcLink.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(vpcLink.getTargetArns(), TARGETARNS_BINDING);
            protocolMarshaller.marshall(vpcLink.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(vpcLink.getStatusMessage(), STATUSMESSAGE_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:
查询数据表的状态信息
@access public
@param $options
@return Command

public function collStats($options)
    {
        $cmd = ['collStats' => $options['table']];
        $command = new Command($cmd);
        $this->log('cmd', 'collStats', $cmd);
        return $command;
    }

protected function getRouteResource($route)
	{
		if (!config('openapischemas.resource_tag')) {
			$this->parentCommand->error('The "resource_tag" value in your apischemas.php configuration file must defined.');
			exit();
		}
		$routeAction = $route->getAction();
		list($class, $method) = explode('@', $routeAction['uses']);
		$reflection = new ReflectionClass($class);

		$comment = $reflection->getDocComment();
		if ($comment) {
			$docBlock = $this->docBlockFactory->create($comment);
			foreach ($docBlock->getTags() as $tag) {
				if ($tag->getName() === config('openapischemas.resource_tag')) {
					return $tag->getDescription()->render();
				}
			}
		}

		return null;
	}

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


Question: Handler of processing entity (overrided, private)

def handle_entityref(self, name):

        self.log.debug( u'Encountered entity  : {0}'.format(name) )
        if not self.removeEntity:
            self.data.append('&%s;' % name)

HalRepresentation mergeWithEmbedding(final Curies curies) {
        this.curies = this.curies.mergeWith(curies);
        if (this.links != null) {

            removeDuplicateCuriesFromEmbedding(curies);

            this.links = this.links.using(this.curies);
            if (embedded != null) {
                embedded = embedded.using(this.curies);
            }
        } else {
            if (embedded != null) {
                embedded = embedded.using(curies);
            }
        }
        return this;
    }

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


Question:
// GetMetric retrieves a metric for a given requested namespace and version.
// If provided a version of -1 the latest plugin will be returned.

func (mc *metricCatalog) GetMetric(requested core.Namespace, version int) (*metricType, error) {
	mc.mutex.Lock()
	defer mc.mutex.Unlock()

	var ns core.Namespace

	catalogedmt, err := mc.tree.GetMetric(requested.Strings(), version)
	if err != nil {
		log.WithFields(log.Fields{
			"_module": "control",
			"_file":   "metrics.go,",
			"_block":  "get-metric",
			"error":   err,
		}).Error("error getting metric")
		return nil, err
	}

	ns = catalogedmt.Namespace()

	if isDynamic, _ := ns.IsDynamic(); isDynamic {
		// when namespace is dynamic and the cataloged namespace (e.g. ns=/intel/mock/*/bar) is different than
		// the requested (e.g. requested=/intel/mock/host0/bar), than specify an instance of dynamic element,
		// so as a result the dynamic element will have set a value (e.g. ns[2].Value equals "host0")
		if ns.String() != requested.String() {
			ns = specifyInstanceOfDynamicMetric(ns, requested)
		}
	}

	returnedmt := &metricType{
		Plugin:             catalogedmt.Plugin,
		namespace:          ns,
		version:            catalogedmt.Version(),
		lastAdvertisedTime: catalogedmt.LastAdvertisedTime(),
		tags:               catalogedmt.Tags(),
		policy:             catalogedmt.Plugin.Policy().Get(catalogedmt.Namespace().Strings()),
		config:             catalogedmt.Config(),
		unit:               catalogedmt.Unit(),
		description:        catalogedmt.Description(),
		subscriptions:      catalogedmt.SubscriptionCount(),
	}
	return returnedmt, nil
}

func (m *MeterFeatures) ReadFrom(r io.Reader) (int64, error) {
	return encoding.ReadFrom(r, &m.MaxMeter, &m.BandTypes,
		&m.Capabilities, &m.MaxBands, &m.MaxColor, &defaultPad2)
}

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


Question: This method read a single parameter and build the regular expression

private function param($key, $string, $value) {

        $field_required = false;

        // If the field name ends with a '*', the parameter is considered as required
        if (preg_match('/^(.+)\*$/', $key, $bits)) {

            $key = $bits[1];
            $field_required = true;

        }

        // The $value query object contains all regex which will be used by the collector to parse the route fields
        $value->setQuery($key, $string, $field_required);

        /* Every parameter can include it's own logic into the regular expression,
         * it can use backreferences and it's expected to be used against a single parameter.
         * This means that it can't be used as is to build the route regular expression,
         * Backreferences are not useful at this point and can make the regular expression more time consuming
         * and resource hungry. This is why they are replaced with the grouping parenthesis.
         * Eg: (value) changes in (?:value)
         *
         * Delimiting characters like '^' and '$' are also meaningless in the complete regular expression and
         * need to be removed. Contrariwise, wildcards must be delimited in order to keep the whole regular
         * expression consistent, hence a '?' is added to all the '.*' or '.+' that don't already have one.
         */
        $string = preg_replace("/(?<!\\\\)\\((?!\\?)/", '(?:', $string);
        $string = preg_replace("/\\.([\\*\\+])(?!\\?)/", '.${1}?', $string);
        $string = preg_replace("/^[\\^]/", '', $string);
        $string = preg_replace("/[\\$]$/", '', $string);

        /* The produced regular expression is grouped and associated with its key (this means that the 'preg_match'
         * function will generate an associative array where the key/value association is preserved).
         * If the field is required, the regular expression is completed with a '{1}' (which make it compulsory),
         * otherwise a '?' is added.
         */
        return '(?P<'.$key.'>'.$string.')'.(($field_required) ? '{1}' : '?');

    }

public RouteMatcher getWithRegEx(String regex, Handler<HttpServerRequest> handler) {
		addRegEx(regex, handler, getBindings);
		return this;
	}

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


Question: Retrieve values from CSS and assign to this instance options.

function (name, detectorFn, imagePath) {
		var options = this.options,
		    prefix = options.classNamePrefix,
		    optionValues = detectorFn(prefix + name, imagePath);

		for (var optionName in optionValues) {
			options[name + optionName] = options[name + optionName] || optionValues[optionName];
		}
	}

def __set_style_sheet(self):

        colors = map(
            lambda x: "rgb({0}, {1}, {2}, {3})".format(x.red(), x.green(), x.blue(), int(self.__opacity * 255)),
            (self.__color, self.__background_color, self.__border_color))
        self.setStyleSheet(self.__style.format(*colors))

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


Question: Construct capacity sized stack

private void setup(BeanMetaData bmd)
    {
        if (!ivSetup)
        {
            int slotSize = bmd.container.getEJBRuntime().getMetaDataSlotSize(MethodMetaData.class);
            for (int i = 0; i < capacity; ++i)
            {
                EJBMethodInfoImpl methodInfo = bmd.createEJBMethodInfoImpl(slotSize);
                methodInfo.initializeInstanceData(null, null, null, null, null, false);
                elements[i] = methodInfo;
            }
            ivSetup = true;
        }
    }

public void add(Versioned<E> arg0) {
        _lastId = VStack.NULL_ID;
        _lastCall = LastCall.ADD;
        throw new UnsupportedOperationException();
    }

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


Question: Delete an issue from one of your repositories.

def delete(self, comment_id, issue_id=None, repo_slug=None):

        issue_id = issue_id or self.issue_id
        repo_slug = repo_slug or self.bitbucket.repo_slug or ''
        url = self.bitbucket.url('DELETE_COMMENT',
                                 username=self.bitbucket.username,
                                 repo_slug=repo_slug,
                                 issue_id=issue_id,
                                 comment_id=comment_id)
        return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth)

function (filePath) {
    var projectRoot = this.project.root
    var fullPath = resolve(projectRoot, filePath)

    return RSVP.denodeify(unlink)(fullPath)
  }

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


Question:
addItem

@param   DListDescription|string $item
@param   array                   $attribs

@return  static

public function addDesc($item, $attribs = [])
    {
        if (!$item instanceof DListDescription) {
            $item = new DListDescription($item, $attribs);
        }

        $this->content[] = $item;

        return $this;
    }

def parse_module(module):
    ''''''
    attributes = [
        (name, type_)
        for (name, type_) in getmembers(module)
        if (isclass(type_) or isfunction(type_))
        and type_.__module__ == module.__name__
        and not type_.__name__.startswith('_')
    ]

    attribute_docs = ['## {0}'.format(module.__name__), '']

    if module.__doc__:
        docstring, _ = _parse_docstring(module.__doc__)
        attribute_docs.append(docstring)

    if hasattr(module, '__all__'):
        for name in module.__all__:
            link = '+ [{0}](./{0}.md)'.format(name)
            attribute_docs.append(link)

    for (name, type_) in attributes:
        if isfunction(type_):
            attribute_docs.append(_parse_function(module, name, type_))
        else:
            attribute_docs.append(_parse_class(module, name, type_))

    return u'{0}\n'.format(
        u'\n'.join(attribute_docs).strip()
    )

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


Question:
Trim *| from the begining of the list.

@param string $keywordsString Keywords string

@return string

private function prepareStepString($keywordsString)
    {
        if (0 === mb_strpos($keywordsString, '*|', 0, 'UTF-8')) {
            $keywordsString = mb_substr($keywordsString, 2, mb_strlen($keywordsString, 'utf8') - 2, 'utf8');
        }

        return $keywordsString;
    }

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;
    }

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


Question:
Get the list of the active packages

@return  array

function getPackages() {
	var results = [];

	if (extensions && extensions.hasOwnProperty('packages')) {
		var sourceArray = extensions.packages;

		for (index = 0; index < sourceArray.length; ++index) {
		    results.push(sourceArray[index]);
		}
	}

	return results;
}

public function setProviders($providers)
    {
        $this->guardForArrayOrTraversable($providers);

        foreach ($providers as $provider) {
            $this->addProvider($provider);
        }
    }

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


Question:
d/dx  (y - lmbda)^T C = d/dx -exp(Cx + d)^T C
            = -C^T exp(Cx + d)^T C

def hessian_local_log_likelihood(self, x):

        # Observation likelihoods
        lmbda = np.exp(np.dot(x, self.C.T) + np.dot(self.inputs, self.D.T))
        return np.einsum('tn, ni, nj ->tij', -lmbda, self.C, self.C)

def kdf_hmac(self):

        encryption_algo = self['algorithm'].native

        if encryption_algo == 'pbes2':
            return self['parameters']['key_derivation_func']['parameters']['prf']['algorithm'].native

        if encryption_algo.find('.') == -1:
            if encryption_algo.find('_') != -1:
                _, hmac_algo, _ = encryption_algo.split('_', 2)
                return hmac_algo

            raise ValueError(unwrap(
                '''
                Encryption algorithm "%s" does not have a registered key
                derivation function
                ''',
                encryption_algo
            ))

        raise ValueError(unwrap(
            '''
            Unrecognized encryption algorithm "%s", can not determine key
            derivation hmac algorithm
            ''',
            encryption_algo
        ))

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


Question:
Log exception event.

        Compatible with logging.exception signature.

def exception(self, message, *args, **kwargs):

        self.system.exception(message, *args, **kwargs)

func ErrorLoggerT(typ gin.ErrorType) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if !c.Writer.Written() {
			json := c.Errors.ByType(typ).JSON()
			if json != nil {
				c.JSON(-1, json)
			}
		}
	}
}

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


Question: // SetDevelopmentSchemaArn sets the DevelopmentSchemaArn field's value.

func (s *UpgradePublishedSchemaInput) SetDevelopmentSchemaArn(v string) *UpgradePublishedSchemaInput {
	s.DevelopmentSchemaArn = &v
	return s
}

func (w *Wallet) isDevEnv() bool {
	switch uint32(w.ChainParams().Net) {
	case uint32(chaincfg.RegressionNetParams.Net):
	case uint32(chaincfg.SimNetParams.Net):
	default:
		return false
	}
	return true
}

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


Question:
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n935.

    Positional arguments:
    data -- bytearray data to read.

    Returns:
    Dict.

def get_bss_load(_, data):

    answers = {
        'station count': (data[1] << 8) | data[0],
        'channel utilisation': data[2] / 255.0,
        'available admission capacity': (data[4] << 8) | data[3],
    }
    return answers

func (c *Ctrie) snapshot(readOnly bool) *Ctrie {
	if readOnly && c.readOnly {
		return c
	}
	for {
		root := c.readRoot()
		main := gcasRead(root, c)
		if c.rdcssRoot(root, main, root.copyToGen(&generation{}, c)) {
			if readOnly {
				// For a read-only snapshot, we can share the old generation
				// root.
				return newCtrie(root, c.hashFactory, readOnly)
			}
			// For a read-write snapshot, we need to take a copy of the root
			// in the new generation.
			return newCtrie(c.readRoot().copyToGen(&generation{}, c), c.hashFactory, readOnly)
		}
	}
}

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


Question:
Initiates color object from given string

@param  string $value

@return AbstractColor

public function initFromString($value)
    {
        if ($color = $this->rgbaFromString($value)) {
            $this->r = $color[0];
            $this->g = $color[1];
            $this->b = $color[2];
            $this->a = $this->alpha2gd($color[3]);
        }

        return $this;
    }

public void setOutRGB(IntRange outRGB) {
        this.outRed = outRGB;
        this.outGreen = outRGB;
        this.outBlue = outRGB;

        CalculateMap(inRed, outRGB, mapRed);
        CalculateMap(inGreen, outRGB, mapGreen);
        CalculateMap(inBlue, outRGB, mapBlue);
    }

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


Question:
Creates a clone of a provided array, with any empty strings removed.

@private
@param   {Array<*>} originalArray
@return  {Array<*>}

function(originalArray) {
            var cleanArray = [],
                i = -1;

            for (i = 0; i < originalArray.length; i++) {
                if (originalArray[i] !== '') {
                    cleanArray.push(originalArray[i]);
                }
            }

            return cleanArray;
        }

public function set(array $data, $id = null) {
        $id = null === $id ? $this->idGen++ : $id;
        $this->data[$id] = $data;
        self::$dirty[$this->class] = true;
        return $id;
    }

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


Question:
// speedMonitor handles tracking the number of hashes per second the mining
// process is performing.  It must be run as a goroutine.

func (m *CPUMiner) speedMonitor() {
	log.Tracef("CPU miner speed monitor started")

	var hashesPerSec float64
	var totalHashes uint64
	ticker := time.NewTicker(time.Second * hpsUpdateSecs)
	defer ticker.Stop()

out:
	for {
		select {
		// Periodic updates from the workers with how many hashes they
		// have performed.
		case numHashes := <-m.updateHashes:
			totalHashes += numHashes

		// Time to update the hashes per second.
		case <-ticker.C:
			curHashesPerSec := float64(totalHashes) / hpsUpdateSecs
			if hashesPerSec == 0 {
				hashesPerSec = curHashesPerSec
			}
			hashesPerSec = (hashesPerSec + curHashesPerSec) / 2
			totalHashes = 0
			if hashesPerSec != 0 {
				log.Debugf("Hash speed: %6.0f kilohashes/s",
					hashesPerSec/1000)
			}

		// Request for the number of hashes per second.
		case m.queryHashesPerSec <- hashesPerSec:
			// Nothing to do.

		case <-m.speedMonitorQuit:
			break out
		}
	}

	m.wg.Done()
	log.Tracef("CPU miner speed monitor done")
}

public function onHeartbeat()
    {
        $now = microtime(true);
        $nextHeartbeat = ($this->lastWrite ?: $now) + $this->options["heartbeat"];

        if ($now >= $nextHeartbeat) {
            $this->writer->appendFrame(new HeartbeatFrame(), $this->writeBuffer);
            $this->flushWriteBuffer()->done(function () {
                $this->heartbeatTimer = $this->eventLoop->addTimer($this->options["heartbeat"], [$this, "onHeartbeat"]);
            });

        } else {
            $this->heartbeatTimer = $this->eventLoop->addTimer($nextHeartbeat - $now, [$this, "onHeartbeat"]);
        }
    }

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


Question:
Appends a script element at the end of the <head> with the content of code,
after transforming it.

function run(transformFn, code, url, options) {
  const scriptEl = document.createElement('script');
  scriptEl.text = transformCode(transformFn, code, url, options);
  headEl.appendChild(scriptEl);
}

function ElmRunner(filename, baseDir, defaults) {
  var relativePath = path.relative(baseDir, filename);
  var baseName = path.basename(filename, path.extname(filename));

  this.filename = filename;
  this.defaults = defaults || {};

  this.moduleName = resolveModuleName(relativePath);
  this.outputPath = path.join(path.dirname(filename), baseName + ".js");

  var self = this;
  withCheckedPath(this.outputPath, function() {
    try {
      compile.call(self);
      execute.call(self);
      wrap.call(self);
    } catch (e) {
      return e;
    }

    return true;
  });
}

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


Question:
Extend the right side of the the collection by appending values from
        the iterable *other*.

def extend(self, other):

        def extend_trans(pipe):
            values = list(other.__iter__(pipe)) if use_redis else other
            for v in values:
                self._append_helper(v, pipe)

        if self._same_redis(other, RedisCollection):
            use_redis = True
            self._transaction(extend_trans, other.key)
        else:
            use_redis = False
            self._transaction(extend_trans)

def siblings(self, as_resources=False):

		'''

		'''

		siblings = set()

		# loop through parents and get children
		for parent in self.parents(as_resources=True):
			for sibling in parent.children(as_resources=as_resources):
				siblings.add(sibling)

		# remove self
		if as_resources:
			siblings.remove(self)
		if not as_resources:
			siblings.remove(self.uri)

		return list(siblings)

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


Question:
@param Node\Example $example

@return array

protected function processExample(Node\Example $example)
    {
        $currentExample = [
            'keyword' => $example->getKeyword(),
            'name' => $example->getName(),
            'line' => $example->getLine(),
            'description' => $example->getDescription(),
            'id' => $example->getId(),
            'rows' => [],
        ];

        if (is_array($example->getRows())) {
            foreach ($example->getRows() as $row) {
                array_push($currentExample['rows'], $this->processExampleRow($row));
            }
        }

        return $currentExample;
    }

public VNode el(String tag, VNodeData data, Object... children) {
    return this.function.create(tag, data, children);
  }

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


Question:
Sets the movie instance for this button.

        :param      movie | <QtGui.QMovie>

def setMovie(self, movie):

        if self._movie is not None:
            self._movie.frameChanged.disconnect(self._updateFrame)

        self._movie = movie

        if movie is not None:
            self._updateFrame()
            self._movie.frameChanged.connect(self._updateFrame)
            self.destroyed.connect(self.cleanup)

def create(self, **kwargs):
        """"""
        if 'monitor' in kwargs:
            value = self._format_monitor_parameter(kwargs['monitor'])
            kwargs['monitor'] = value
        return super(Pool, self)._create(**kwargs)

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


Question: arg is for internal usage only

function( elems, callback, arg ) {
		var value, key, ret = [],
			i = 0,
			length = elems.length,
			// jquery objects are treated as arrays
			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( key in elems ) {
				value = callback( elems[ key ], key, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return ret.concat.apply( [], ret );
	}

func New(target io.Writer) Archive {
	gw := gzip.NewWriter(target)
	tw := tar.NewWriter(gw)
	return Archive{
		gw: gw,
		tw: tw,
	}
}

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


Question: // UnmarshalJSON JSONアンマーシャル(配列、オブジェクトが混在するためここで対応)

func (m *MobileGatewaySIMGroup) UnmarshalJSON(data []byte) error {
	targetData := strings.Replace(strings.Replace(string(data), " ", "", -1), "\n", "", -1)
	if targetData == `[]` {
		return nil
	}

	tmp := &struct {
		DNS1 string `json:"dns_1,omitempty"`
		DNS2 string `json:"dns_2,omitempty"`
	}{}
	if err := json.Unmarshal(data, &tmp); err != nil {
		return err
	}

	m.DNS1 = tmp.DNS1
	m.DNS2 = tmp.DNS2
	return nil
}

public WebhookData parseWebhookData(String webhook) {
        if (webhook == null || webhook.trim()
                .length() <= 0) {
            return null;
        }
        webhook = LEFT_QUOTATION.matcher(webhook)
                .replaceAll("{");
        webhook = RIGHT_QUOTATION.matcher(webhook)
                .replaceAll("}");
        webhook = BACKLASH_QUOTATION.matcher(webhook)
                .replaceAll("\"");

        return FastjsonDecoder.decodeAsBean(webhook, WebhookData.class);
    }

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


Question: // Tracef logs a trace statement

func (s *StanLogger) Tracef(format string, v ...interface{}) {
	s.executeLogCall(func(logger Logger, format string, v ...interface{}) {
		if s.trace {
			logger.Tracef(format, v...)
		}
	}, format, v...)
}

public function dumpBacktrace(Environment $env, $context, $depth)
    {
        if (!$this->isEnabled($env)) {
            return null;
        }

        return $this->dump($env, $context, debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, $depth));
    }

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


Question:
// Merge combines the HyperLogLog with that of the input Set.  Since the
// HyperLogLog is marshalled in the value, it unmarshals it first.

func (s *Set) Merge(v *metricpb.SetValue) error {
	return s.Combine(v.HyperLogLog)
}

def update_if_outdated(folder):

    folders = []
    while os.path.isdir(folder):
        folders.append(folder)
        # Get info.yml
        with open(os.path.join(folder, "info.yml")) as ymlfile:
            content = yaml.load(ymlfile)
        folder = os.path.join(utils.get_project_root(), content['data-source'])
    raw_source_file = folder
    if not os.path.isfile(raw_source_file):
        logging.error("File '%s' was not found.", raw_source_file)
        logging.error("You should eventually execute 'hwrt download'.")
        sys.exit(-1)
    dt = os.path.getmtime(raw_source_file)
    source_mtime = datetime.datetime.utcfromtimestamp(dt)
    folders = folders[::-1]  # Reverse order to get the most "basic one first"

    for target_folder in folders:
        target_mtime = utils.get_latest_successful_run(target_folder)
        if target_mtime is None or source_mtime > target_mtime:
            # The source is later than the target. That means we need to
            # refresh the target
            if "preprocessed" in target_folder:
                logging.info("Preprocessed file was outdated. Update...")
                preprocess_dataset.main(os.path.join(utils.get_project_root(),
                                                     target_folder))
            elif "feature-files" in target_folder:
                logging.info("Feature file was outdated. Update...")
                create_ffiles.main(target_folder)
            elif "model" in target_folder:
                logging.info("Model file was outdated. Update...")
                create_model.main(target_folder, True)
            target_mtime = datetime.datetime.utcnow()
        else:
            logging.info("'%s' is up-to-date.", target_folder)
        source_mtime = target_mtime

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


Question:
Returns the height needed to draw the remaining text.

@return a height

public float remainingHeight() {
        float result = 0f;
        for (Iterator i = images.iterator(); i.hasNext();) {
            Image image = (Image) i.next();
            result += image.getScaledHeight();
        }
        return remainingLinesHeight() + cellspacing + 2 * cellpadding + result;
    }

def stacked_graph(labels, data, normal_data, len_categories, args, colors):
    """"""
    val_min = find_min(data)

    for i in range(len(labels)):
        if args['no_labels']:
            # Hide the labels.
            label = ''
        else:
            label = "{:<{x}}: ".format(labels[i],
                                       x=find_max_label_length(labels))

        print(label, end="")
        values = data[i]
        num_blocks = normal_data[i]

        for j in range(len(values)):
            print_row(values[j], int(num_blocks[j]), val_min, colors[j])

        tail = ' {}{}'.format(args['format'].format(sum(values)),
                              args['suffix'])
        print(tail)

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


Question: // See: http://duktape.org/api.html#duk_push_uint

func (d *Context) PushUint(val uint) {
	C.duk_push_uint(d.duk_context, C.duk_uint_t(val))
}

func Unary(op syntax.Token, x Value) (Value, error) {
	switch op {
	case syntax.MINUS:
		switch x := x.(type) {
		case Int:
			return zero.Sub(x), nil
		case Float:
			return -x, nil
		}
	case syntax.PLUS:
		switch x.(type) {
		case Int, Float:
			return x, nil
		}
	case syntax.TILDE:
		if xint, ok := x.(Int); ok {
			return xint.Not(), nil
		}
	case syntax.NOT:
		return !x.Truth(), nil
	}
	return nil, fmt.Errorf("unknown unary op: %s %s", op, x.Type())
}

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


Question:
Private: checks if value is already contained in a nested object.

* `object` {Object} that might contain the value
* `key` {String} key of the nested object that might contain the value
* `value` {String} to check for

Returns {Boolean}

function _mediaMatch(object, key, value) {
  if (!{}.hasOwnProperty.call(object, key)) {
    return false;
  }
  return Boolean(object[key].indexOf(value) >= 0);
}

function(packedValue)
    {

        var result;

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

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


Question: returns true or false

function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
	{
		global $php_errormsg;

		if (!function_exists('db2_connect')) return null;

		// This needs to be set before the connect().
		// Replaces the odbc_binmode() call that was in Execute()
		ini_set('ibm_db2.binmode', $this->binmode);

		if (isset($php_errormsg)) $php_errormsg = '';
		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';

		if ($argDatabasename && empty($argDSN)) {

			if (stripos($argDatabasename,'UID=') && stripos($argDatabasename,'PWD=')) $this->_connectionID = db2_pconnect($argDatabasename,null,null);
			else $this->_connectionID = db2_pconnect($argDatabasename,$argUsername,$argPassword);
		} else {
			if ($argDatabasename) $schema = $argDatabasename;
			if (stripos($argDSN,'UID=') && stripos($argDSN,'PWD=')) $this->_connectionID = db2_pconnect($argDSN,null,null);
			else $this->_connectionID = db2_pconnect($argDSN,$argUsername,$argPassword);
		}
		if (isset($php_errormsg)) $php_errormsg = '';

		$this->_errorMsg = @db2_conn_errormsg();
		if ($this->_connectionID && $this->autoRollback) @db2_rollback($this->_connectionID);
		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);

		if ($this->_connectionID && isset($schema)) $this->Execute("SET SCHEMA=$schema");
		return $this->_connectionID != 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:
// Equivalent to:
// bytes.Compare(S.Words[S.WordIndex[i]][S.SuffixIndex[i]:], S.Words[S.WordIndex[j]][S.SuffixIndex[j]:]) <= 0
// but faster

func (SW *sortWrapper) Less(i, j int) bool {
	x := SW.WordIndex[i]
	y := SW.WordIndex[j]
	a := SW.Words[x]
	b := SW.Words[y]
	pa := SW.SuffixIndex[i]
	pb := SW.SuffixIndex[j]
	na := len(a)
	nb := len(b)
	for pa < na && pb < nb {
		wa := a[pa]
		wb := b[pb]
		if wa < wb {
			return true
		}
		if wb < wa {
			return false
		}
		pa++
		pb++
	}
	return pa == na
}

func (fm *FieldMapping) Options() document.IndexingOptions {
	var rv document.IndexingOptions
	if fm.Store {
		rv |= document.StoreField
	}
	if fm.Index {
		rv |= document.IndexField
	}
	if fm.IncludeTermVectors {
		rv |= document.IncludeTermVectors
	}
	if fm.DocValues {
		rv |= document.DocValues
	}
	return rv
}

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


Question:
Parse display name to extract user firstname & lastname
@return array

public static function parseDisplayName($string, $data)
    {
        $response = array();

        if (isset($data->sn) && !empty($data->sn)) {
            $response['firstname'] = trim(str_replace($data->sn, "", substr($string, 0, strpos($string, " - "))));
            $response['lastname'] = $data->sn;
        } elseif (isset($data->mail) && strpos($data->mail, ".")) {
            $response['firstname'] = trim(substr($data->mail, 0, strpos($data->mail, ".")));
            $response['lastname'] = trim(substr($data->mail, strpos($data->mail, ".")+1, strpos($data->mail, "@")-strpos($data->mail, ".")-1));
        } else {
            $tempData = array();
            $tempData = trim(substr($string, 0, strpos($string, " - ")));

            if (!empty($tempData)) {

                $tempData = explode(" ", $tempData);

                if (is_array($tempData) && count($tempData)) {
                    $response['lastname'] = $tempData[0];
                    unset($tempData[0]);
                    $response['firstname'] = implode(" ", $tempData);
                }
            }
        }

        //Uppercase first letters
        $response['firstname'] = ucfirst($response['firstname']);
        $response['lastname'] = ucfirst($response['lastname']);

        return $response;
    }

protected function getHeadersAsArray($rawHeaders)
    {
        $headers = [];

        foreach (explode("\r\n", (string) $rawHeaders) as $header) {
            if (false !== strpos($header, ':')) {
                list($name, $headerStr) = explode(':', $header, 2);
                $headers[trim($name)] = trim($headerStr);
            }
        }

        return $headers;
    }

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


Question: // SetDirection sets the Direction field's value.

func (s *CreateResolverEndpointInput) SetDirection(v string) *CreateResolverEndpointInput {
	s.Direction = &v
	return s
}

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

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

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


Question:
Create a base migration file.

@return string

protected function createBaseMigration()
	{
		$name = 'create_' . $this->argument('table') . '_table';

		$path = $this->laravel['path'].'/database/migrations';

		return $this->laravel['migration.creator']->create($name, $path);
	}

public function import(array $tables)
    {
        foreach ($tables as $table => $data) {

            if (!$this->query($this->getSqlCreateTable($table, $data))) {
                throw new RuntimeException("Failed to import database table $table");
            }

            $alter = $this->getSqlAlterTable($table, $data);

            if (!empty($alter) && !$this->query($alter)) {
                throw new RuntimeException("Failed to alter table $table");
            }
        }
    }

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


Question:
Validate and format lowdata from incoming unserialized request data

    This tool requires that the hypermedia_in tool has already been run.

def lowdata_fmt():
    '''

    '''

    if cherrypy.request.method.upper() != 'POST':
        return

    data = cherrypy.request.unserialized_data

    # if the data was sent as urlencoded, we need to make it a list.
    # this is a very forgiving implementation as different clients set different
    # headers for form encoded data (including charset or something similar)
    if data and isinstance(data, collections.Mapping):
        # Make the 'arg' param a list if not already
        if 'arg' in data and not isinstance(data['arg'], list):
            data['arg'] = [data['arg']]

        # Finally, make a Low State and put it in request
        cherrypy.request.lowstate = [data]
    else:
        cherrypy.serving.request.lowstate = data

def parse_header_links(self):
        """"""
        for linktype, linkinfo in self.url_connection.links.items():
            url = linkinfo["url"]
            name = u"Link: header %s" % linktype
            self.add_url(url, name=name)
        if 'Refresh' in self.headers:
            from ..htmlutil.linkparse import refresh_re
            value = self.headers['Refresh'].strip()
            mo = refresh_re.match(value)
            if mo:
                url = unicode_safe(mo.group("url"))
                name = u"Refresh: header"
                self.add_url(url, name=name)
        if 'Content-Location' in self.headers:
            url = self.headers['Content-Location'].strip()
            name = u"Content-Location: header"
            self.add_url(url, name=name)

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


Question:
Returns the adapter supporting the given format.

@param TableInterface $table
@param string         $format

@return \Ekyna\Component\Table\Export\AdapterInterface|null

private function getAdapter(TableInterface $table, $format)
    {
        $adapters = $table->getConfig()->getExportAdapters();

        foreach ($adapters as $adapter) {
            if ($adapter->supports($format)) {
                return $adapter;
            }
        }

        return null;
    }

def excel_main(file):

    os.chdir(file["dir"])
    name_ext = file["filename_ext"]

    # Filename without extension
    name = file["filename_no_ext"]
    # remove foreign characters to prevent wiki uploading errors
    name = normalize_name(name)
    print("processing: {}".format(name_ext))
    logger_excel.info("processing: {}".format(name_ext))

    pending_csv = []
    final = OrderedDict()
    logger_excel.info("variables initialized")

    # Create a temporary folder and set paths
    dir_tmp = create_tmp_dir()

    """
    EACH DATA TABLE WILL BE STRUCTURED LIKE THIS
    "paleo_chron": "paleo",
    "pc_idx": 1,
    "model_idx": "",
    "table_type": "measurement",
    "table_idx": 1,
    "name": sheet,
    "filename": sheet,
    "data": { column data }
    """

    # Open excel workbook with filename
    try:
        workbook = xlrd.open_workbook(name_ext)
        logger_excel.info("opened XLRD workbook")

    except Exception as e:
        # There was a problem opening a file with XLRD
        print("Failed to open Excel workbook: {}".format(name))
        workbook = None
        logger_excel.debug("excel: xlrd failed to open workbook: {}, {}".format(name, e))

    if workbook:

        # Build sheets, but don't make full filenames yet. Need to parse metadata sheet first to get datasetname.
        sheets, ct_paleo, ct_chron, metadata_str = _get_sheet_metadata(workbook, name)

        # METADATA WORKSHEETS
        # Parse Metadata sheet and add to output dictionary
        if metadata_str:
            logger_excel.info("parsing worksheet: {}".format(metadata_str))
            final = cells_dn_meta(workbook, metadata_str, 0, 0, final)

        # Now that we have the dataSetName, we can use it to build filenames
        dsn = __get_datasetname(final, name)
        filename = str(dsn) + ".lpd"
        sheets = __set_sheet_filenames(sheets, dsn)

        dir_bag = os.path.join(dir_tmp, "bag")
        dir_data = os.path.join(dir_bag, 'data')

        # Make folders in tmp
        os.mkdir(os.path.join(dir_bag))
        os.mkdir(os.path.join(dir_data))

        # PALEO AND CHRON SHEETS
        for sheet in sheets:
            logger_excel.info("parsing data worksheet: {}".format(sheet["new_name"]))
            sheet_meta, sheet_csv = _parse_sheet(workbook, sheet)
            if sheet_csv and sheet_meta:
                pending_csv.append(sheet_csv)
                sheet["data"] = sheet_meta

        # create the metadata skeleton where we will place the tables. dynamically add empty table blocks for data.
        skeleton_paleo, skeleton_chron = _create_skeleton_1(sheets)

        # Reorganize sheet metadata into LiPD structure
        d_paleo, d_chron = _place_tables_main(sheets, skeleton_paleo, skeleton_chron)

        # Add organized metadata into final dictionary
        final['paleoData'] = d_paleo
        final['chronData'] = d_chron

        # OUTPUT

        # Create new files and dump data in dir_data
        os.chdir(dir_data)

        # WRITE CSV
        _write_data_csv(pending_csv)

        # JSON-LD
        # Invoke DOI Resolver Class to update publisher data
        try:
            logger_excel.info("invoking doi resolver")
            final = DOIResolver(file["dir"], name, final).main()
        except Exception as e:
            print("Error: doi resolver failed: {}".format(name))
            logger_excel.debug("excel: doi resolver failed: {}, {}".format(name, e))

        # Dump final_dict to a json file.
        final["lipdVersion"] = 1.2
        final["createdBy"] = "excel"
        write_json_to_file(final)

        # Move files to bag root for re-bagging
        # dir : dir_data -> dir_bag
        logger_excel.info("start cleanup")
        dir_cleanup(dir_bag, dir_data)

        # Create a bag for the 3 files
        finish_bag(dir_bag)

        # dir: dir_tmp -> dir_root
        os.chdir(file["dir"])

        # Check if same lpd file exists. If so, delete so new one can be made
        if os.path.isfile(filename):
            os.remove(filename)

        # Zip dir_bag. Creates in dir_root directory
        logger_excel.info("re-zip and rename")
        zipper(root_dir=dir_tmp, name="bag", path_name_ext=os.path.join(file["dir"], filename))

    # Move back to dir_root for next loop.
    os.chdir(file["dir"])

    # Cleanup and remove tmp directory
    shutil.rmtree(dir_tmp)

    return dsn

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


Question: // GenError calls Output to print to the standard logger.

func (l *Logger) GenError(format string, v ...interface{}) error {
	s := fmt.Sprintf(format, v...)
	l.base.SetPrefix(l2s[LError])
	l.base.Output(2, s)
	return errors.New(s)
}

def run(self):

        try:
            threading.Thread.run(self)
        except Exception:
            t, v, tb = sys.exc_info()
            error = traceback.format_exception_only(t, v)[0][:-1]
            tback = (self.name + ' Traceback (most recent call last):\n' +
                     ''.join(traceback.format_tb(tb)))
            self.fifo.put((self.name, error, tback))

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


Question: Update the experiment status in config file

def update_experiment():
    ''''''
    experiment_config = Experiments()
    experiment_dict = experiment_config.get_all_experiments()
    if not experiment_dict:
        return None
    for key in experiment_dict.keys():
        if isinstance(experiment_dict[key], dict):
            if experiment_dict[key].get('status') != 'STOPPED':
                nni_config = Config(experiment_dict[key]['fileName'])
                rest_pid = nni_config.get_config('restServerPid')
                if not detect_process(rest_pid):
                    experiment_config.update_experiment(key, 'status', 'STOPPED')
                    continue
                rest_port = nni_config.get_config('restServerPort')
                startTime, endTime = get_experiment_time(rest_port)
                if startTime:
                    experiment_config.update_experiment(key, 'startTime', startTime)
                if endTime:
                    experiment_config.update_experiment(key, 'endTime', endTime)
                status = get_experiment_status(rest_port)
                if status:
                    experiment_config.update_experiment(key, 'status', status)

def form_valid(self, form):
        """"""

        self.object = form.save(commit=False)
        self.object.project = self.project

        if self.kwargs.get('stage_id', None):
            current_stage = models.Stage.objects.get(pk=self.kwargs.get('stage_id'))
            self.object.stage = current_stage

        self.object.save()

        # Good to make note of that
        messages.add_message(self.request, messages.SUCCESS, 'Configuration %s created' % self.object.key)

        return super(ProjectConfigurationCreate, self).form_valid(form)

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


Question:
//
// Validate - checks for missing required fields, etc
//

func (pTypeDef *UUIDTest) Validate() error {
	if pTypeDef.Myid == nil {
		return fmt.Errorf("UUIDTest: Missing required field: myid")
	}
	return nil
}

public static function makeAndValidate(array $data, array $rules = [], array $translates = [], string $scene = '')
    {
        return new static($data, $rules, $translates, $scene, true);
    }

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


Question:
This function perform http get request on member.api_url and fetches its status
        :returns: `_MemberStatus` object

def fetch_node_status(member):

        try:
            response = requests.get(member.api_url, timeout=2, verify=False)
            logger.info('Got response from %s %s: %s', member.name, member.api_url, response.content)
            return _MemberStatus.from_api_response(member, response.json())
        except Exception as e:
            logger.warning("Request failed to %s: GET %s (%s)", member.name, member.api_url, e)
        return _MemberStatus.unknown(member)

func (cli *Client) LeaveRoom(roomID string) (resp *RespLeaveRoom, err error) {
	u := cli.BuildURL("rooms", roomID, "leave")
	_, err = cli.MakeRequest("POST", u, struct{}{}, &resp)
	return
}

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


Question:
Sets the state machine for this instance.

@since [*next-version*]

@param StateMachineInterface|null $stateMachine The state machine instance or null

protected function _setStateMachine($stateMachine)
    {
        if ($stateMachine !== null && !($stateMachine instanceof StateMachineInterface)) {
            throw $this->_createInvalidArgumentException(
                $this->__('Argument is not a valid state machine instance'),
                null,
                null,
                $stateMachine
            );
        }

        $this->stateMachine = $stateMachine;
    }

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

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


Question: Method decorator for 'generator type' methods

def _ha_gen_method(func):
        '''  '''
        def wrapped(self, *args, **kw):
            self._reset_retries()
            while(True): # switch between all namenodes
                try:
                    results = func(self, *args, **kw)
                    while(True): # yield all results
                        yield results.next()
                except RequestError as e:
                    self.__handle_request_error(e)
                except socket.error as e:
                    self.__handle_socket_error(e)
        return wrapped

def changed(self):

        if not self.parents:
            return []
        return ChangedFileNodesGenerator([n for n in
                                self._get_paths_for_status('modified')], self)

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


Question:
Replace the fields of the model factory.

@param  string  $name
@param  string  $stub
@return string

protected function replaceFields($name, &$stub)
    {
        if (empty($fillable = $this->getFillable())) {
            return str_replace('fields', '//', $stub);
        }

        $fields = 'return [';

        foreach ($fillable as $column) {
            $fields .= PHP_EOL."        '{$column}' => \$faker->word,";
        }

        return str_replace('fields', $fields.PHP_EOL.'    ];', $stub);
    }

func (s *CreateModelInput) SetDescription(v string) *CreateModelInput {
	s.Description = &v
	return s
}

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


Question:
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
    command cmd returns the STDOUT of the command

def _psrdp(cmd):
    '''

    '''
    rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '
           '-Namespace root\\CIMV2\\TerminalServices -Computer . '
           '-Authentication 6 -ErrorAction Stop')
    return __salt__['cmd.run']('{0} ; {1}'.format(rdp, cmd),
                               shell='powershell', python_shell=True)

def show_raslog_output_show_all_raslog_raslog_entries_severity(self, **kwargs):

        config = ET.Element("config")
        show_raslog = ET.Element("show_raslog")
        config = show_raslog
        output = ET.SubElement(show_raslog, "output")
        show_all_raslog = ET.SubElement(output, "show-all-raslog")
        raslog_entries = ET.SubElement(show_all_raslog, "raslog-entries")
        severity = ET.SubElement(raslog_entries, "severity")
        severity.text = kwargs.pop('severity')

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

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


Question:
// AccessApplication returns a single application based on the
// application ID.
//
// API reference: https://api.cloudflare.com/#access-applications-access-applications-details

func (api *API) AccessApplication(zoneID, applicationID string) (AccessApplication, error) {
	uri := fmt.Sprintf(
		"/zones/%s/access/apps/%s",
		zoneID,
		applicationID,
	)

	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return AccessApplication{}, errors.Wrap(err, errMakeRequestError)
	}

	var accessApplicationDetailResponse AccessApplicationDetailResponse
	err = json.Unmarshal(res, &accessApplicationDetailResponse)
	if err != nil {
		return AccessApplication{}, errors.Wrap(err, errUnmarshalError)
	}

	return accessApplicationDetailResponse.Result, nil
}

func (db *db) ListClusters(ctx context.Context) (*appv1.ClusterList, error) {
	clusterSecrets, err := db.listClusterSecrets()
	if err != nil {
		return nil, err
	}
	clusterList := appv1.ClusterList{
		Items: make([]appv1.Cluster, len(clusterSecrets)),
	}
	hasInClusterCredentials := false
	for i, clusterSecret := range clusterSecrets {
		cluster := *secretToCluster(clusterSecret)
		clusterList.Items[i] = cluster
		if cluster.Server == common.KubernetesInternalAPIServerAddr {
			hasInClusterCredentials = true
		}
	}
	if !hasInClusterCredentials {
		clusterList.Items = append(clusterList.Items, localCluster)
	}
	return &clusterList, nil
}

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


Question:
Matches the whole input and returns the matched string
@param reader
@return
@throws IOException
@throws SyntaxErrorException

public String getMatch(InputReader reader) throws IOException, SyntaxErrorException
    {
        int rc = match(reader);
        if (rc == 1 && reader.read() == -1)
        {
            return reader.getString();
        }
        else
        {
            throw new SyntaxErrorException("syntax error"
                    + "\n"
                    + reader.getLineNumber() + ": " + reader.getLine()
                    + "\n"
                    + pointer(reader.getColumnNumber() + 2));
        }
    }

def parse(scanner, rules, scope = ParserScope.empty)
      backtracking(scanner) do
        if scope = parse_children(scanner, rules, scope.nest)
          yield scope if block_given?
          parse_result(scope)
        end
      end
    end

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


Question: Load raw numpy data into the viewer.

def load_data(self, data_np):

        image = AstroImage.AstroImage(logger=self.logger)
        image.set_data(data_np)

        self.set_image(image)

def _submit_results(self):

        if self._cur_res_id and self._cur_values:
            # Setting DefaultResult just because it is obligatory.
            self._addRawResult(self._cur_res_id, self._cur_values)
            self._reset()

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


Question: // GetAllAlexaASKSkillResources retrieves all AlexaASKSkill items from an AWS CloudFormation template

func (t *Template) GetAllAlexaASKSkillResources() map[string]*resources.AlexaASKSkill {
	results := map[string]*resources.AlexaASKSkill{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AlexaASKSkill:
			results[name] = resource
		}
	}
	return results
}

def create_utilities(self):

        self.create_stack(
            self.utilities_name,
            'amazon-utilities.yaml',
            parameters=define_parameters(
                Subnets=self.subnet_ids,
                NodeSecurityGroup=self.node_security_group
            )
        )

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


Question:
Turn a binary string of rights ("0011") into an array of right names (["read", "create"]).

@param string $rights

@return string[]

public function getNamesFromRights($rights)
    {
        $names = [];
        foreach ($this->rights as $name => $value) {
            if ($this->check($rights, $name)) {
                $names[] = $name;
            }
        }
        return $names;
    }

public function radio($options = []){
        if (is_string($options)) {
            $options = ['class' => $options];
        }elseif(is_bool($options)){
            $options = [
                'checked' => 'checked'
            ];
        }

        if (!Arr::has($options, 'type')) {
            Arr::set($options, 'type', 'radio');
        }

        return $this->input($options);
    }

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


Question:
Replace "from PyQt5 import" by "from pyqode.qt import".

    :param script: script path

def fix_imports(script):

    with open(script, 'r') as f_script:
        lines = f_script.read().splitlines()
    new_lines = []
    for l in lines:
        if l.startswith("import "):
            l = "from . " + l
        if "from PyQt5 import" in l:
            l = l.replace("from PyQt5 import", "from pyqode.qt import")
        new_lines.append(l)
    with open(script, 'w') as f_script:
        f_script.write("\n".join(new_lines))

def populate_event_que(self, que_obj):

        for ip in self.obj_dict:
            drvr_obj = self.obj_dict.get(ip).get('drvr_obj')
            drvr_obj.populate_event_que(que_obj)

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


Question:
Mark job done and add some stats

@param $id
@return bool|\Cake\Datasource\EntityInterface|mixed

public function markJobDone($id)
    {
        $entity = $this->get($id);
        $data = ['completed' => true, 'stats' => ['tries' => ($entity->stats['tries'] + 1), 'message' => $entity->stats['message'] . ($entity->stats['tries'] + 1) . '. ' . 'Success!' . PHP_EOL]];
        $this->patchEntity($entity, $data, ['validate' => false]);
        return $this->save($entity);
    }

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

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

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

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

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

		return $this->errorPayload;
	}

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


Question:
支付响应
@param Request $request
@param $paymentId
@param $money
@param $message
@param $payId
@return mixed

public function callback(Request $request, &$paymentId, &$money, &$message, &$payId)
    {
        $return = $request->get();
        // 订单号
        $payId = trim($return ['payId']);
        //支付号
        $paymentId = trim($return ['paymentId']);
        //钱数
        $money = trim($return ['money']);
        //状态
        $status = trim($return ['status']);
        // 备注
        $message = trim($return ['message']);
        //签名
        $SignMD5info = trim($return ['sign']);
        $sign = strtoupper(md5("{$paymentId}&{$money}&{$this->md5Key}"));
        if ($sign == $SignMD5info) {
            if ($status == "completion" && WalletLog::find()->where(['id' => $payId])->exists()) {
                return true;
            }
        }
        return false;
    }

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: Get sequence from genome

def precursor_sequence(loci, reference):
    """"""
    region = "%s\t%s\t%s\t.\t.\t%s" % (loci[1], loci[2], loci[3], loci[4])
    precursor = pybedtools.BedTool(str(region), from_string=True).sequence(fi=reference, s=True)
    return open(precursor.seqfn).read().split("\n")[1]

def find_index(segmentation, stroke_id):

    for i, symbol in enumerate(segmentation):
        for sid in symbol:
            if sid == stroke_id:
                return i
    return -1

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


Question:
get the container frameLayout of the current drawer

@return

public FrameLayout getContent() {
        if (mContentView == null && this.mDrawerBuilder.mDrawerLayout != null) {
            mContentView = (FrameLayout) this.mDrawerBuilder.mDrawerLayout.findViewById(R.id.content_layout);
        }
        return mContentView;
    }

public ClassRecord getClassRecord (String className)
    {
        Iterator<ClassRecord> iter = _classes.values().iterator();
        while (iter.hasNext()) {
            ClassRecord crec = iter.next();
            if (crec.name.equals(className)) {
                return crec;
            }
        }
        log.warning("No such color class", "class", className, new Exception());
        return null;
    }

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


Question: Get the current chaperone bounds draw color and brightness

def getBoundsColor(self, nNumOutputColors, flCollisionBoundsFadeDistance):
        """"""

        fn = self.function_table.getBoundsColor
        pOutputColorArray = HmdColor_t()
        pOutputCameraColor = HmdColor_t()
        fn(byref(pOutputColorArray), nNumOutputColors, flCollisionBoundsFadeDistance, byref(pOutputCameraColor))
        return pOutputColorArray, pOutputCameraColor

def channel_difference(chan, pixel, x, y)
      ChunkyPNG::Color.send(chan, pixel) + ChunkyPNG::Color.send(chan, @images.last[x,y]) - 2 * [ChunkyPNG::Color.send(chan, pixel), ChunkyPNG::Color.send(chan, @images.last[x,y])].min
    end

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


Question: // Invoke will start the given editor and return the content

func Invoke(ctx context.Context, editor string, content []byte) ([]byte, error) {
	if !ctxutil.IsTerminal(ctx) {
		return nil, errors.New("need terminal")
	}

	tmpfile, err := tempfile.New(ctx, "gopass-edit")
	if err != nil {
		return []byte{}, errors.Errorf("failed to create tmpfile %s: %s", editor, err)
	}
	defer func() {
		if err := tmpfile.Remove(ctx); err != nil {
			color.Red("Failed to remove tempfile at %s: %s", tmpfile.Name(), err)
		}
	}()

	if _, err := tmpfile.Write(content); err != nil {
		return []byte{}, errors.Errorf("failed to write tmpfile to start with %s %v: %s", editor, tmpfile.Name(), err)
	}
	if err := tmpfile.Close(); err != nil {
		return []byte{}, errors.Errorf("failed to close tmpfile to start with %s %v: %s", editor, tmpfile.Name(), err)
	}

	cmdArgs, err := shellquote.Split(editor)
	if err != nil {
		return []byte{}, errors.Errorf("failed to parse EDITOR command `%s`", editor)
	}

	editor = cmdArgs[0]
	args := append(cmdArgs[1:], tmpfile.Name())

	cmd := exec.Command(editor, args...)
	cmd.Stdin = Stdin
	cmd.Stdout = Stdout
	cmd.Stderr = Stderr

	if err := cmd.Run(); err != nil {
		out.Debug(ctx, "editor - cmd: %s %+v - error: %+v", cmd.Path, cmd.Args, err)
		return []byte{}, errors.Errorf("failed to run %s with %s file: %s", editor, tmpfile.Name(), err)
	}

	nContent, err := ioutil.ReadFile(tmpfile.Name())
	if err != nil {
		return []byte{}, errors.Errorf("failed to read from tmpfile: %v", err)
	}

	// enforce unix line endings in the password store
	nContent = bytes.Replace(nContent, []byte("\r\n"), []byte("\n"), -1)
	nContent = bytes.Replace(nContent, []byte("\r"), []byte("\n"), -1)

	return nContent, nil
}

def _handle_command(self, command):

        logger.info('Handle command %r', command)

        def in_executor():
            self.handling_command = True
            try:
                if self.callback is not None:
                    self.callback(self, command)
            finally:
                self.server.call_from_executor(done)

        def done():
            self.handling_command = False

            # Reset state and draw again. (If the connection is still open --
            # the application could have called TelnetConnection.close()
            if not self.closed:
                self.cli.reset()
                self.cli.buffers[DEFAULT_BUFFER].reset()
                self.cli.renderer.request_absolute_cursor_position()
                self.vt100_output.flush()
                self.cli._redraw()

        self.server.run_in_executor(in_executor)

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


Question:
Checks that all statement options specified in annotation are supported by the database.

@param metaData
@throws SQLException

private void checkJdbcSupport(DatabaseMetaData metaData) throws SQLException {

        if (_getGeneratedKeys && !metaData.supportsGetGeneratedKeys()) {
            throw new ControlException("The database does not support getGeneratedKeys.");
        }

        if (_batchUpdate && !metaData.supportsBatchUpdates()) {
            throw new ControlException("The database does not support batchUpdates.");
        }

        if (_scrollType != JdbcControl.ScrollType.DRIVER_DEFAULT
                && !metaData.supportsResultSetConcurrency(_scrollType.getType(), _scrollType.getConcurrencyType())) {
            throw new ControlException("The database does not support the ResultSet concurrecy type: " + _scrollType.toString());
        }

        if (_holdability != JdbcControl.HoldabilityType.DRIVER_DEFAULT
                && !metaData.supportsResultSetHoldability(_holdability.getHoldability())) {
            throw new ControlException("The database does not support the ResultSet holdability type: " + _holdability.toString());
        }
    }

public function GetTableColumnsMeta($tableName, $columnNames) {
        $tableColumnsMetadata = array();
        foreach ($columnNames as $columnName) {
            $this->setDbConfigList(array());
            $dbConfig = new \Puzzlout\Framework\Dal\DbStatementConfig(null, \Puzzlout\Framework\Dal\DbExecutionType::COLUMNMETAS, new \Puzzlout\Framework\Dal\DbQueryFilters());
            $dbConfig->setQuery("SHOW COLUMNS FROM `$tableName` WHERE `Field` = '$columnName';");
            $this->addDbConfigItem($dbConfig);
            $tableColumnsMetadata[$columnName] = $this->BindParametersAndExecute();
        }
        return $tableColumnsMetadata;
    }

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


Question:
Create new object from raw comment data.

@param string $value The PHP comment string.
@param int $line The line where the comment starts.

@return self The parsed comment.

public static function create($value, $line)
    {
        $lastLine = $line + substr_count($value, "\n");

        $lines = array_map(function ($line) {
            if ('' === trim($line)) {
                return null;
            }

            $line = ltrim($line, '#*/ ');
            $line = rtrim($line, '#*/ ');

            return trim($line);
        }, explode("\n", $value));

        // Remove empty lines.
        $lines = array_filter($lines);
        $value = implode(' ', $lines);

        return new self($value, $line, $lastLine);
    }

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question: Auto Generated Code

def get_vnetwork_vswitches_output_vnetwork_vswitches_interface_name(self, **kwargs):

        config = ET.Element("config")
        get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
        config = get_vnetwork_vswitches
        output = ET.SubElement(get_vnetwork_vswitches, "output")
        vnetwork_vswitches = ET.SubElement(output, "vnetwork-vswitches")
        interface_name = ET.SubElement(vnetwork_vswitches, "interface-name")
        interface_name.text = kwargs.pop('interface_name')

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

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
Clears the cache for the commerce country.

<p>
The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
</p>

@Override
	public void clearCache(CommerceCountry commerceCountry) {
		entityCache.removeResult(CommerceCountryModelImpl.ENTITY_CACHE_ENABLED,
			CommerceCountryImpl.class, commerceCountry.getPrimaryKey());

		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

		clearUniqueFindersCache((CommerceCountryModelImpl)commerceCountry, true);
	}

public function setModelPage(\Haven\CmsBundle\Entity\TemplatePage $modelPage = null) {
        $this->model_page = $modelPage;

        return $this;
    }

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


Question:
Converts the input single value into the expected Python data type,
        raising django.core.exceptions.ValidationError if the data can't be
        converted.  Returns the converted value. Subclasses should override
        this.

def value_to_python(self, value):

        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be a bytes")

        length = len(value) - 8
        if length % 4 != 0:
            raise tldap.exceptions.ValidationError("Invalid sid")

        length = length // 4

        array = struct.unpack('<bbbbbbbb' + 'I' * length, value)

        if array[1] != length:
            raise tldap.exceptions.ValidationError("Invalid sid")

        if array[2:7] != (0, 0, 0, 0, 0):
            raise tldap.exceptions.ValidationError("Invalid sid")

        array = ("S", ) + array[0:1] + array[7:]
        return "-".join([str(i) for i in array])

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

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

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


Question:
Genera una array lista para usar con json_encode

@param array $fields
@param bool $recursive
@return array

public function json($fields = array(), $recursive = true)
    {
        $list = array();
        foreach ($this->getModels() as $model) {
            $list[] = $model->json($fields, $recursive);
        }
        return $list;
    }

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

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


Question:
CLI output of the debug backtrace

@author Art <a.molcanovas@gmail.com>

@param array  $trace The debug backtrace
@param string $label Colour id

@codeCoverageIgnore

private function traceCLI(array $trace, $label) {
            foreach ($trace as $k => $v) {
                $func = $loc = $line = '';
                $argsPresent = isset($v['args']) && !empty($v['args']);

                self::formatTraceLine($v, $func, $loc, $line);

                $this->console->write('<' . $label . 'b>#' . $k . ': </>')
                              ->write('<' . $label . '>' . ($loc ? $loc : '<<unknown file>>') . '</> ')
                              ->write('<' . $label . '>(' . ($line ? 'line ' . $line : 'unknown line') . ')</>')
                              ->write('<' . $label . '> | </>')
                              ->write('<' . $label . '>' . $func . '</>', true);

                if ($argsPresent) {
                    $this->console->write('<' . $label . 'b>Arguments:</>', true);
                    VarDumper::dump($v['args']);
                }

                $this->console->writeln('');
            }
        }

public function listCommand($services = [], $table_pattern = '')
    {
        foreach ($services ?: $this->_getDbServices() as $service) {
            /** @var \ManaPHP\DbInterface $db */
            $db = $this->_di->getShared($service);

            $this->console->writeLn(['service: `:service`', 'service' => $service], Console::FC_CYAN);
            foreach ($this->_getTables($service, $table_pattern) as $row => $table) {
                $columns = (array)$db->getMetadata($table)[Db::METADATA_ATTRIBUTES];
                $primaryKey = $db->getMetadata($table)[Db::METADATA_PRIMARY_KEY];
                foreach ($columns as $i => $column) {
                    if (in_array($column, $primaryKey, true)) {
                        $columns[$i] = $this->console->colorize($column, Console::FC_RED);
                    }
                }

                $this->console->writeLn([' :row :table(:columns)',
                    'row' => sprintf('%2d ', $row + 1),
                    'table' => $this->console->colorize($table, Console::FC_GREEN),
                    'columns' => implode(', ', $columns)]);
            }
        }
    }

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


Question:
If the type argument needs to be mapped to a new variable type class,
returns the new class name; otherwise returns the unmodified argument.

public static String getVariableType(String type) throws IOException {
        if (getVariableTypes() != null) {
            String newType = getVariableTypes().get(type);
            if (newType != null)
                return newType;
        }
        return type;
    }

public static void modify(
			int calleeValKind,
			Object callee,
			String calleeClass,
			String fieldName,
			int callerValKind,
			Object caller,
			String callerClass) {
		System.err.println("modify(          "+
				valAndValKindToString(callee, calleeClass, calleeValKind)+
				" . "+fieldName+", "+
//				"calleeClass="+calleeClass+", "+
				"caller="+valAndValKindToString(caller, callerClass, callerValKind)+", "+
//				"callerClass="+callerClass+", "+
				")");
	}

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


Question:
// FindTelegrafConfigs returns a list of telegraf configs that match filter and the total count of matching telegraf configs.
// Additional options provide pagination & sorting.

func (s *Service) FindTelegrafConfigs(ctx context.Context, filter influxdb.TelegrafConfigFilter, opt ...influxdb.FindOptions) (tcs []*influxdb.TelegrafConfig, n int, err error) {
	err = s.kv.View(ctx, func(tx Tx) error {
		tcs, n, err = s.findTelegrafConfigs(ctx, tx, filter)
		return err
	})
	return tcs, n, err
}

public function renderPaginateSelect(\Twig_Environment $twig, Pagerfanta $paginator, array $limitOptions = [], array $options = [])
    {
        $parameterName = $this->parameters->get('parameter_name');
        if (false !== $this->parameters->get('paginate') &&
            isset($parameterName['paginate'])) {
            $options = $this->getOptions($options, $this->paginateTemplate);
            $paginateName = $this->getParameterName('paginate');
            $limitOptions = !empty($limitOptions) ? $limitOptions : $this->parameters->get('allowed_paginate');

            $limits = [];
            foreach ($limitOptions as $limit) {
                $routeParams = $this->getRouteParams(
                    [$paginateName => $limit],
                    $options['route_params']
                );

                if (array_key_exists('page', $routeParams)) {
                    $routeParams['page'] = 1;
                }

                $limits[$limit] = $this->router->generate(
                    $this->getRouteName($options['route']),
                    $routeParams
                );
            }

            return $twig->render($options['template'], [
                'paginator' => $paginator,
                'limits' => $limits,
            ]);
        }

        return '';
    }

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


Question: Write `thconfig` file for the Therion project

def thconfig(txtfiles, cavename='cave'):
    """"""
    fmts_model = ['lox', '3d', 'dxf', 'kml', 'plt', 'vrml']
    outfilename = 'thconfig'

    with open(outfilename, 'w') as outfile:
        for txtfilename in txtfiles:
            print >> outfile, 'source "%s"' % convert_filename(txtfilename)
        print >> outfile

        for fmt in fmts_model:
            print >> outfile, 'export model -output "%s"' % os.path.join('models', '%s.%s' % (cavename, fmt))

        print >> outfile, 'export map -projection plan -format esri -output "%s"' % os.path.join('models', 'gis')

        print 'Wrote Therion project file %s .' % outfilename

protected function init()
    {
        $this->addCommand(new SyncCommand());
        $this->addCommand(new MakesumCommand());

        $this->addGlobalOption('e')
            ->alias('env')
            ->description('The environment application name or class.')
            ->defaultValue('dev');
    }

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


Question:
Gets the metadata for a provider.

        return: (osid.Metadata) - metadata for the provider
        *compliance: mandatory -- This method must be implemented.*

def get_provider_metadata(self):

        metadata = dict(self._mdata['provider'])
        metadata.update({'existing_id_values': self._my_map['providerId']})
        return Metadata(**metadata)

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

    table = 'meta'
    problems = []

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

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

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

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

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

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

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

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

    return gt.format_problems(problems, as_df=as_df)

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


Question:
Adds a parse warning.
@param message the warning message

public void addWarning(String message) {
		//@formatter:off
		warnings.add(new ParseWarning.Builder(this)
			.message(message)
		.build());
		//@formatter:on
	}

public function balance() {
        $data = $this->getSend()->parameters([
            'method' => 'GetNum'
        ])->json();
        if ($data['code'] == 2) {
            return $data['num'];
        }
        throw new \Exception($data['msg']);
    }

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