Question: Former, misleading name for descendants.

def children(self):
        """"""
        from warnings import warn
        warn("Deprecated. Use Scraper.descendants.", DeprecationWarning)
        for descendant in self.descendants:
            yield descendant

function hasAncestor(nodes, judge) {
                for (var i = nodes.length - 1; i >= 0; --i) {
                    if (nodes[i].isAncestorOf(judge)) return true;
                }
                return false;
            }

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


Question:
Updates the type metadata from the current jCal type and design set.

@private

function() {
      var designSet = this._designSet;

      if (this.type in designSet.value) {
        var designType = designSet.value[this.type];

        if ('decorate' in designSet.value[this.type]) {
          this.isDecorated = true;
        } else {
          this.isDecorated = false;
        }

        if (this.name in designSet.property) {
          this.isMultiValue = ('multiValue' in designSet.property[this.name]);
          this.isStructuredValue = ('structuredValue' in designSet.property[this.name]);
        }
      }
    }

def _isvalid(self, datatype):
        ''''''
        if datatype in self.meta:
            return bool(Dap._meta_valid[datatype].match(self.meta[datatype]))
        else:
            return datatype in Dap._optional_meta

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


Question:
Cancela um pagamento recorrente.

@param string $preApprovalCode

@return \SimpleXMLElement

public function cancelPreApproval($preApprovalCode)
    {
        return $this->sendTransaction([
            'email' => $this->email,
            'token' => $this->token,
        ], $this->url['preApprovalCancel'].$preApprovalCode, false);
    }

func (c *subjectRulesReviews) Create(subjectRulesReview *authorization.SubjectRulesReview) (result *authorization.SubjectRulesReview, err error) {
	result = &authorization.SubjectRulesReview{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("subjectrulesreviews").
		Body(subjectRulesReview).
		Do().
		Into(result)
	return
}

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


Question:
Set list ordering.

@param string|null $name sorter name or null to disable
@param string      $type `asc` or `desc`

@return AbstractRepository self

public function orderBy(?string $name, string $type = self::ORDER_ASC): AbstractRepository
    {
        $this->sorter['name'] = $name;
        $this->sorter['type'] = $type;

        return $this;
    }

public function run()
    {
        Model::unguard();

        // Lookup_todo_priority_type

        Lookup_todo_priority_type::create([
            'title'       => 'Green',
            'description' => 'Green',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);
        Lookup_todo_priority_type::create([
            'title'       => 'Yellow',
            'description' => 'Yellow',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);
        Lookup_todo_priority_type::create([
            'title'       => 'Red',
            'description' => 'Red',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);

        // Lookup_todo_status_type

        Lookup_todo_status_type::create([
            'title'       => 'Open',
            'description' => 'Open',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);
        Lookup_todo_status_type::create([
            'title'       => 'Closed',
            'description' => 'Closed',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);
        Lookup_todo_status_type::create([
            'title'       => 'Waiting',
            'description' => 'Waiting for someone to do something; or, something to happen.',
            'enabled'     => 1,
            'created_at' => new DateTime,
            'created_by' => 1,
            'updated_at' => new DateTime,
            'updated_by' => 1,
        ]);

        // Projects
        Project::create([
            'milestone_id' => null,
            'status_id'    => null,
            'priority_id'  => null,
            'company_id'   => null,
            'people_id'    => null,
            'website_id'   => null,
            'title'        => 'LaSalle Software',
            'description'  => 'Messages from LaSalle Software.',
            'comments'     => "",
            'enabled'      => 1,
            'due_date'     => new DateTime,
            'created_at'   => new DateTime,
            'created_by'   => 1,
            'updated_at'   => new DateTime,
            'updated_by'   => 1,
        ]);
    }

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


Question:
Return a generator for all the points that match the given filters.

        :param measurement: The measurement name
        :type measurement: str

        :param tags: Tags to look for
        :type tags: dict

        :return: Points generator

def get_points(self, measurement=None, tags=None):

        # Raise error if measurement is not str or bytes
        if not isinstance(measurement,
                          (bytes, type(b''.decode()), type(None))):
            raise TypeError('measurement must be an str or None')

        for series in self._get_series():
            series_name = series.get('measurement',
                                     series.get('name', 'results'))
            if series_name is None:
                # this is a "system" query or a query which
                # doesn't return a name attribute.
                # like 'show retention policies' ..
                if tags is None:
                    for item in self._get_points_for_series(series):
                        yield item

            elif measurement in (None, series_name):
                # by default if no tags was provided then
                # we will matches every returned series
                series_tags = series.get('tags', {})
                for item in self._get_points_for_series(series):
                    if tags is None or \
                            self._tag_matches(item, tags) or \
                            self._tag_matches(series_tags, tags):
                        yield item

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question: Find the log directory and return all the logs sorted.

def logs(self):
        """"""
        if not self.parent.loaded: self.parent.load()
        logs = self.parent.p.logs_dir.flat_directories
        logs.sort(key=lambda x: x.mod_time)
        return logs

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

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

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

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


Question:
Decode an get schema request.

@param {Object} message the message object partially initialized with the id and the verb
@param {Array} tokens the rest of the message already tokenized
@private

function readGetSchema(message, tokens) {
	message.userName = protocol.decodeString(tokens[1]);
	message.groupName = protocol.decodeString(tokens[3]);
	message.schemaName = protocol.decodeString(tokens[5]);
	message.sessionId = protocol.decodeString(tokens[7]);
}

public static DynamicMessage parseFrom(final Descriptor type, final ByteString data,
      final ExtensionRegistry extensionRegistry) throws InvalidProtocolBufferException {
    return wrap(com.google.protobuf.DynamicMessage.parseFrom(type, data, extensionRegistry));
  }

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


Question:
// Sub performs an element-wise subtraction of two matrices, this is
// equivalent to iterating over every element of m1 and subtracting the corresponding value of m2.

public function override($post_type, $post){
        if( $this->is_valid_post_type($post_type) ){
            foreach( $this->fields as $name => $vars ){
                switch( $name ){
                    case 'excerpt':
                        remove_meta_box('postexcerpt', $post_type, 'normal');
                        break;
                    case 'post_format':
                        remove_meta_box('formatdiv', $post_type, 'side');
                        break;
                    default:
                        if( false !== array_search(Taxonomy::class, class_uses($vars['class'])) ){
                            if( taxonomy_exists($name) ){
                                if( is_taxonomy_hierarchical($name) ){
                                    $box_id = $name.'div';
                                }else{
                                    $box_id = 'tagsdiv-'.$name;
                                }
                                remove_meta_box($box_id, $post_type, 'side');
                            }
                        }else{
                            // Do nothing
                        }
                        break;
                }
            }
        }
    }

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


Question:
Performs the analysis on a single Dependency.

@param dependency the dependency to analyze
@param engine the engine to perform the analysis under
@throws AnalysisException if anything goes sideways

@Override
    public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
        final File test = new File(dependency.getActualFilePath());
        if (!test.isFile()) {
            throw new AnalysisException(String.format("%s does not exist and cannot be analyzed by dependency-check",
                    dependency.getActualFilePath()));
        }
        if (grokAssembly == null) {
            LOGGER.warn("GrokAssembly didn't get deployed");
            return;
        }
        if (baseArgumentList == null) {
            LOGGER.warn("Assembly Analyzer was unable to execute");
            return;
        }
        final List<String> args = new ArrayList<>(baseArgumentList);
        args.add(dependency.getActualFilePath());
        final ProcessBuilder pb = new ProcessBuilder(args);
        try {
            final Process proc = pb.start();
            final GrokParser parser = new GrokParser();
            final AssemblyData data = parser.parse(proc.getInputStream());

            // Try evacuating the error stream
            final String errorStream = IOUtils.toString(proc.getErrorStream(), StandardCharsets.UTF_8);
            if (null != errorStream && !errorStream.isEmpty()) {
                LOGGER.warn("Error from GrokAssembly: {}", errorStream);
            }

            final int rc;
            try {
                rc = proc.waitFor();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                return;
            }
            if (rc == 3) {
                LOGGER.debug("{} is not a .NET assembly or executable and as such cannot be analyzed by dependency-check",
                        dependency.getActualFilePath());
                return;
            } else if (rc != 0) {
                LOGGER.debug("Return code {} from GrokAssembly; dependency-check is unable to analyze the library: {}",
                        rc, dependency.getActualFilePath());
                return;
            }

            // First, see if there was an error
            final String error = data.getError();
            if (error != null && !error.isEmpty()) {
                throw new AnalysisException(error);
            }
            if (data.getWarning() != null) {
                LOGGER.debug("Grok Assembly - could not get namespace on dependency `{}` - ()", dependency.getActualFilePath(), data.getWarning());
            }

            final StringBuilder sb = new StringBuilder();
            if (!StringUtils.isEmpty(data.getFileDescription())) {
                sb.append(data.getFileDescription());
            }
            if (!StringUtils.isEmpty(data.getComments())) {
                if (sb.length() > 0) {
                    sb.append("\n\n");
                }
                sb.append(data.getComments());
            }
            if (!StringUtils.isEmpty(data.getLegalCopyright())) {
                if (sb.length() > 0) {
                    sb.append("\n\n");
                }
                sb.append(data.getLegalCopyright());
            }
            if (!StringUtils.isEmpty(data.getLegalTrademarks())) {
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(data.getLegalTrademarks());
            }
            final String description = sb.toString();
            if (description.length() > 0) {
                dependency.setDescription(description);
                addMatchingValues(data.getNamespaces(), description, dependency, EvidenceType.VENDOR);
                addMatchingValues(data.getNamespaces(), description, dependency, EvidenceType.PRODUCT);
            }

            if (!StringUtils.isEmpty(data.getProductVersion())) {
                dependency.addEvidence(EvidenceType.VERSION, "grokassembly", "ProductVersion", data.getProductVersion(), Confidence.HIGHEST);
            }
            if (!StringUtils.isEmpty(data.getFileVersion())) {
                dependency.addEvidence(EvidenceType.VERSION, "grokassembly", "FileVersion", data.getFileVersion(), Confidence.HIGHEST);
            }

            if (data.getFileVersion() != null && data.getProductVersion() != null) {
                final int max = data.getFileVersion().length() > data.getProductVersion().length()
                        ? data.getProductVersion().length() : data.getFileVersion().length();
                int pos;
                for (pos = 0; pos < max; pos++) {
                    if (data.getFileVersion().charAt(pos) != data.getProductVersion().charAt(pos)) {
                        break;
                    }
                }
                final DependencyVersion fileVersion = DependencyVersionUtil.parseVersion(data.getFileVersion(), true);
                final DependencyVersion productVersion = DependencyVersionUtil.parseVersion(data.getProductVersion(), true);
                if (pos > 0) {
                    final DependencyVersion matchingVersion = DependencyVersionUtil.parseVersion(data.getFileVersion().substring(0, pos), true);
                    if (fileVersion.toString().length() == data.getFileVersion().length()) {
                        if (matchingVersion != null && matchingVersion.getVersionParts().size() > 2) {
                            dependency.addEvidence(EvidenceType.VERSION, "AssemblyAnalyzer", "FilteredVersion",
                                    matchingVersion.toString(), Confidence.HIGHEST);
                            dependency.setVersion(matchingVersion.toString());
                        }
                    }
                }
                if (dependency.getVersion() == null) {
                    if (data.getFileVersion().length() >= data.getProductVersion().length()) {
                        if (fileVersion.toString().length() == data.getFileVersion().length()) {
                            dependency.setVersion(fileVersion.toString());
                        } else if (productVersion.toString().length() == data.getProductVersion().length()) {
                            dependency.setVersion(productVersion.toString());
                        }
                    } else {
                        if (productVersion.toString().length() == data.getProductVersion().length()) {
                            dependency.setVersion(productVersion.toString());
                        } else if (fileVersion.toString().length() == data.getFileVersion().length()) {
                            dependency.setVersion(fileVersion.toString());
                        }
                    }
                }
            } else if (data.getFileVersion() != null) {
                final DependencyVersion version = DependencyVersionUtil.parseVersion(data.getFileVersion(), true);
                dependency.setVersion(version.toString());
            } else if (data.getProductVersion() != null) {
                final DependencyVersion version = DependencyVersionUtil.parseVersion(data.getProductVersion(), true);
                dependency.setVersion(version.toString());
            }

            if (!StringUtils.isEmpty(data.getCompanyName())) {
                dependency.addEvidence(EvidenceType.VENDOR, "grokassembly", "CompanyName", data.getCompanyName(), Confidence.HIGHEST);
                addMatchingValues(data.getNamespaces(), data.getCompanyName(), dependency, EvidenceType.VENDOR);
            }
            if (!StringUtils.isEmpty(data.getProductName())) {
                dependency.addEvidence(EvidenceType.PRODUCT, "grokassembly", "ProductName", data.getProductName(), Confidence.HIGHEST);
                addMatchingValues(data.getNamespaces(), data.getProductName(), dependency, EvidenceType.PRODUCT);
            }
            if (!StringUtils.isEmpty(data.getFileDescription())) {
                dependency.addEvidence(EvidenceType.PRODUCT, "grokassembly", "FileDescription", data.getFileDescription(), Confidence.HIGH);
                addMatchingValues(data.getNamespaces(), data.getFileDescription(), dependency, EvidenceType.PRODUCT);
            }

            final String internalName = data.getInternalName();
            if (!StringUtils.isEmpty(internalName)) {
                dependency.addEvidence(EvidenceType.PRODUCT, "grokassembly", "InternalName", internalName, Confidence.MEDIUM);
                addMatchingValues(data.getNamespaces(), internalName, dependency, EvidenceType.PRODUCT);
                addMatchingValues(data.getNamespaces(), internalName, dependency, EvidenceType.VENDOR);
                if (dependency.getName() == null && StringUtils.containsIgnoreCase(dependency.getActualFile().getName(), internalName)) {
                    final String ext = FileUtils.getFileExtension(internalName);
                    if (ext != null) {
                        dependency.setName(internalName.substring(0, internalName.length() - ext.length() - 1));
                    } else {
                        dependency.setName(internalName);
                    }
                }
            }

            final String originalFilename = data.getOriginalFilename();
            if (!StringUtils.isEmpty(originalFilename)) {
                dependency.addEvidence(EvidenceType.PRODUCT, "grokassembly", "OriginalFilename", originalFilename, Confidence.MEDIUM);
                addMatchingValues(data.getNamespaces(), originalFilename, dependency, EvidenceType.PRODUCT);
                if (dependency.getName() == null && StringUtils.containsIgnoreCase(dependency.getActualFile().getName(), originalFilename)) {
                    final String ext = FileUtils.getFileExtension(originalFilename);
                    if (ext != null) {
                        dependency.setName(originalFilename.substring(0, originalFilename.length() - ext.length() - 1));
                    } else {
                        dependency.setName(originalFilename);
                    }
                }
            }
            if (dependency.getName() != null && dependency.getVersion() != null) {
                try {
                    dependency.addSoftwareIdentifier(new PurlIdentifier("generic", dependency.getName(), dependency.getVersion(), Confidence.MEDIUM));
                } catch (MalformedPackageURLException ex) {
                    LOGGER.debug("Unable to create Package URL Identifier for " + dependency.getName(), ex);
                    dependency.addSoftwareIdentifier(new GenericIdentifier(
                            String.format("%s@%s", dependency.getName(), dependency.getVersion()),
                            Confidence.MEDIUM));
                }
            }
            dependency.setEcosystem(DEPENDENCY_ECOSYSTEM);
        } catch (GrokParseException saxe) {
            LOGGER.error("----------------------------------------------------");
            LOGGER.error("Failed to read the Assembly Analyzer results.");
            LOGGER.error("----------------------------------------------------");
            throw new AnalysisException("Couldn't parse Assembly Analyzer results (GrokAssembly)", saxe);
        } catch (IOException ioe) {
            throw new AnalysisException(ioe);
        }
    }

def __do_parse(self, pattern_str):

        in_ = antlr4.InputStream(pattern_str)
        lexer = STIXPatternLexer(in_)
        lexer.removeErrorListeners()  # remove the default "console" listener
        token_stream = antlr4.CommonTokenStream(lexer)

        parser = STIXPatternParser(token_stream)
        parser.removeErrorListeners()  # remove the default "console" listener
        error_listener = ParserErrorListener()
        parser.addErrorListener(error_listener)

        # I found no public API for this...
        # The default error handler tries to keep parsing, and I don't
        # think that's appropriate here.  (These error handlers are only for
        # handling the built-in RecognitionException errors.)
        parser._errHandler = antlr4.BailErrorStrategy()

        # To improve error messages, replace "<INVALID>" in the literal
        # names with symbolic names.  This is a hack, but seemed like
        # the simplest workaround.
        for i, lit_name in enumerate(parser.literalNames):
            if lit_name == u"<INVALID>":
                parser.literalNames[i] = parser.symbolicNames[i]

        # parser.setTrace(True)

        try:
            tree = parser.pattern()
            # print(tree.toStringTree(recog=parser))

            return tree
        except antlr4.error.Errors.ParseCancellationException as e:
            # The cancellation exception wraps the real RecognitionException
            # which caused the parser to bail.
            real_exc = e.args[0]

            # I want to bail when the first error is hit.  But I also want
            # a decent error message.  When an error is encountered in
            # Parser.match(), the BailErrorStrategy produces the
            # ParseCancellationException.  It is not a subclass of
            # RecognitionException, so none of the 'except' clauses which would
            # normally report an error are invoked.
            #
            # Error message creation is buried in the ErrorStrategy, and I can
            # (ab)use the API to get a message: register an error listener with
            # the parser, force an error report, then get the message out of the
            # listener.  Error listener registration is above; now we force its
            # invocation.  Wish this could be cleaner...
            parser._errHandler.reportError(parser, real_exc)

            # should probably chain exceptions if we can...
            # Should I report the cancellation or recognition exception as the
            # cause...?
            six.raise_from(ParseException(error_listener.error_message),
                           real_exc)

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


Question: // Uint32 returns request form as uint32

func (p *Params) Uint32(key string) (uint32, error) {
	v, err := strconv.ParseUint(p.Get(key), 10, 32)
	return uint32(v), err
}

func (c *HTTPClient) PostForm(url string, data url.Values) (*http.Response, error) {
	panic("Use Do")
}

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


Question:
Parse the body html and returns the body text using bs4

        :return: body text
        :rtype: str

def get_body_text(self):

        if self.body_type != 'HTML':
            return self.body

        try:
            soup = bs(self.body, 'html.parser')
        except RuntimeError:
            return self.body
        else:
            return soup.body.text

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
Make a Component options object hot.

@param {String} id
@param {Object} options

function makeOptionsHot(id, options) {
  if (options.functional) {
    const render = options.render
    options.render = (h, ctx) => {
      const instances = map[id].instances
      if (ctx && instances.indexOf(ctx.parent) < 0) {
        instances.push(ctx.parent)
      }
      return render(h, ctx)
    }
  } else {
    injectHook(options, initHookName, function() {
      const record = map[id]
      if (!record.Ctor) {
        record.Ctor = this.constructor
      }
      record.instances.push(this)
    })
    injectHook(options, 'beforeDestroy', function() {
      const instances = map[id].instances
      instances.splice(instances.indexOf(this), 1)
    })
  }
}

protected function getBodyParametersFromDocBlock(array $tags)
    {
        $parameters = collect($tags)
            ->filter(function ($tag) {
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
            })
            ->mapWithKeys(function ($tag) {
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
                if (empty($content)) {
                    // this means only name and type were supplied
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
                    $required = false;
                    $description = '';
                } else {
                    list($_, $name, $type, $required, $description) = $content;
                    $description = trim($description);
                    if ($description == 'required' && empty(trim($required))) {
                        $required = $description;
                        $description = '';
                    }
                    $required = trim($required) == 'required' ? true : false;
                }

                $type = $this->normalizeParameterType($type);
                list($description, $example) = $this->parseDescription($description, $type);
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;

                return [$name => compact('type', 'description', 'required', 'value')];
            })->toArray();

        return $parameters;
    }

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


Question:
Utility method to count the total number of "used" bytes in the list of
buffers. This would represent the size of the data if it was printed
out.

@param list
@return int

static public int sizeOf(WsByteBuffer[] list) {
        if (null == list) {
            return 0;
        }
        int size = 0;
        for (int i = 0; i < list.length; i++) {
            if (null != list[i]) {
                size += list[i].remaining();
            }
        }
        return size;
    }

public function getMemoryUsage()
    {
        if (empty($this->endMemory)) {
            $this->stop();
        }

        return $this->getFormattedMemorySize($this->endMemory - $this->startMemory);
    }

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


Question:
Similar to {@link #handle()} but intended for execution on any thread.<p/>
May throw a runtime exception in case something went wrong invoking the target saga message handler.

@Override
    public void run() {
        try {
            handle();
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    }

def process(self, metric):

        event = self._metric_to_riemann_event(metric)
        try:
            self.client.send_event(event)
        except Exception as e:
            self.log.error(
                "RiemannHandler: Error sending event to Riemann: %s", e)

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


Question:
Reload search results or load another "page".

        Parameters
        ----------
        forward : bool or None, optional
            Whether move forwards or backwards (``True`` or ``False``). If ``None``, then first page is loaded.

def updateResults(self, forward=None):

        # this choses data we need.
        files = lambda x: {
            i['snippet']['title'].replace('/', '\\'): YTStor(
                {'yid': i['id']['videoId'], 'pub_date': i['snippet']['publishedAt']},
                opts=self.yts_opts) for i in x['items']
        }
        descs = lambda x: {
            (i['snippet']['title'].replace('/', '\\') + '.txt'): YTMetaStor(
                {
                    'title': i['snippet']['title'],
                    'yid': i['id']['videoId'],
                    'desc': i['snippet']['description'],
                    'channel': i['snippet']['channelTitle'],
                    'pub_date': i['snippet']['publishedAt']
                },
                opts=dict()
            ) for i in x['items']
        }
        thumbs = lambda x: {
            (i['snippet']['title'].replace('/', '\\') + '.jpg'): YTMetaStor(
                {'url': i['snippet']['thumbnails']['high']['url'], 'pub_date': i['snippet']['publishedAt']}, opts=dict()
            ) for i in x['items']
        }

        try:
            if self.adj_tokens[forward] is None: # in case someone would somehow cross boundary.
                forward = None
        except KeyError:
            pass

        recv = None
        try:
            try:
                data = self.avail_files[ self.adj_tokens[forward] ] # maybe data is already available locally.
            except KeyError:
                recv = self.__search( self.adj_tokens[forward] ) # nope, we have to search.
        except KeyError: # wrong index in adj_tokens

            if forward is None:
                recv = self.__search()
            else:
                raise ValueError("Valid values for forward are True, False or None (default).")

        if recv is not None:

            _d = files(recv)
            if self.preferences['metadata']['desc']: _d.update(descs(recv))
            if self.preferences['metadata']['thumb']: _d.update(thumbs(recv))

            data = (None, _d) # little format unification.

        if len(self.avail_files) > 4:

            pop = self.avail_files.popitem(False) # get rid of the oldest data.
            for s in pop[1][1].values(): s.clean()

        adj_t = deepcopy(self.adj_tokens) # this will we write to avail_files, now we update self.adj_tokens.

        if data[0] is None: # get tokens from obtained results.
            try:
                self.adj_tokens[False] = recv['prevPageToken']
            except KeyError:
                self.adj_tokens[False] = None

            try:
                self.adj_tokens[True] = recv['nextPageToken']
            except KeyError:
                self.adj_tokens[True] = None

        else: # already in avail_files.
            self.adj_tokens = data[0]

        if forward is not None:
            # backup last results in avail_files:
            self.avail_files[ self.adj_tokens[not forward] ] = (adj_t, self.visible_files)

        self.visible_files = data[1]

private void moveToNext() {
        if (controller != null) {
            currentItemIndex = controller.nextItem(this, currentItemIndex);
        } else {
            currentItemIndex = defaultController.nextItem(this, currentItemIndex);
        }
    }

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


Question: Helper to write the given buffer to the persistent socket.

protected function _writeStream($buffer) {
        $fd = $this->socket_;
        $total = TStringFuncFactory::create()->strlen($buffer);

        // Early out on the trivial case
        if ($total <= 0) {
            return;
        }

        $failed = FALSE;
        $sent = 0;

        while (!$failed && $sent < $total) {

            if (!is_resource($fd)) {
                $failed = TRUE;
            }

            try {
                // Supress any error messages as it is considered part of normal
                // operation for the write to fail on a broken pipe or timeout
                $written = @fwrite($fd, $buffer, self::MAX_BYTES_PER_WRITE);

                if ($written > 0){
                    $sent += $written;
                    $buffer = substr($buffer, $written);

                } else if ($written === FALSE) {
                    if ($this->debug_) {
                        error_log("Write failed.");
                    }
                    $failed = TRUE;

                } else if ($written === 0) {
                    if ($this->debug_) {
                        error_log("Zero bytes written to socket. sent=$sent total=$total");
                    }
                    $failed = TRUE;
                } else {
                    if ($this->debug_) {
                        error_log("Unexpected fwrite return value '$written'");
                    }
                    $failed = TRUE;
                }

                if ($this->debug_) {
                    error_log("Written = $written bytes. Sent $sent of $total.");
                }

            } catch (Exception $e) {
                if ($this->debug_) {
                    error_log($e);
                }
                $failed = TRUE;
            }
        }

        if ($failed) {
            $this->_closeSocket();
        }
    }

def raw_callback(self, raw_packet):
        """"""
        if not ';PONG;' in raw_packet:
            log.info('forwarding packet %s to clients', raw_packet)
        else:
            log.debug('forwarding packet %s to clients', raw_packet)
        writers = [i[1] for i in list(clients)]
        for writer in writers:
            writer.write(str(raw_packet).encode() + CRLF)

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


Question:
Returns true if object supports attribute $name.

@param string $name

@return bool

public function hasAttribute($name)
    {
        return isset($this->properties[$name]) || isset($this->getters['get' . ucfirst($name)]);
    }

static AttrHold createFromString(final String str)
    throws BOSHException {
        if (str == null) {
            return null;
        } else {
            return new AttrHold(str);
        }
    }

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


Question:
Register seo metadata. You can register part of it using methods below right in view code.

@param Component $model
@since x.x.x

public static function registerAllSeoMeta(Component $model)
	{
		self::registerMetaTitle($model);
		self::registerMetaKeywords($model);
		self::registerMetaDescription($model);
	}

def sitemap_meta_description
      return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
    end

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


Question:
Sets the movie's volume

@param volume
@return this Movie

public Movie setVolume(final double volume)
    {
        getAttributes().setVolume(volume);

        if (null != m_video)
        {
            m_video.setVolume(getVolume());
        }
        return this;
    }

def subvol_quota(self, path, limit):

        args = {
            'path': path,
            'limit': limit,
        }

        self._subvol_quota_chk.check(args)

        self._client.sync('btrfs.subvol_quota', args)

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


Question: // Associates name and data together as an attribute of path.

func Setxattr(path, name string, data []byte) error {
	name = userPrefix + name
	if err := syscall.Setxattr(path, name, data, 0); err != nil {
		return &XAttrError{"setxattr", path, name, err}
	}
	return nil
}

public void setBackingMap(final Map<String, Map<String, List<Object>>> backingMap) {
        if (backingMap == null) {
            this.backingMap = new HashMap<>();
            this.possibleUserAttributeNames = new HashSet<>();
        } else {
            this.backingMap = new LinkedHashMap<>(backingMap);
            this.initializePossibleAttributeNames();
        }
    }

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


Question:
@param string $path
@param bool   $allowQueryString

@return string

protected function createAbsoluteUri($path, $allowQueryString = false)
    {
        $value = '/'.ltrim(parse_url($path, PHP_URL_PATH), '/');

        if ($allowQueryString && $query = parse_url($path, PHP_URL_QUERY)) {
            $value .= '?'.$query;
        }

        return $value;
    }

public function getAuthorizationUrl()
    {
        // Check for required items
        if (!$this->clientId) {
            throw new Exception('Client ID is required');
        }
        if (!$this->scope) {
            throw new Exception('Scope is required');
        }
        if (!$this->redirectUri) {
            throw new Exception('Redirect URI is required');
        }

        // Start building url (enpoint is the same for public and member APIs)
        $url  = 'https://';
        $url .= (!empty($this->environment)) ? $this->environment . '.' : '';
        $url .= self::HOSTNAME . '/' . self::AUTHORIZE;
        $url .= '?client_id='    . $this->clientId;
        $url .= '&scope='        . $this->scope;
        $url .= '&redirect_uri=' . urlencode($this->redirectUri);
        $url .= '&response_type=code';

        // Process non-required fields
        $url .= ($this->showLogin)          ? '&show_login=true'                    : '';
        $url .= (isset($this->state))       ? '&state=' . $this->state              : '';
        $url .= (isset($this->familyNames)) ? '&family_names=' . $this->familyNames : '';
        $url .= (isset($this->givenNames))  ? '&given_names=' . $this->givenNames   : '';
        $url .= (isset($this->email))       ? '&email=' . urlencode($this->email)   : '';

        return $url;
    }

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


Question:
Get a listing of all files at 'src'.  The Object[] array
exists so we can return file attributes (soon to be implemented)

public HdfsFileStatus[] getHdfsListing(String src) throws IOException {
    getListingCheck(src);
    HdfsFileStatus[] stats = dir.getHdfsListing(src);
    if (auditLog.isInfoEnabled()) {
      logAuditEvent(getCurrentUGI(),
        Server.getRemoteIp(),
        "listStatus", src, null, null);
    }
    return stats;
  }

public static ns_doc_image[] get_filtered(nitro_service service, String filter) throws Exception
	{
		ns_doc_image obj = new ns_doc_image();
		options option = new options();
		option.set_filter(filter);
		ns_doc_image[] response = (ns_doc_image[]) obj.getfiltered(service, option);
		return response;
	}

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


Question:
@param Role|string              $role
@param ResourceInterface|string $resource
@param Privilege|string         $privileges

@throws \InvalidArgumentException

@return Rule

private function getRule($role, $resource, $privilege)
    {
        $role = $this->roles->get($role);

        if (is_scalar($resource)) {
            $resource = new Resource($resource);
        } elseif (!$resource instanceof ResourceInterface) {
            throw new \InvalidArgumentException('$resource is expected to be of type string or Gobline\Acl\ResourceInterface');
        }

        if (is_scalar($privilege)) {
            $privilege = new Privilege($privilege);
        } elseif (!$privilege instanceof Privilege) {
            throw new \InvalidArgumentException('$privilege is expected to be of type string or Gobline\Acl\Privilege');
        }

        foreach ($this->rules as $rule) {
            if (!$rule->getRole()->equals($role)) {
                continue;
            }
            if (!$rule->getPrivilege()->equals($privilege) && !$rule->getPrivilege()->equals('*')) {
                continue;
            }
            if (!$rule->getResource()->matches($resource) && (!$rule->getResource() instanceof Resource || !$rule->getResource()->matches('*'))) {
                continue;
            }

            return $rule;
        }

        foreach ($role->getParents() as $role) {
            $rule = $this->getRule($role, $resource, $privilege);
            if ($rule !== null) {
                return $rule;
            }
        }

        return null;
    }

public static void main( String [] args )
    {
        if ( args.length > 0 ) {
            String filename = args[0];

            String [] bshArgs;
            if ( args.length > 1 ) {
                bshArgs = new String [ args.length -1 ];
                System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
            } else
                bshArgs = new String [0];

            try {
                Interpreter interpreter = new Interpreter();
                interpreter.setu( "bsh.args", bshArgs );
                Object result =
                    interpreter.source( filename, interpreter.globalNameSpace );
                if ( result instanceof Class )
                    try {
                        invokeMain( (Class<?>)result, bshArgs );
                    } catch ( Exception e )
                    {
                        Object o = e;
                        if ( e instanceof InvocationTargetException )
                            o = e.getCause();
                        System.err.println(
                            "Class: "+result+" main method threw exception:"+o);
                    }
            } catch ( FileNotFoundException e ) {
                System.err.println("File not found: "+e);
            } catch ( TargetError e ) {
                System.err.println("Script threw exception: "+e);
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), System.err );
            } catch ( EvalError e ) {
                System.err.println("Evaluation Error: "+e);
            } catch ( IOException e ) {
                System.err.println("I/O Error: "+e);
            }
        } else {
            @SuppressWarnings("resource")
            Interpreter interpreter =
            new Interpreter(new CommandLineReader(
                new FileReader(System.in)),
                System.out, System.err, true );
            interpreter.run();
        }
    }

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


Question: Returns the array of declared methods.

public JMethod []getConstructors()
  {
    ArrayList<JavaMethod> ctorList = new ArrayList<JavaMethod>();

    for (JavaMethod method : getMethodList()) {
      if (method.getName().equals("<init>"))
        ctorList.add(method);
    }

    JMethod[] methods = new JMethod[ctorList.size()];

    ctorList.toArray(methods);

    return methods;
  }

private void exportInternalAPI(ClassLoader cl) {
        String[] packages = {
            "com.sun.tools.doclets",
            "com.sun.tools.doclets.standard",
            "com.sun.tools.doclets.internal.toolkit",
            "com.sun.tools.doclets.internal.toolkit.taglets",
            "com.sun.tools.doclets.internal.toolkit.builders",
            "com.sun.tools.doclets.internal.toolkit.util",
            "com.sun.tools.doclets.internal.toolkit.util.links",
            "com.sun.tools.doclets.formats.html",
            "com.sun.tools.doclets.formats.html.markup"
        };

        try {
            Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
            Object thisModule = getModuleMethod.invoke(getClass());

            Class<?> moduleClass = Class.forName("java.lang.Module");
            Method addExportsMethod = moduleClass.getDeclaredMethod("addExports", String.class, moduleClass);

            Method getUnnamedModuleMethod = ClassLoader.class.getDeclaredMethod("getUnnamedModule");
            Object target = getUnnamedModuleMethod.invoke(cl);

            for (String pack : packages) {
                addExportsMethod.invoke(thisModule, pack, target);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

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


Question:
Show the form for editing the specified resource.

@param  Language $language
@return \Illuminate\Http\Response

public function edit(Language $language)
    {
        $extends = $this->viewExtends;
        $section = $this->viewSection;

        return view($this->viewNamespace . '.edit', compact('language', 'extends', 'section'));
    }

protected function getResourceMethodConfiguration(): array
    {
        return [
            ResourceMethodEnum::GET_ALL => RequestPathFormatEnum::CUSTOM_FIELDS,
            ResourceMethodEnum::GET_BY_ID => RequestPathFormatEnum::CUSTOM_FIELDS_BY_ID,
            ResourceMethodEnum::GET_BY_IDS => RequestPathFormatEnum::CUSTOM_FIELDS_BY_IDS,
            ResourceMethodEnum::CREATE => RequestPathFormatEnum::CUSTOM_FIELDS,
            ResourceMethodEnum::UPDATE => RequestPathFormatEnum::CUSTOM_FIELDS_BY_ID,
        ];
    }

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


Question: // SetPersons sets the Persons field's value.

func (s *GetFaceSearchOutput) SetPersons(v []*PersonMatch) *GetFaceSearchOutput {
	s.Persons = 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: TODO: Add support for axis label positions/styles, support for multiple label sets per axis

def axes=(axes)
      idx = 0
      @axes, @axis_labels, @axis_ranges = [], [], []
      [:x, :y, :r, :t].each do |axis|
        case axes[axis]
        when Array
          @axis_labels << ("#{idx}:|" + axes[axis].map {|l| CGI::escape(l.to_s) }.join('|'))
          @axes << axis
          idx += 1
        when Range
          @axis_ranges << ("#{idx},#{axes[axis].first},#{axes[axis].last}")
          @axes << axis
          idx += 1
        when true
          @axes << axis
          idx += 1
        end
      end
    end

function(feature) {
        var geometry = feature.geometry;
            geometry = geometry.clone();
        if (this.internalProjection && this.externalProjection) {
            geometry.transform(this.internalProjection,
                               this.externalProjection);
        }
        if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
            var wpt = this.buildWptNode(geometry);
            this.appendAttributesNode(wpt, feature);
            return wpt;
        } else {
            var trkNode = this.createElementNS(this.namespaces.gpx, "trk");
            this.appendAttributesNode(trkNode, feature);
            var trkSegNodes = this.buildTrkSegNode(geometry);
            trkSegNodes = OpenLayers.Util.isArray(trkSegNodes) ?
                trkSegNodes : [trkSegNodes];
            for (var i = 0, len = trkSegNodes.length; i < len; i++) {
                trkNode.appendChild(trkSegNodes[i]);
            }
            return trkNode;
        }
    }

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


Question:
Generates files from templates for a given application.
<p>
Templates are provided in parameters.
</p>

@param application an application (not null)
@param templates a non-null collection of templates

void generate( Application application, Collection<TemplateEntry> templates ) {

		try {
			synchronized( this.generationLock ) {
				TemplateUtils.generate( application, this.outputDIR, templates, this.logger );
			}

		} catch( IOException e ) {
			this.logger.warning( "An error occurred while generating files from templates for application " + application );
			Utils.logException( this.logger, e );

		} catch( Throwable e ) {
			this.logger.warning( "An unexpected error occurred while generating files from templates for application " + application );
			Utils.logException( this.logger, new UndeclaredThrowableException( e ));
		}
	}

def tar(self, appname, appversion):

        name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2'
        time = utc.now()
        name = name_tmpl % {'app': appname,
                            'version': appversion,
                            'time': time.strftime('%Y-%m-%dT%H-%M')}

        if not os.path.exists(TARBALL_HOME):
            os.mkdir(TARBALL_HOME)
        tarball = os.path.join(TARBALL_HOME, name)
        tar_params = {'filename': tarball, 'folder': self.folder}
        tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params)
        tar_result.raise_for_status()
        return Build(appname, appversion, time, tarball)

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


Question:
Find a project. Create it if one doesn't exist.

@param   string  $name  Project name
@return  mixed

public static function find_or_create($name)
	{
		$hztp = new self();

		if (is_numeric($name))
		{
			$hztp->id = $name;
		}
		else
		{
			$hztp->name = $name;
		}

		if ($hztp->read() == false)
		{
			if ($hztp->create() == false)
			{
				return false;
			}
		}

		return $hztp;
	}

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

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

        return new pakeMercurial($path);
    }

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


Question: // Fire implements Fire.

func (s *SinkYARPCServer) Fire(ctx context.Context, request *examplepb.FireRequest) error {
	if request == nil {
		return errRequestNil
	}
	if request.Value == "" {
		return errRequestValueNil
	}
	s.Lock()
	s.values = append(s.values, request.Value)
	s.Unlock()
	if s.fireDone == nil {
		return nil
	}
	select {
	case s.fireDone <- struct{}{}:
	case <-time.After(FireDoneTimeout):
		return yarpcerrors.Newf(yarpcerrors.CodeDeadlineExceeded, "fire done not handled after %v", FireDoneTimeout)
	}
	return nil
}

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

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


Question:
Resolves loader by resource.

@param mixed $resource Resource to load

@return LoaderInterface

public function resolveLoader($resource)
    {
        foreach ($this->loaders as $loader) {
            if ($loader->supports($resource)) {
                return $loader;
            }
        }

        return null;
    }

public static void main(String[] args)
    {
        String splashImage = Splash.getParam(args, SPLASH);
        if ((splashImage == null) || (splashImage.length() == 0))
            splashImage = DEFAULT_SPLASH;
        URL url = Splash.class.getResource(splashImage);
        if (url == null)
            if (ClassServiceUtility.getClassService().getClassFinder(null) != null)
                url = ClassServiceUtility.getClassService().getClassFinder(null).findResourceURL(splashImage, null);

        Container container = null;
        Splash.splash(container, url);
        String main = Splash.getParam(args, MAIN);
        if ((main == null) || (main.length() == 0))
            main = ROOT_PACKAGE + "Thin";
        else if (main.charAt(0) == '.')
            main = ROOT_PACKAGE + main.substring(1);
        Splash.invokeMain(main, args);
        Splash.disposeSplash();
    }

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


Question:
Calculates the exponential of an input vertex

    :param input_vertex: the vertex

def Exp(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:

    return Double(context.jvm_view().ExpVertex, label, cast_to_double_vertex(input_vertex))

public void ENsetnodevalue( int index, NodeParameters nodeParameter, float value ) throws EpanetException {
        int errcode = epanet.ENsetnodevalue(index, nodeParameter.getCode(), value);
        checkError(errcode);
    }

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


Question:
perform post-processing (smoothing, normalisation, interpolation) of
        the data

def post_process_data(self, voltage=None, incremental_capacity=None,
                          voltage_step=None):
        """"""

        logging.debug("post-processing data")

        if voltage is None:
            voltage = self.voltage_processed
            incremental_capacity = self.incremental_capacity
            voltage_step = self.voltage_inverted_step

        if self.post_smoothing:
            logging.debug(" - post smoothing (gaussian)")
            logging.debug(f"    * using voltage fwhm: {self.voltage_fwhm}")
            points_fwhm = int(self.voltage_fwhm / voltage_step)

            sigma = np.amax([1, points_fwhm / 2])

            self.incremental_capacity = gaussian_filter1d(
                incremental_capacity, sigma=sigma, order=self.gaussian_order,
                mode=self.gaussian_mode,
                cval=self.gaussian_cval,
                truncate=self.gaussian_truncate
            )

        if self.normalize:
            logging.debug(" - normalizing")
            area = simps(incremental_capacity, voltage)
            self.incremental_capacity = incremental_capacity * self.normalizing_factor / abs(area)

        fixed_range = False
        if isinstance(self.fixed_voltage_range, np.ndarray):
            fixed_range = True
        else:
            if self.fixed_voltage_range:
                fixed_range = True
        if fixed_range:
            logging.debug(" - using fixed voltage range (interpolating)")
            v1, v2, number_of_points = self.fixed_voltage_range
            v = np.linspace(v1, v2, number_of_points)
            f = interp1d(x=self.voltage_processed, y=self.incremental_capacity,
                         kind=self.interpolation_method, bounds_error=False,
                         fill_value=np.NaN)

            self.incremental_capacity = f(v)
            self.voltage_processed = v

def _serialize_record(self, record):
        """"""
        f = self._empty_to_dot
        row = [record.CHROM, record.POS]
        row.append(f(";".join(record.ID)))
        row.append(f(record.REF))
        if not record.ALT:
            row.append(".")
        else:
            row.append(",".join([f(a.serialize()) for a in record.ALT]))
        row.append(f(record.QUAL))
        row.append(f(";".join(record.FILTER)))
        row.append(f(self._serialize_info(record)))
        if record.FORMAT:
            row.append(":".join(record.FORMAT))
        row += [
            self._serialize_call(record.FORMAT, record.call_for_sample[s])
            for s in self.header.samples.names
        ]
        print(*row, sep="\t", file=self.stream)

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


Question:
Set configuration database info

@param array $data

@return void

public function setDatabaseInfo($data)
    {
        $data['host'] = $data['host'].':'.$data['port'];

        unset($data['port']);

        $keys = array_map(function($key) {
            return 'database_'.$key;
        }, array_keys($data));

        $data = array_combine($keys, array_values($data));

        $this->set($data);
    }

func (s *DescribeDBParameterGroupsOutput) SetDBParameterGroups(v []*DBParameterGroup) *DescribeDBParameterGroupsOutput {
	s.DBParameterGroups = v
	return s
}

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


Question:
Build the serial field tags information.

@param serializableFieldsTree content tree to which the documentation will be added

public void buildSerialFieldTagsInfo(Content serializableFieldsTree) {
        if(configuration.nocomment){
            return;
        }
        FieldDoc field = (FieldDoc)currentMember;
        // Process Serializable Fields specified as array of
        // ObjectStreamFields. Print a member for each serialField tag.
        // (There should be one serialField tag per ObjectStreamField
        // element.)
        SerialFieldTag[] tags = field.serialFieldTags();
        Arrays.sort(tags);
        int tagsLength = tags.length;
        for (int i = 0; i < tagsLength; i++) {
            if (tags[i].fieldName() == null || tags[i].fieldType() == null) // ignore malformed @serialField tags
                continue;
            Content fieldsContentTree = fieldWriter.getFieldsContentHeader(
                    (i == tagsLength - 1));
            fieldWriter.addMemberHeader(tags[i].fieldTypeDoc(),
                    tags[i].fieldType(), "", tags[i].fieldName(), fieldsContentTree);
            fieldWriter.addMemberDescription(tags[i], fieldsContentTree);
            serializableFieldsTree.addContent(fieldsContentTree);
        }
    }

public void setFloatingParameter(FloatingParameterType newFloatingParameter) {
		((FeatureMap.Internal)getMixed()).set(BpsimPackage.Literals.DOCUMENT_ROOT__FLOATING_PARAMETER, newFloatingParameter);
	}

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


Question: Documented in Collection.js

function(models, out)
  {
    var target = out || this.cloneEmpty();

    for (var i = 0; i < models.length; i++)
    {
      var a = models[ i ];
      var key = this.buildKeyFromInput( a );

      if ( this.has( key ) )
      {
        target.push( a );
      }
    }

    return target;
  }

function(iterator, context) {
            if (context != null) iterator = _.bind(iterator, context);
            _.each(this.components, function(value, cid) {
                if (_.isArray(value)) {
                    _.each(value, iterator);
                } else {
                    iterator(value);
                }
            });
            return this;
        }

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


Question:
Call findIdentifiersByTag but ignore the expires check.

@param string $tag

@return array

protected function findIdentifiersByTagIncludingExpired($tag): array
    {
        $base = (new DateTimeService())->getCurrentTime();
        $GLOBALS['EXEC_TIME'] = 0;
        $identifiers = $this->findIdentifiersByTag($tag);
        $GLOBALS['EXEC_TIME'] = $base;

        return $identifiers;
    }

function checkIfMatch(req, res, next) {
    var clientETags;
    var cur;
    var etag = res.etag || res.getHeader('etag') || '';
    var ifMatch;
    var matched = false;

    if ((ifMatch = req.headers['if-match'])) {

        clientETags = ifMatch.split(/\s*,\s*/);

        for (var i = 0; i < clientETags.length; i++) {
            cur = clientETags[i];

            // only strong comparison

            cur = cur.replace(/^W\//, '');
            cur = cur.replace(/^"(\w*)"$/, '$1');

            if (cur === '*' || cur === etag) {
                matched = true;
                break;
            }
        }

        if (!matched) {
            var err = new PreconditionFailedError(IF_MATCH_FAIL,
                ifMatch,
                etag);
            return (next(err));
        }
    }

    return (next());
}

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


Question: Split all strings in df.Context and df.Utterance on __eot__ (turn) markers

def preprocess_ubuntu_corpus(df):

    statements = []
    replies = []
    for i, record in tqdm(df.iterrows()):
        turns = list(split_turns(record.Context))
        statement = turns[-1] if len(turns) else '\n'  # <1>
        statements.append(statement)
        turns = list(split_turns(record.Utterance))
        reply = turns[-1] if len(turns) else '\n'
        replies.append(reply)
    df['statement'] = statements
    df['reply'] = replies
    return df

def parse_tile_name(name):

        tile_name = name.lstrip('T0')
        if len(tile_name) == 4:
            tile_name = '0' + tile_name
        if len(tile_name) != 5:
            raise ValueError('Invalid tile name {}'.format(name))
        return tile_name

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


Question: // HeaderFromContext returns http.Header from a context if it's found.

func HeaderFromContext(ctx context.Context) (http.Header, bool) {
	if ctx == nil {
		panic("Context cannot be nil")
	}

	requestValue := ctx.Value(requestHeaderKey)
	if requestValue == nil {
		return nil, false
	}

	header, ok := requestValue.(http.Header)
	return header, ok
}

func (r *ResponseData) WriteHeader(status int) {
	go IncrCounter([]string{"goa", "response", strconv.Itoa(status)}, 1.0)
	r.Status = status
	r.ResponseWriter.WriteHeader(status)
}

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


Question:
Register the service provider.

@return void

public function register()
    {
        $this->app->singleton(
            'datatables.fractal', function () {
                $fractal = new Manager;
                $config  = $this->app['config'];
                $request = $this->app['request'];

                $includesKey = $config->get('datatables-fractal.includes', 'include');
                if ($request->get($includesKey)) {
                    $fractal->parseIncludes($request->get($includesKey));
                }

                $serializer = $config->get('datatables-fractal.serializer', DataArraySerializer::class);
                $fractal->setSerializer(new $serializer);

                return $fractal;
            }
        );

        $this->app->singleton(
            'datatables.transformer', function () {
                return new FractalTransformer($this->app->make('datatables.fractal'));
            }
        );

        $this->commands(
            [
                TransformerMakeCommand::class,
            ]
        );
    }

protected function queueRecallerCookie(AuthenticatableContract $user)
    {
        $this->getCookieJar()->queue($this->createRecaller(
            $user->getAuthIdentifier().'|'.$user->getRememberToken().'|'.$user->getAuthPassword()
        ));
    }

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


Question:
get

Returns the $var value

@final
@access public
@param  string|array $var Key(s) you want to retrieve value from.
@throws  ModelException if strict and the attribute does not exist.
@return mixed

final public function get($var)
    {
        if (is_scalar($var)) {
            if ($this->has($var)) {
                return $this->container[$var];
            } elseif (static::$strict === true) {
                throw new ModelException(sprintf("No such key '%s'.", $var));
            }
        } elseif (is_array($var)) {
            return array_intersect_key($this->container, array_flip($var));
        }
    }

func (tb *LTable) RawGet(key LValue) LValue {
	switch v := key.(type) {
	case LNumber:
		if isArrayKey(v) {
			if tb.array == nil {
				return LNil
			}
			index := int(v) - 1
			if index >= len(tb.array) {
				return LNil
			}
			return tb.array[index]
		}
	case LString:
		if tb.strdict == nil {
			return LNil
		}
		if ret, ok := tb.strdict[string(v)]; ok {
			return ret
		}
		return LNil
	}
	if tb.dict == nil {
		return LNil
	}
	if v, ok := tb.dict[key]; ok {
		return v
	}
	return LNil
}

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


Question: Set up routes with a version prefix.

def setup_versioned_routes(routes, version=None):
    """"""
    prefix = '/' + version if version else ""
    for r in routes:
        path, method = r
        route(prefix + path, method, routes[r])

public function any( $uri, $action = null )
	{
		$verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];

		return $this->addRoute( $verbs, $uri, $action );
	}

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


Question: // setHasVote sets the HasVote status of all the given machines to hasVote.

func setHasVote(ms []*machineTracker, hasVote bool) error {
	if len(ms) == 0 {
		return nil
	}
	logger.Infof("setting HasVote=%v on machines %v", hasVote, ms)
	for _, m := range ms {
		if err := m.stm.SetHasVote(hasVote); err != nil {
			return fmt.Errorf("cannot set voting status of %q to %v: %v", m.Id(), hasVote, err)
		}
	}
	return nil
}

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceStrategyOptions.

func (in *SourceStrategyOptions) DeepCopy() *SourceStrategyOptions {
	if in == nil {
		return nil
	}
	out := new(SourceStrategyOptions)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


Question:
loads a definition

@param string $version
@param string $resource
@param string $type
@param string $key
@return string

private function loadDefinition($version, $resource, $type, $key = null) : string
    {
        $definition = $this->definition($resource, $version);

        $classPath = $definition->$type;
        if (is_array($classPath) && array_key_exists($key, $classPath)) {
            $classPath = $classPath[$key];
        }

        if ($classPath === null) {
            throw ResourceNotDefinedException::resource($resource, $type);
        }

        return $classPath;
    }

func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
	apiserver, ok := obj.(*apiextensions.CustomResourceDefinition)
	if !ok {
		return nil, nil, fmt.Errorf("given object is not a CustomResourceDefinition")
	}
	return labels.Set(apiserver.ObjectMeta.Labels), CustomResourceDefinitionToSelectableFields(apiserver), nil
}

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


Question:
returns the data

@param string $key
@param string $cookieExtra

@return array|null

public static function getData($key = self::KEY, $cookieExtra = '')
    {
        if (!empty(self::$data)) {
            return self::$data;
        }

        $key .= $cookieExtra;

        if (PHP_SESSION_ACTIVE === session_status() && isset($_SESSION[$key])) {
            self::$data = $_SESSION[$key];

            return self::$data;
        }

        if (isset($_COOKIE) && isset($_COOKIE[$key])) {
            self::$data = self::ang($_COOKIE[$key]);

            if (isset($_SESSION)) {
                $_SESSION[$key] = self::$data;
            }

            return self::$data;
        }

        return null;
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question: Delete references to routers/networks.

def delete_router_references(self, snet, address=None, dnets=None):
        """"""
        if _debug: NetworkServiceAccessPoint._debug("delete_router_references %r %r %r", snet, address, dnets)

        # see if we have an adapter for the snet
        if snet not in self.adapters:
            raise RuntimeError("no adapter for network: %d" % (snet,))

        # pass this along to the cache
        self.router_info_cache.delete_router_info(snet, address, dnets)

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:
Gets key.

@param service the service
@return the key

public static String buildKey(final RegisteredService service) {
        return service.getId() + ";" + service.getName() + ';' + service.getServiceId();
    }

func (s *SecurityGroupService) NewAuthorizeSecurityGroupEgressParams() *AuthorizeSecurityGroupEgressParams {
	p := &AuthorizeSecurityGroupEgressParams{}
	p.p = make(map[string]interface{})
	return p
}

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


Question: Returns if the namespace is configured by composer autoloader.

public function isNamespaceConfiguredToAutoload(string $namespace): bool
    {
        $namespace = trim($namespace, '\\').'\\';
        $classLoader = $this->getClassLoader();

        foreach ($classLoader->getPrefixesPsr4() as $prefix => $paths) {
            if (0 === strpos($namespace, $prefix)) {
                return true;
            }
        }

        foreach ($classLoader->getPrefixes() as $prefix => $paths) {
            if (0 === strpos($namespace, $prefix)) {
                return true;
            }
        }

        return false;
    }

public function load(ContainerBuilder $container, array $config) {
        // Client initializer definition
        $clientInitializerDefinition = new Definition(
            ApiClientAwareInitializer::class,
            [
                $config['apiClient']
            ]
        );
        $clientInitializerDefinition->addTag(ContextExtension::INITIALIZER_TAG);

        // Definition for the array contains comparator
        $comparatorDefinition = new Definition(ArrayContainsComparator::class);

        // Comparator initializer definition
        $comparatorInitializerDefinition = new Definition(
            ArrayContainsComparatorAwareInitializer::class,
            [
                new Reference(self::COMPARATOR_SERVICE_ID)
            ]
        );
        $comparatorInitializerDefinition->addTag(ContextExtension::INITIALIZER_TAG);

        // Add all definitions to the container
        $container->setDefinition(self::APICLIENT_INITIALIZER_SERVICE_ID, $clientInitializerDefinition);
        $container->setDefinition(self::COMPARATOR_SERVICE_ID, $comparatorDefinition);
        $container->setDefinition(self::COMPARATOR_INITIALIZER_SERVICE_ID, $comparatorInitializerDefinition);
    }

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


Question:
Removes an user to team.

@param User $user

@return Team

public function removeUser(User $user)
    {
        if ($this->users->contains($user)) {
            $this->users->removeElement($user);
        }

        return $this;
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
Handle bind service event.
@param service Service instance
@param props Service reference properties

public void bind(T service, Map<String, Object> props) {
    synchronized (serviceMap) {
      serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service);
      updateSortedServices();
    }
  }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question: Add class to compile.

public function configureClassesToCompile()
    {
        if (\PHP_VERSION_ID >= 70000) {
            return;
        }

        $this->addClassesToCompile([
            CDNInterface::class,
            CloudFront::class,
            Fallback::class,
            PantherPortal::class,
            Server::class,
            Pixlr::class,
            Local::class,
            Replicate::class,
            DefaultGenerator::class,
            GeneratorInterface::class,
            ODMGenerator::class,
            PHPCRGenerator::class,
            AmazonMetadataBuilder::class,
            MetadataBuilderInterface::class,
            NoopMetadataBuilder::class,
            ProxyMetadataBuilder::class,
            Gallery::class,
            GalleryHasMedia::class,
            GalleryHasMediaInterface::class,
            GalleryInterface::class,
            GalleryManager::class,
            GalleryManagerInterface::class,
            Media::class,
            MediaInterface::class,
            MediaManagerInterface::class,
            BaseProvider::class,
            BaseVideoProvider::class,
            DailyMotionProvider::class,
            FileProvider::class,
            ImageProvider::class,
            MediaProviderInterface::class,
            Pool::class,
            VimeoProvider::class,
            YouTubeProvider::class,
            ResizerInterface::class,
            SimpleResizer::class,
            SquareResizer::class,
            DownloadStrategyInterface::class,
            ForbiddenDownloadStrategy::class,
            PublicDownloadStrategy::class,
            RolesDownloadStrategy::class,
            SessionDownloadStrategy::class,
            ConsumerThumbnail::class,
            FormatThumbnail::class,
            ThumbnailInterface::class,
            MediaExtension::class,
        ]);
    }

public static FaxClient createFaxClient(String type,Properties configuration)
    {
        return FaxClientFactory.createFaxClientImpl(type,configuration);
    }

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


Question: Processing uses bcbio-variation-recall. Avoids core requirement if not used.

def use_bcbio_variation_recall(algs):

    for alg in algs:
        jointcaller = alg.get("jointcaller", [])
        if not isinstance(jointcaller, (tuple, list)):
            jointcaller = [jointcaller]
        for caller in jointcaller:
            if caller not in set(["gatk-haplotype-joint", None, False]):
                return True
    return False

func (vp *vplayer) play(ctx context.Context) error {
	if !vp.stopPos.IsZero() && vp.startPos.AtLeast(vp.stopPos) {
		if vp.saveStop {
			return vp.vr.setState(binlogplayer.BlpStopped, fmt.Sprintf("Stop position %v already reached: %v", vp.startPos, vp.stopPos))
		}
		return nil
	}

	plan, err := buildReplicatorPlan(vp.vr.source.Filter, vp.vr.tableKeys, vp.copyState)
	if err != nil {
		return err
	}
	vp.replicatorPlan = plan

	if err := vp.fetchAndApply(ctx); err != nil {
		msg := err.Error()
		vp.vr.stats.History.Add(&binlogplayer.StatsHistoryRecord{
			Time:    time.Now(),
			Message: msg,
		})
		if err := vp.vr.setMessage(msg); err != nil {
			log.Errorf("Failed to set error state: %v", err)
		}
		return err
	}
	return nil
}

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


Question:
Returns a random date in the range of [min, max].

@param min
minimum value for generated date
@param max
maximum value for generated date

public Date getDate(final Date min, final Date max) {
		return getDate(min.getTime(), max.getTime());
	}

public function setSeed($seed)
    {
        if (is_int($seed) !== true) {
            throw new Exception(
                sprintf('The type of the seed value "%s" need to be int. You passed a(n) "%s".', $seed, gettype($seed))
            );
        }

        // We need to call different methods depending on chosen source
        switch ($this->getMode()) {

            case self::MODE_PHP_MERSENNE_TWISTER:
                mt_srand($seed);
                break;

            case self::MODE_PHP_DEFAULT:
                srand($seed);
                break;

            case self::MODE_OPEN_SSL:
            default:
                // Intentionally left blank
                break;
        }

        $this->seed = $seed;
    }

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


Question: // HasBlock checks if a block is fully present in the database or not.

func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
	if bc.blockCache.Contains(hash) {
		return true
	}
	return rawdb.HasBody(bc.db, hash, number)
}

public function do_exists($key)
    {
        $context = $this->_context;

        return isset($context->data[$key]) && $context->data[$key]['deadline'] >= time();
    }

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


Question:
Extracts mention usernames from the entity body and updates the entity.

@param AnCommandContext $context

@return bool

public function updateMentionsFromBody(AnCommandContext $context)
    {
        $entity = $this->getItem();
        $body_mentions = $this->extractMentions($entity->body);
        $body_mentions = array_map('strtolower', $body_mentions);

        // @todo we should be accessing username, but for now we are using alias
        // until the design in the domain entities is improved
        $entity_mentions = AnConfig::unbox($entity->mentions->alias);

        if (is_array($entity_mentions)) {
            $entity_mentions = array_map('strtolower', $entity_mentions);
        }

        //update removed mentions
      if (is_array($body_mentions)) {
          foreach ($entity_mentions as $mention) {
              if (! in_array($mention, $body_mentions)) {
                  $entity->removeMention($mention);
              }
          }
      }

       //remove the body mentions that already exists in the entity mentions
      if (is_array($entity_mentions)) {
          foreach ($body_mentions as $index => $mention) {
              if (in_array($mention, $entity_mentions)) {
                  unset($body_mentions[$index]);
              }
          }
      }

       //what's left are new mentions. Add them to the entity.
       foreach ($body_mentions as $mention) {
           $entity->addMention(trim($mention));
       }

        //keep the list of new mentions so you can notify them later.
        $this->_newly_mentioned = $body_mentions;
    }

public function call($args = [])
    {
        if (count($args) == 0 || empty($args[2]))
            throw new NoticeException('Command "'.$this->key.'": Expecting a setting (version).');

        $object = explode(':', $args[2]);

        // Validations
        if (!in_array($object[0], ['version']))
            throw new NoticeException('Command "'.$this->key.'": Invalid setting. Expecting version.');

        switch ($object[0]) {
            case 'version':
                // Validate second parameter
                if ($object[0] === 'version' && !isset($object[1]))
                    throw new NoticeException('Command "'.$this->key.'": Expecting a version.');
                $this->setVersion($object[1]);
                break;
        }
    }

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


Question:
// verifyNICsWithConfigFile is recruited for legacy LXD installations.
// It checks the LXD bridge configuration file and ensure that one of the input
// devices is suitable for LXD to work with Juju.

func (s *Server) verifyNICsWithConfigFile(nics map[string]device, reader func(string) ([]byte, error)) error {
	netName, err := checkBridgeConfigFile(reader)
	if err != nil {
		return errors.Trace(err)
	}

	checked := make([]string, 0, len(nics))
	for name, nic := range nics {
		checked = append(checked, name)

		if nic["parent"] != netName {
			continue
		}
		if !isValidNICType(nic) {
			continue
		}

		logger.Tracef("found usable network device %q with parent %q", name, netName)
		s.localBridgeName = netName
		return nil
	}

	return errors.Errorf("no network device found with nictype %q or %q that uses the configured bridge in %s"+
		"\n\tthe following devices were checked: %v", nicTypeBridged, nicTypeMACVLAN, BridgeConfigFile, checked)
}

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question: Warning: relies on default timezone!

public static String formatDateTime(long ms) {
    return formatDateTime(OffsetDateTime.ofInstant(Instant.ofEpochMilli(ms), ZoneId.systemDefault()));
  }

public static Calendar startOfYear(Calendar origin) {
        Calendar cal = (Calendar) origin.clone();
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.DAY_OF_YEAR, 1);
        return cal;
    }

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


Question:
Includes the class API by looking up plugins/xxx/API.php

@param string $fileName api class name eg. "API"
@throws Exception

private function includeApiFile($fileName)
    {
        $module = self::getModuleNameFromClassName($fileName);
        $path = Manager::getPluginDirectory($module) . '/API.php';

        if (is_readable($path)) {
            require_once $path; // prefixed by PIWIK_INCLUDE_PATH
        } else {
            throw new Exception("API module $module not found.");
        }
    }

public function add($request)
    {
        if (is_array($request)) {
            array_walk($request, [$this, __METHOD__]);

            return $this;
        }

        if (!$request instanceof Request) {
            throw new InvalidArgumentException('Argument for add() must be of type array or Request.');
        }

        $this->requests[] = $request;

        return $this;
    }

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


Question:
//
// Copyright (c) 2015 Huan Du
// Modifications: 2015 Donal Byrne

func ToDashCase(str string) string {
	if len(str) == 0 {
		return ""
	}

	buf := &bytes.Buffer{}
	var prev, r0, r1 rune
	var size int

	r0 = '-'

	for len(str) > 0 {
		prev = r0
		r0, size = utf8.DecodeRuneInString(str)
		str = str[size:]

		switch {
		case r0 == utf8.RuneError:
			buf.WriteByte(byte(str[0]))

		case unicode.IsUpper(r0):
			if prev != '-' {
				buf.WriteRune('-')
			}

			buf.WriteRune(unicode.ToLower(r0))

			if len(str) == 0 {
				break
			}

			r0, size = utf8.DecodeRuneInString(str)
			str = str[size:]

			if !unicode.IsUpper(r0) {
				buf.WriteRune(r0)
				break
			}

			// find next non-upper-case character and insert `_` properly.
			// it's designed to convert `HTTPServer` to `http_server`.
			// if there are more than 2 adjacent upper case characters in a word,
			// treat them as an abbreviation plus a normal word.
			for len(str) > 0 {
				r1 = r0
				r0, size = utf8.DecodeRuneInString(str)
				str = str[size:]

				if r0 == utf8.RuneError {
					buf.WriteRune(unicode.ToLower(r1))
					buf.WriteByte(byte(str[0]))
					break
				}

				if !unicode.IsUpper(r0) {
					if r0 == '_' || r0 == ' ' || r0 == '-' {
						r0 = '-'

						buf.WriteRune(unicode.ToLower(r1))
					} else {
						buf.WriteRune('-')
						buf.WriteRune(unicode.ToLower(r1))
						buf.WriteRune(r0)
					}

					break
				}

				buf.WriteRune(unicode.ToLower(r1))
			}

			if len(str) == 0 || r0 == '-' {
				buf.WriteRune(unicode.ToLower(r0))
				break
			}

		default:
			if r0 == ' ' || r0 == '_' {
				r0 = '-'
			}

			buf.WriteRune(r0)
		}
	}

	return buf.String()
}

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question: // Add adds a value to the cache.  Returns true if an eviction occurred.

func (c *Cache) Add(key, value interface{}) (evicted bool) {
	c.lock.Lock()
	evicted = c.lru.Add(key, value)
	c.lock.Unlock()
	return evicted
}

public function save($userid, $apikey, $scope, $name, $args, $xml)
    {
        $key = $this->getKey($userid, $apikey, $scope, $name, $args);
        $ttl = $this->getTimeout($xml);
        $time = time();
        $timeout = $time + $ttl;

        $replace = $this->memcached->replace($key, $xml, $timeout);

        $set = $set_age = false;

        if (!$replace) {
            $set = $this->memcached->set($key, $xml, $timeout);
        }

        $replace_age = $this->memcached->replace($key.'_age', array('age' => $time, 'ttl' => $ttl), $timeout);

        if (!$replace_age) {
            $set_age = $this->memcached->set($key.'_age', array('age' => $time, 'ttl' => $ttl), $timeout);
        }

        return (($replace || $set) && ($replace_age || $set_age));
    }

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


Question:
Register the application's event listeners.

@return void

public function boot()
    {
        $events = app('events');

        foreach ($this->listen as $event => $listeners) {
            foreach ($listeners as $listener) {
                $events->listen($event, $listener);
            }
        }
    }

protected function initPluginType()
    {
        $dispatcher = $this->client->getEventDispatcher();
        $dispatcher->addListener(SolariumEvents::PRE_EXECUTE_REQUEST, array($this, 'preExecuteRequest'), 1000);
        $dispatcher->addListener(SolariumEvents::POST_EXECUTE_REQUEST, array($this, 'postExecuteRequest'), -1000);
    }

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


Question:
Define the class and text that are on the button. Called by set on default.

@returns {Pagelet}
@api private

function define() {
    var type = this.data.type || this.defaults.type
      , collection = this.collection;

    this.data.use = collection[type].class;
    this.data.text = this.data.text || collection[type].text;
    this.data.href = this.data.href || collection[type].href;

    return this;
  }

function () {
        var btnElm = this.getEl().firstChild,
          btnStyle;

        if (btnElm) {
          btnStyle = btnElm.style;
          btnStyle.width = btnStyle.height = "100%";
        }

        this._super();
      }

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


Question: // NewUserinfoController creates a userinfo controller.

func NewUserinfoController(service *goa.Service, app application.Application, tokenManager manager.TokenManager) *UserinfoController {
	return &UserinfoController{
		Controller:   service.NewController("UserinfoController"),
		app:          app,
		tokenManager: tokenManager,
	}
}

public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = [])
    {
        $this->routes[$dataSource->getName()] = $route;
        $this->additional_parameters[$dataSource->getName()] = $additional_parameters;
    }

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


Question: Local duplicate of Twig_Loader_Filesystem::isAbsolutePath().

private function isAbsolute($path)
    {
        return strspn($path, '/\\', 0, 1)
            || (strlen($path) > 3 && ctype_alpha($path[0])
                && ':' === substr($path, 1, 1)
                && strspn($path, '/\\', 2, 1)
            )
            || null !== parse_url($path, PHP_URL_SCHEME)
            ;
    }

public function moduleAsset($asset, $module = null, $absolute = false)
    {
        return $this->createAssetPath($asset, $module, $absolute, true);
    }

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