Question:
Print HTML Body

@param \Throwable $e
@param string $title
@param string $file
@param integer $line

@return string

@throws

private function makeHtmlBody( $e, $title, $file, $line )
    {
        $html = '';

        $html .= '
' . PHP_EOL;
        $html .= '

' . $title . '

' . PHP_EOL;

        // PHP info
        $phpinfo = array(
                'PHP_VERSION' => PHP_VERSION,
                'date_default_timezone' => date_default_timezone_get(),
            );

        $html .= '

PHP Info  (' . count($phpinfo) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $phpinfo as $name => $value )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $name . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // php.ini info
        $php_ini = ini_get_all();

        $html .= '

php.ini  (' . count($php_ini) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $php_ini as $key => $item )
        {
            $local_value = isset($item['local_value']) ? $item['local_value'] : NULL;

            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $key . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $local_value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // $_SERVER variables

        $html .= '

$_SERVER variables  (' . count($_SERVER) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $_SERVER as $name => $value )
        {
            if ( is_array($value) ) $value = print_r($value,true);

            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $name . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // $_COOKIE variables

        $html .= '

$_COOKIE variables  (' . count($_COOKIE) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $_COOKIE as $name => $value )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $name . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // $_ENV variables

        $html .= '

$_ENV variables  (' . count($_ENV) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $_ENV as $name => $value )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $name . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // $_SESSION variables

        if ( isset($_SESSION) ){
            $html .= '

$_SESSION variables  (' . count($_SESSION) . ')

' . PHP_EOL;

            $html .= '' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $no = 1;
            foreach( $_SESSION as $name => $value )
            {
                $html .= '
' . PHP_EOL;
                $html .= '  ' . $no . '	' . PHP_EOL;
                $html .= '  ' . $name . '	' . PHP_EOL;
                $html .= '
' . PHP_EOL;
                $html .= '
' . PHP_EOL;
                $html .= '
' . Util::toString($value) . '
	' . PHP_EOL;
                $html .= '
' . PHP_EOL;

                $no ++;
            }
            $html .= '
' . PHP_EOL;
        }

        // output included files
        $included_files = get_included_files();

        $html .= '

Included Files  (' . count($included_files) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $included_files as $file )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $file . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // output loaded extensions
        $loaded_extensions = get_loaded_extensions();

        $html .= '

Loaded Extensions  (' . count($loaded_extensions) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $loaded_extensions as $name => $value )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // output defined constants
        $declared_constants = Util::getUserDefinedConstants();

        $html .= '

User Declared Constants  (' . count($declared_constants) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $declared_constants as $name => $value )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $name . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $value . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // output defined interfaces
        $declared_interfaces = get_declared_interfaces();
        $interfaces = NULL;
        foreach( $declared_interfaces as $interface )
        {
            $interfaces[] = $interface;
        }
        sort($interfaces);

        $html .= '

Declared Interfaces  (' . count($interfaces) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $interfaces as $interface )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $interface . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // output defined functions
        $defined_functions = get_defined_functions();
        $functions = NULL;
        foreach( $defined_functions['internal'] as $function )
        {
            $functions[] = '[core]' . $function;
        }
        foreach( $defined_functions['user'] as $function )
        {
            $functions[] = '[user]' . $function;
        }
        sort($functions);

        $html .= '

Declared Functions  (' . count($functions) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $functions as $function )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $function . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // output defined classes
        $declared_klasses = get_declared_classes();
        $klasses = NULL;
        foreach( $declared_klasses as $klass )
        {
            $klasses[] = $klass;
        }
        sort($klasses);

        $html .= '

Declared Classes  (' . count($klasses) . ')

' . PHP_EOL;

        $html .= '' . PHP_EOL;
        $html .= '
' . PHP_EOL;
        $no = 1;
        foreach( $klasses as $klass )
        {
            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . $klass . '	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $no ++;
        }
        $html .= '
' . PHP_EOL;

        // output exception stack
        $html .= '

Exception Stack

' . PHP_EOL;

        $hash = sha1($file . $line);

        $src = new PhpSourceInfo( $file, $line, 10 );
        $html .= '
' . PHP_EOL;
        $html .= '    ' . $file . '(' . $line . ')' . ' View Source' . PHP_EOL;
        $html .= '
' . $src . '
' . PHP_EOL;
        $html .= '
' . PHP_EOL;

        $html .= '
' . PHP_EOL;
        $no = 1;
        $backtrace = NULL;
        while( $e )
        {
            $clazz = get_class($e);
            $file = $e->getFile();
            $line = $e->getLine();
            $message = $e->getMessage();
            $backtrace = ($e instanceof CalgamoException) ? $e->getBackTraceList() : NULL;

            $src = new PhpSourceInfo( $file, $line, 10 );

            $hash = sha1($file . $line);

            $html .= '
' . PHP_EOL;
            $html .= '  ' . $no . '	' . PHP_EOL;
            $html .= '  ' . PHP_EOL;
            $html .= '    class:' . $clazz . '' . PHP_EOL;
            $html .= '    file:' . $file . '(' . $line . ')' . PHP_EOL;
            $html .= '  	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . $message . '
	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
View Source
' . PHP_EOL;
            $html .= '
' . $src . '
' . PHP_EOL;
            $html .= '  	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $e = method_exists( $e, 'getPrevious' ) ? $e->getPrevious() : NULL;
            $no ++;
        }
        $html .= '
' . PHP_EOL;

        if ( $backtrace === NULL || !is_array($backtrace) ){
            return $html;
        }

        // output call stack
        $html .= '

Call Stack

' . PHP_EOL;

        $html .= '
' . PHP_EOL;
        $call_no = 1;
        foreach( $backtrace as $element ){
            $klass = isset($element['class']) ? $element['class'] : '';
            $func  = isset($element['function']) ? $element['function'] : '';
            $type  = isset($element['type']) ? $element['type'] : '';
            $args  = isset($element['args']) ? $element['args'] : array();
            $file  = isset($element['file']) ? $element['file'] : '';
            $line  = isset($element['line']) ? $element['line'] : 0;

            if ( $type == "::" ){
                $ref_method = new \ReflectionMethod( $klass, $func );
                $modifiers = \Reflection::getModifierNames( $ref_method->getModifiers() );
                $modifiers = implode(" ",$modifiers);
                $params = $ref_method->getParameters();

                $args_defs = '';
                foreach( $params as $p ){
                    if ( strlen($args_defs) > 0 ){
                        $args_defs .= ',';
                    }
                    if ( $p->isOptional() ){
                        $args_defs .= '[';
                    }
                    if ( $p->isArray() ){
                        $args_defs .= 'array ';
                    }
                    $args_defs .= $p->getClass();
                    if ( $p->isPassedByReference() ){
                        $args_defs .= '&';
                    }
                    $args_defs .= $p->getName();

                    if ( $p->isDefaultValueAvailable() ){
                        $args_defs .= '=' . $p->getDefaultValue();
                    }

                    if ( $p->isOptional() ){
                        $args_defs .= ']';
                    }
                }

                $args_disp  = '
';
                $args_disp .= '
';
                $args_disp .= '  No	';
                $args_disp .= '  value	';
                $args_disp .= '
';
                foreach( $args as $key => $arg ){
                    $args_disp .= '
';
                    $args_disp .= '  ' . $key . '	';
                    $args_disp .= '  ' . Util::toString($arg) . '	';
                    $args_disp .= '
';
                }
                $args_disp .= '
';

                $message = "$modifiers {$klass}{$type}{$func}($args_defs)
$args_disp";
            }
            else{
                $args_disp = '';
                foreach( $args as $arg ){
                    if ( strlen($args_disp) > 0 ){
                        $args_disp .= ',';
                    }
                    $args_disp .= '"' . Util::toString($arg) . '"';
                }
                $message = "{$klass}{$type}{$func}($args_disp)";
            }

            $src = new PhpSourceInfo( $file, $line, 10 );

            $hash = Util::hash( 'sha1', $file.$line );

            $html .= '
' . PHP_EOL;
            $html .= '  ' . $call_no . '	' . PHP_EOL;
            $html .= '  ' . PHP_EOL;
            $html .= '    class:' . $klass . '' . PHP_EOL;
            $html .= '    file:' . $file . '(' . $line . ')' . PHP_EOL;
            $html .= '    ' . PHP_EOL;
            $html .= '  	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . $message . '
	' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
' . PHP_EOL;
            $html .= '
View Source
' . PHP_EOL;
            $html .= '
' . $src . '
' . PHP_EOL;
            $html .= '  	' . PHP_EOL;
            $html .= '
' . PHP_EOL;

            $call_no ++;
        }
        $html .= '
' . PHP_EOL;

        return $html;
    }

function getTemplate(template, options) {
  stack.clear();
  parser.reset();

  let opts = typeof options === 'undefined' ? {} : options;
  opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
  opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
  opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
  opts.logger = opts.logger != null ? opts.logger : {};

  let lambdas = {};
  if (_.isArray(opts.lambdas)) {
    for (let i = 0; i < opts.lambdas.length; i++) {
      lambdas[opts.lambdas[i]] = true;
    }
  }
  opts.lambdas = lambdas;
  opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true;

  compilerLogger.setStrictMode(opts.strict);
  compilerLogger.setOverrides(opts.logger);
  stack.setHtmlValidation(opts.validateHtml);

  let templateStr = template.toString();

  processTemplate(templateStr, opts);

  let output = {};

  if (stack.stack.length > 0) {
    compilerErrors.notAllTagsWereClosedProperly(stack.stack);
  }

  parser.end();
  output.templateObj = stack.getOutput();
  const Template = require('../template');
  output.template = new Template(output.templateObj);
  output.source = template;
  output.tokens = {};
  _.each(stack.tokens, function(values, type) {
    output.tokens[type] = _.keys(values);
  });
  return output;
}

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


Question: // QueryUint64 returns request form as uint64 with default

func (ctx *Context) QueryUint64(key string, defaults ...uint64) uint64 {
	return (*Queries)(ctx.req).MustUint64(key, defaults...)
}

func GenerateOTPURL(typ string, label string, parameters map[string][]byte) string {
	var u url.URL

	u.Scheme = "otpauth"
	u.Host = typ
	u.Path = label

	var params url.Values = make(url.Values)
	for k, v := range parameters {
		if k == "secret" {
			v = []byte(base32.StdEncoding.EncodeToString(v))
		}
		params.Add(k, string(v))
	}
	u.RawQuery = params.Encode()

	return u.String()
}

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


Question: Equivalent to __send_exc_clear

def __recv_exc_clear(self, log_if_exc_set=None):
        """"""
        if not (log_if_exc_set is None or self.__recv_exc is None):
            logger.info(log_if_exc_set)
        self.__recv_exc = None

func (xw *Writer) Reset(wr io.Writer) error {
	*xw = Writer{
		wr:   wr,
		mw:   xw.mw,
		zw:   xw.zw,
		nchk: xw.nchk,
		nidx: xw.nidx,
		idx:  xw.idx,
	}
	if xw.zw == nil {
		xw.zw, _ = newFlateWriter(wr, DefaultCompression)
	} else {
		xw.zw.Reset(wr)
	}
	if xw.nchk == 0 {
		xw.nchk = DefaultChunkSize
	}
	if xw.nidx == 0 {
		xw.nidx = DefaultIndexSize
	}
	xw.idx.Reset()
	return nil
}

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


Question:
Returns the selected column name.

@throws Exception if the column is not found

protected function getColumnIndexByValue(string $value, string $error_message): string
    {
        if (false !== array_search($value, $this->header, true)) {
            return $value;
        }

        throw new Exception(sprintf($error_message, $value));
    }

private function getColumns($data)
        {
            $cols = [];

            foreach ($data[0] as $key => $value) {
                if (is_numeric($key)){
                    if (is_string($data[1][$key])) {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'number'];
                    }

                    $this->_skipFirstRow = true;
                } else {
                    if (is_string($value)) {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'number'];
                    }
                }
            }

            return $cols;
        }

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


Question: // JSON decodes the JSON in the request's body to the out interface

func (wc *WebhookContext) JSON(out interface{}) error {
	var err error
	if wc.body == nil {
		wc.firstParse = true
		wc.body, err = ioutil.ReadAll(wc.gin.Request.Body)

		if err != nil {
			return err
		}
	}
	err = json.Unmarshal(wc.body, out)

	if err != nil && strings.HasPrefix(string(wc.body), "payload=") {
		s := string(wc.body)
		s, err = uurl.QueryUnescape(s[8:])
		if err != nil {
			return err
		}
		err = json.Unmarshal([]byte(s), out)

	}
	return err
}

public function handleEncode(EncodeValueEvent $event)
    {
        $definition = $event->getValue();
        if (!$definition instanceof Definition) {
            return;
        }

        $type   = $definition->getType();
        $method = 'encode' . $this->convertTypeToMethod($type);

        if (method_exists($this, $method)) {
            $buffer = $this->$method($definition, $event->getEncoder(), $event->getJsonFlags());

            if ($buffer) {
                $event->addLine($buffer);
                $this->handleMethodCalls($definition, $event->getEncoder(), $event);
            }

            $event->setSuccessful();
        }
    }

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


Question:
flushStderr.

@return a {@link java.util.List} object.
@throws java.io.IOException if any.

public List<String> flushStderr() throws IOException {
		List<String> result = new ArrayList<String>();
		while(stderr.ready()) {
			result.add(stderr.readLine());
		}
		return result;
	}

public static String rowToString(JSONArray ja) {

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < ja.length(); i += 1) {
            if (i > 0) {
                sb.append(',');
            }
            Object o = ja.opt(i);
            if (o != null) {
                String s = o.toString();
                if (s.indexOf(',') >= 0) {
                    if (s.indexOf('"') >= 0) {
                        sb.append('\'');
                        sb.append(s);
                        sb.append('\'');
                    } else {
                        sb.append('"');
                        sb.append(s);
                        sb.append('"');
                    }
                } else {
                    sb.append(s);
                }
            }
        }
        sb.append('\n');
        return sb.toString();

    }

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


Question:
Constructs a Component object
@param  {String} compName
@param  {Object} filter
@param  {Object} options
@return {Component}

function fetchComponent(compName, filter, options) {
    var componentFiles = [];
    _.each(filter, function(destDir, expression) {
      var fileInfo = path.parse(path.resolve(BOWER_DIRECTORY, compName, expression));
      var sourceDir = fileInfo.dir;

      var dirContent = fs.readdirSync(sourceDir);
      var expressionObj = {};
      expressionObj[expression] = destDir;

      dirContent = dirContent.map(function(file) {
        return path.resolve(BOWER_DIRECTORY, compName, file);
      });

      Array.prototype.push.apply(componentFiles,
        filterByExpression(dirContent, expressionObj, options));

    });
    console.log(componentFiles.length + ' file(s) found for ' + compName);
    var bowerObj = getBower(compName);
    return new Component(bowerObj, componentFiles);
  }

public function render(array $data, ContextInterface $context)
    {
        $data = optionsParser($data, [
            'name' => '',
            'val' => null,
            'type' => 'text',
            'escape' => true,
            'templateVars' => [],
        ]);
        $data->add('value', $data->consume('val'));

        return $this->_templates->format('hidden', [
            'name' => $data->get('name'),
            'type' => $data->get('type'),
            'templateVars' => $data->get('templateVars'),
            'attrs' => $this->_templates->formatAttributes($data->toArray(), ['name', 'type']),
        ]);
    }

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


Question:
Validate the signature on the response

@param  \Yubikey\Response $response Response instance
@return boolean Pass/fail status of signature validation

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

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

def onHello(self, realm, details):

        log.msg("onHello: {} {}".format(realm, details))

        self._pending_auth = None

        if details.authmethods:
            for authmethod in details.authmethods:
                if authmethod == u"wampcra":

                    ## lookup user in user DB
                    salt, key, role, uid = yield self.factory.userdb.get(details.authid)
                    log.msg("salt, key, role: {} {} {} {}".format(salt, key, role, uid))

                    ## if user found ..
                    if key:

                        log.msg("found key")

                        ## setup pending auth
                        self._pending_auth = PendingAuth(key, details.pending_session,
                            details.authid, role, authmethod, u"userdb", uid)

                        log.msg("setting challenge")
                        ## send challenge to client
                        extra = {
                            u'challenge': self._pending_auth.challenge
                        }

                        ## when using salted passwords, provide the client with
                        ## the salt and then PBKDF2 parameters used
                        if salt:
                            extra[u'salt'] = salt
                            extra[u'iterations'] = 1000
                            extra[u'keylen'] = 32

                        defer.returnValue(types.Challenge(u'wampcra', extra))

        ## deny client
        defer.returnValue(types.Deny())

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


Question:
Return fonts, fills, borders, xfs xml strings.

@param Component[] $components
@return string

private function getComponentXml(array $components)
    {
        $componentXml = '';
        foreach ($components as $component) {
            $componentXml .= $component->asXml();
        }
        return $componentXml;
    }

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

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

        $generator->startList('Tag');

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

        $generator->endList('Tag');

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

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


Question:
Find the maximum ordering within this parent

@return int

protected function getMaxOrdering()
    {
        $table  = $this->getTable();
        $db     = $table->getAdapter();

        $query = $this->getObject('lib:database.query.select')
            ->columns('MAX(ordering)')
            ->table($table->getName());

        $this->_buildQueryWhere($query);

        return (int) $db->select($query, KDatabase::FETCH_FIELD);
    }

def _do_document(self, node):
        ''''''

        self.documentOrder = _LesserElement
        for child in node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE:
                self.documentOrder = _Element        # At document element
                self._do_element(child)
                self.documentOrder = _GreaterElement # After document element
            elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
                self._do_pi(child)
            elif child.nodeType == Node.COMMENT_NODE:
                self._do_comment(child)
            elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
                pass
            else:
                raise TypeError, str(child)

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


Question:
Parses a query string item according to the connection string spec

@param {string} key The key for the parsed value
@param {Array|String} value The value to parse
@return {Array|Object|String} The parsed value

function parseQueryStringItemValue(key, value) {
  if (Array.isArray(value)) {
    // deduplicate and simplify arrays
    value = value.filter((v, idx) => value.indexOf(v) === idx);
    if (value.length === 1) value = value[0];
  } else if (value.indexOf(':') > 0) {
    value = value.split(',').reduce((result, pair) => {
      const parts = pair.split(':');
      result[parts[0]] = parseQueryStringItemValue(key, parts[1]);
      return result;
    }, {});
  } else if (value.indexOf(',') > 0) {
    value = value.split(',').map(v => {
      return parseQueryStringItemValue(key, v);
    });
  } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
    value = value.toLowerCase() === 'true';
  } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) {
    const numericValue = parseFloat(value);
    if (!Number.isNaN(numericValue)) {
      value = parseFloat(value);
    }
  }

  return value;
}

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question: Place any commands to setup depotexample here

def setup_schema(command, conf, vars):
    """"""
    # Load the models

    # <websetup.websetup.schema.before.model.import>
    from depotexample import model
    # <websetup.websetup.schema.after.model.import>

    # <websetup.websetup.schema.before.metadata.create_all>
    print("Creating tables")
    model.metadata.create_all(bind=config['tg.app_globals'].sa_engine)
    # <websetup.websetup.schema.after.metadata.create_all>
    transaction.commit()
    print('Initializing Migrations')
    import alembic.config, alembic.command
    alembic_cfg = alembic.config.Config()
    alembic_cfg.set_main_option("script_location", "migration")
    alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url'])
    alembic.command.stamp(alembic_cfg, "head")

def drop kwargs={}
      force = kwargs.arg :force, false

      cmd = 'aptly snapshot drop'
      cmd += ' -force' if force
      cmd += " #{@name.quote}"

      Aptly::runcmd cmd
    end

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


Question:
Returns the layout based on the connected watch
@returns {Array}

function autoLayout() {
      if (!clay.meta.activeWatchInfo ||
          clay.meta.activeWatchInfo.firmware.major === 2 ||
          ['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 &&
          !self.config.allowGray) {
        return standardLayouts.BLACK_WHITE;
      }

      if (['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 &&
          self.config.allowGray) {
        return standardLayouts.GRAY;
      }

      return standardLayouts.COLOR;
    }

public function render(OutputInterface $output, ResultCollection $results)
    {
        $output->write($this->getHeader());

        $table = new Table($output);
        $table->setHeaders(['File', 'Times Changed', 'Complexity', 'Score']);
        $table->addRows($results->toArray());
        $table->render();

        $output->write("\n");
    }

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


Question:
@param \PHPMD\AbstractNode $node

@return void

public function apply(AbstractNode $node)
    {
        if (preg_match('#[A-Za-z0-9]+Constants$#', $node->getName()) === 0 ||
            preg_match('#\\\\Shared\\\\#', $node->getNamespaceName()) !== 0) {
            return;
        }

        $message = sprintf(
            'The environment configuration is not lie in "Shared" layer. That violates the rule "%s"',
            static::RULE
        );

        $this->addViolation($node, [$message]);
    }

func NewPartialStatement(pos int, line int) *PartialStatement {
	return &PartialStatement{
		NodeType: NodePartial,
		Loc:      Loc{pos, line},
	}
}

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


Question:
Return the `AerospikeStore` extending `express`'s session Store.

@param {Object} express session
@return {Function}
@public

function AerospikeStore (options) {
    if (!(this instanceof AerospikeStore)) {
      throw new TypeError('Cannot call AerospikeStore constructor as a function')
    }

    options = options || {}
    Store.call(this, options)

    this.as_namespace = options.namespace || 'test'
    this.as_set = options.set || 'express-session'
    this.ttl = options.ttl
    this.mapper = options.mapper || new DataMapper()

    if (options.serializer) {
      throw new Error('The `serializer` option is no longer supported - supply a custom data mapper instead.')
    }

    if (options.client) {
      this.client = options.client
    } else {
      this.client = Aerospike.client(options)
      this.client.connect(error => {
        if (error) {
          debug('ERROR - %s', error.message)
          process.nextTick(() => this._onDisconnected())
        } else {
          process.nextTick(() => this._onConnected())
        }
      })
    }

    this.connected = false
    this.client.on('nodeAdded', () => this._onConnected())
    this.client.on('disconnected', () => this._onDisconnected())
  }

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

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

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

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


Question:
Retrieves metadata about the object.

    Returns:
      An ObjectMetadata instance with information about this object.
    Raises:
      Exception if there was an error requesting the object's metadata.

def metadata(self):

    if self._info is None:
      try:
        self._info = self._api.objects_get(self._bucket, self._key)
      except Exception as e:
        raise e
    return ObjectMetadata(self._info) if self._info else None

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Run adb from the Android SDK.
        Args must come after --, or use
        --alias to make an alias

def cmd_adb(self, *args):
        '''

        '''
        self.check_requirements()
        self.install_platform()
        args = args[0]
        if args and args[0] == '--alias':
            print('To set up ADB in this shell session, execute:')
            print('    alias adb=$(buildozer {} adb --alias 2>&1 >/dev/null)'
                  .format(self.targetname))
            sys.stderr.write(self.adb_cmd + '\n')
        else:
            self.buildozer.cmd(' '.join([self.adb_cmd] + args))

def _build_egg(egg, archive_filename, to_dir):
    """"""
    with archive_context(archive_filename):
        # building an egg
        log.warn('Building a Setuptools egg in %s', to_dir)
        _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
    # returning the result
    log.warn(egg)
    if not os.path.exists(egg):
        raise IOError('Could not build the egg.')

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


Question:
/* (non-Javadoc)
@see com.oath.cyclops.types.Zippable#zip(java.util.function.BiFunction, org.reactivestreams.Publisher)

public <T2, R> ValueTransformer<W,R> zip(BiFunction<? super T, ? super T2, ? extends R> f, Publisher<? extends T2> publisher) {

        return unitAnyM(this.transformerStream().map(v->v.zip(f, publisher)));
    }

public function copyModuleFiles(PackageEvent $event): void
    {
        $package = $this->extractPackage($event);
        $this->packagePath = $this->vendorPath .DS. $package->getName();
        if ($package->getType() === 'bluz-module' && file_exists($this->packagePath)) {
            if ($package->getExtra() && isset($package->getExtra()['copy-files'])) {
                $this->copyExtras($package->getExtra()['copy-files']);
            }
            $this->copyModule();
        }
    }

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


Question:
Middle aligns the owner to the other.

@param <T> the generic type
@param other the other
@param offset the offset
@return the int supplier

public static <T extends IPositioned & ISized> IntSupplier middleAlignedTo(ISized owner, T other, int offset)
	{
		checkNotNull(other);
		return () -> {
			return (int) (other.position().y() + Math.ceil(((float) other.size().height() - owner.size().height()) / 2) + offset);
		};
	}

public function parse($template)
    {
        $parts   = preg_split('#(\{[^\}]+\})#', $template, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        $nodes   = array();

        foreach($parts as $part) {
            $node = $this->createNode($part);

            // if current node has dot separator that requires a forward lookup
            // for the previous node iff previous node's operator is UnNamed
            if ($node instanceof Expression && $node->getOperator()->id === '.') {
                if (sizeof($nodes) > 0) {
                    $previousNode = $nodes[sizeof($nodes) - 1];
                    if ($previousNode instanceof Expression && $previousNode->getOperator() instanceof UnNamed) {
                        $previousNode->setForwardLookupSeparator($node->getOperator()->id);
                    }
                }
            }

            $nodes[] = $node;
        }

        return $nodes;
    }

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


Question:
Iterates in the index and shifts the offset

@return Array

private function iterateKeyReader()
    {
        $results = $this->index->getKeyReader()->readKeys(
            $this->offset,
            $this->direction,
            $this->parseHints
        );
        if (empty($results)) {
            return $results;

        }

        // reverse order if iterating backwards
        if ($this->direction == KeyReader::DIRECTION_BACKWARD) {
            // $results = array_reverse($results);

            // trim results to the offset and reverse the order
            $revertBackwardResults = array();
            foreach ($results as $result) {
                if ($result->getOffset() > $this->offset) {
                    break;

                }
                array_unshift($revertBackwardResults, $result);

            }
            $results = $revertBackwardResults;

        }

        // shift offset
        $end = end($results);
        switch ($this->direction) {

            case KeyReader::DIRECTION_FORWARD:
                $this->setOffset($end->getOffset() + strlen($end->getData()));
                break;

            case KeyReader::DIRECTION_BACKWARD:
                $this->setOffset($end->getOffset() - 1);
                break;

            default:
                throw new \LogicException("invalid direction");

        }

        // remove duplicates (BACKWARD only)
        $this->avoidBackwardDuplicates($results);

        reset($results);
        return $results;
    }

public function setPointer($charOffset)
    {
        if ($this->charCount < $charOffset) {
            $charOffset = $this->charCount;
        }
        $this->currentPos = $charOffset;
    }

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


Question:
Adds the siblings (= other children of the parent) of the current menu item to this list

@param boolean $anyParameters When false, siblings must have the same parameter set as the current menu item
@return \Gems_Menu_MenuList (continuation pattern)

public function addCurrentSiblings($anyParameters = false, $includeCurrent = false)
    {
        if ($current = $this->menu->getCurrent()) {
            if ($parent = $current->getParent()) {
                $parameters = $current->getParameters();
                if ($includeCurrent) {
                    $current = null;
                }

                foreach ($parent->getChildren() as $menuItem) {
                    // Add any menu item that is not the current menu item
                    // and that has the same parameters, unless $anyParameters is true.
                    if (($menuItem !== $current) && ($anyParameters || ($menuItem->getParameters() == $parameters))) {
                        $this->addMenuItem($menuItem);
                    }
                }
            }
        }
        return $this;
    }

def _set_menu_toggles(self):
        """"""

        toggles = [
            (self.main_toolbar, "main_window_toolbar", _("Main toolbar")),
            (self.macro_toolbar, "macro_toolbar", _("Macro toolbar")),
            (self.macro_panel, "macro_panel", _("Macro panel")),
            (self.attributes_toolbar, "attributes_toolbar",
             _("Format toolbar")),
            (self.find_toolbar, "find_toolbar", _("Find toolbar")),
            (self.widget_toolbar, "widget_toolbar", _("Widget toolbar")),
            (self.entry_line_panel, "entry_line_panel", _("Entry line")),
            (self.table_list_panel, "table_list_panel", _("Table list")),
        ]

        for toolbar, pane_name, toggle_label in toggles:
            # Get pane from aui manager
            pane = self._mgr.GetPane(pane_name)

            # Get menu item to toggle
            toggle_id = self.menubar.FindMenuItem(_("View"), toggle_label)
            if toggle_id != -1:
                # Check may fail if translation is incomplete
                toggle_item = self.menubar.FindItemById(toggle_id)

                # Adjust toggle to pane visibility
                toggle_item.Check(pane.IsShown())

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


Question:
Only very limited support for transformations, so {@link #supportsTransformations()} still returns false.

@param element
@param transform

public void setTransform(Element element, String transform) {
		if (transform.contains("scale")) {
			try {
				String scaleValue = transform.substring(transform.indexOf("scale(") + 6);
				scaleValue = scaleValue.substring(0, scaleValue.indexOf(")"));
				Dom.setStyleAttribute(element, "zoom", scaleValue);
			} catch (Exception e) {
			}
		}
	}

def process_children(self, node, path, level, parent=None):

        data_parent = parent if parent else node
        chs = node.i_children
        for ch in chs:
            if ch.keyword in ["choice", "case"]:
                self.process_children(ch, path, level, node)
                continue
            p = path + "/" + self.qname(ch)
            tmpl = self.xsl_template(p)
            ct = self.xsl_calltemplate(ch.keyword, tmpl)
            self.xsl_withparam("level", "%d" % level, ct)
            if (data_parent.i_module is None or
                ch.i_module.i_modulename != data_parent.i_module.i_modulename):
                self.xsl_withparam("nsid", ch.i_module.i_modulename + ":", ct)
            if ch.keyword in ["leaf", "leaf-list"]:
                self.type_param(ch, ct)
            elif ch.keyword != "anyxml":
                offset = 2 if ch.keyword == "list" else 1
                self.process_children(ch, p, level + offset)

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


Question: // SetVolumeKmsKeyId sets the VolumeKmsKeyId field's value.

func (s *TopicsDetectionJobProperties) SetVolumeKmsKeyId(v string) *TopicsDetectionJobProperties {
	s.VolumeKmsKeyId = &v
	return s
}

func (c *ClientsetSecretStore) createSecret(s *fi.Secret, name string, replace bool) (*kops.Keyset, error) {
	keyset := &kops.Keyset{}
	keyset.Name = NamePrefix + name
	keyset.Spec.Type = kops.SecretTypeSecret

	t := time.Now().UnixNano()
	id := pki.BuildPKISerial(t)

	keyset.Spec.Keys = append(keyset.Spec.Keys, kops.KeysetItem{
		Id:              id.String(),
		PrivateMaterial: s.Data,
	})

	if replace {
		return c.clientset.Keysets(c.namespace).Update(keyset)
	}
	return c.clientset.Keysets(c.namespace).Create(keyset)
}

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


Question: Returns a new instance with the given writable link flag.

public function withWritableLink(bool $writableLink): self
    {
        $metadata = clone $this;
        $metadata->writableLink = $writableLink;

        return $metadata;
    }

def mount(self, readonly=True):

        self._handler.add_drive_opts(self.disk_path, readonly=True)
        self._handler.launch()

        for mountpoint, device in self._inspect_disk():
            if readonly:
                self._handler.mount_ro(device, mountpoint)
            else:
                self._handler.mount(device, mountpoint)

        if self._handler.inspect_get_type(self._root) == 'windows':
            self.path = self._windows_path
        else:
            self.path = posix_path

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


Question:
Include and add our Service Provider to the App config.

@param  string $configPath

@return array

protected function buildAppConfig($configPath)
    {
        $config = require($configPath);

        $callback = Arr::get($this->config, 'callback.vendor_config');
        if ($callback instanceof Closure) {
            $config = call_user_func($callback, $config);
        }

        return $config;
    }

protected function loadConfiguration()
    {
        try {
            $configuration = $this->configurationStorage->loadFromFile()->get();
        } catch (NoConfigurationException $e) {

            $this->io->comment($e->getMessage());

            if (!$this->secret) {
                $this->secret = $this->io->ask('Secret');
            }
            $configuration = $this->parseConfigurationKey();
        }
        $this->serverUrl = $configuration['socket_url'];
        $this->secret = $configuration['secret'];
        $this->configurationStorage->merge($configuration)->save();
    }

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


Question:
Creates a new binary special method with left and right versions, such as
        A.__mul__(B) <=> A*B,
        A.__rmul__(B) <=> [B*A if B.__mul__(A) fails]
    for target class. The method is called __op_name__.

def create_rl_bin_method(op_name, klass, jacobians={}):

    # Make left and right versions.
    for prefix in ['r', '']:
        # This function will became the methods.
        op_modules = [operator, builtins]
        op_names = [op_name, op_name + '_']

        op_function_base = find_element(
            op_names,
            op_modules,
            error_on_fail=True)
        # many such functions do not take keyword arguments, so we need to wrap
        # them

        def op_function(a, b):
            return op_function_base(a, b)

        def new_method(self, other, prefix=prefix):
            if not check_special_methods():
                raise NotImplementedError(
                    'Special method %s called on %s, but special methods have been disabled. Set pymc.special_methods_available to True to enable them.' %
                    (op_name, str(self)))
            # This code will create one of two Deterministic objects.
            if prefix == 'r':
                parents = {'a': other, 'b': self}

            else:
                parents = {'a': self, 'b': other}
            jacobian_formats = {'a': 'broadcast_operation',
                                'b': 'broadcast_operation'}
            return pm.Deterministic(op_function,
                                    'A Deterministic returning the value of %s(%s,%s)' % (
                                        prefix + op_name, self.__name__, str(
                                            other)),
                                    '(' + '_'.join(
                                        [self.__name__,
                                         prefix + op_name,
                                         str(other)]) + ')',
                                    parents,
                                    trace=False,
                                    plot=False,
                                    jacobians=jacobians,
                                    jacobian_formats=jacobian_formats)
        # Convert the functions into methods for klass.
        new_method.__name__ = '__' + prefix + op_name + '__'
        setattr(
            klass,
            new_method.__name__,
            UnboundMethodType(
                new_method,
                None,
                klass))

func (rl *RevelLogger) Errorf(msg string, param ...interface{}) {
	rl.Error(fmt.Sprintf(msg, param...))
}

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


Question: Constructs the tensorflow graph of the hierarchical model.

def construct_model(images,
                    actions=None,
                    context_frames=2,
                    hparams=None,
                    is_training=True):
  """"""

  pred_depth = 20

  enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [], [], [], []

  lstm_states = [None] * (pred_depth + 2)

  enc_out = encoder_vgg(
      images[0], hparams.enc_size, False, scope_prefix='timestep/',
      hparams=hparams, is_training=is_training)
  enc_out = tf.identity(enc_out, 'enc_out')
  enc_out_all.append(enc_out)

  num_timesteps = len(actions) - 1
  sum_freq = int(num_timesteps / 4 + 1)

  reuse = False
  for timestep, action in zip(range(len(actions) - 1), actions[:-1]):
    done_warm_start = timestep > context_frames - 1

    with tf.variable_scope('timestep', reuse=reuse):
      if done_warm_start:
        pred_input = pred_out_all[-1]
      else:
        pred_input = enc_out_all[-1]
      pred_out = predictor(
          pred_input, action, lstm_states, pred_depth, False, hparams=hparams)
      pred_out = tf.identity(pred_out, 'pred_out')
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('pred_out', pred_out)
      pred_out_all.append(pred_out)

      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('lstm_state', lstm_states[0])
      van_out, _, _ = van(
          enc_out_all[0],
          images[0],
          pred_out,
          images[timestep + 1],
          tf.AUTO_REUSE,
          hparams=hparams)
      van_out = tf.identity(van_out, 'van_out')
      van_out_all.append(van_out)

      enc_out = encoder_vgg(
          images[timestep + 1], hparams.enc_size, True, hparams=hparams,
          is_training=is_training)
      enc_out = tf.identity(enc_out, 'enc_out')
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('enc_out', enc_out)
      enc_out_all.append(enc_out)

      van_input = images[0]
      enc_noise = tf.zeros_like(enc_out)
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('enc_noise', enc_noise)
      van_on_enc, _, _ = van(
          enc_out_all[0],
          van_input,
          enc_out + enc_noise,
          images[timestep + 1],
          tf.AUTO_REUSE,
          hparams=hparams)
      van_on_enc = tf.identity(van_on_enc, 'van_on_enc')
      van_on_enc_all.append(van_on_enc)

      reuse = True

  return enc_out_all, pred_out_all, van_out_all, van_on_enc_all

def training(self):

        handles = [h for h in self._handles if h.is_training]
        return TowerTensorHandles(handles)

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


Question:
:param request: OAuthlib request.
        :type request: oauthlib.common.Request

def validate_request(self, request):

        token = get_token_from_header(request)
        return self.request_validator.validate_bearer_token(
            token, request.scopes, request)

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

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

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

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


Question:
Returns the available classes a given type.

@method catalogEntriesByType
@param {String} type The type. e.g. "model", "controller", "route"
@return {Array} An array of strings.

function(type) {
        var namespaces = emberA(Namespace.NAMESPACES), types = emberA(), self = this;
        var typeSuffixRegex = new RegExp(classify(type) + "$");

        namespaces.forEach(function(namespace) {
          if (namespace !== Ember) {
            for (var key in namespace) {
              if (!namespace.hasOwnProperty(key)) { continue; }
              if (typeSuffixRegex.test(key)) {
                var klass = namespace[key];
                if (typeOf(klass) === 'class') {
                  types.push(dasherize(key.replace(typeSuffixRegex, '')));
                }
              }
            }
          }
        });
        return types;
      }

public function addRoute($route)
    {
        if (!$route instanceof Route && !is_array($route)) {
            throw new \LogicException('Route invalid. Expected Route instance or array.');
        } elseif ($route instanceof Route) {
            $name = $route->getName();
            if (isset($this->routes[$name])) {
                throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name));
            }
            $this->routes[$route->getName()] = $route;
        } elseif (is_array($route) && !count($route) == 4) {
            throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).');
        } else {
            list($methods, $patternUri, $action, $name) = array_values($route);

            $this->routes[$name] = new Route($methods, $patternUri, $action, $name);
        }

        return $this;
    }

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


Question: Compute *x* and *y* coordinates at which to plot the positions.

def build_stereographic_projection(center):
    """"""

    # TODO: Computing the center should really be done using
    # optimization, as in:
    # https://math.stackexchange.com/questions/409217/
    p = center.position.au
    u = p / length_of(p)
    c = u.mean(axis=1)
    c = c / length_of(c)
    x_c, y_c, z_c = c

    def project(position):
        p = position.position.au
        u = p / length_of(p)
        x, y, z = u
#        x_out = (x*y_c/sqrt(x_c**2 + y_c**2) - x_c*y/sqrt(x_c**2 + y_c**2))/(x*x_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + y*y_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + z*z_c + 1)
#        y_out = (-x*x_c*z_c/sqrt(x_c**2 + y_c**2) - y*y_c*z_c/sqrt(x_c**2 + y_c**2) + z*sqrt(-z_c**2 + 1))/(x*x_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + y*y_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + z*z_c + 1)
#        return x_out, y_out

        t0 = 1/sqrt(x_c**2 + y_c**2)
        t1 = x*x_c
        t2 = sqrt(-z_c**2 + 1)
        t3 = t0*t2
        t4 = y*y_c
        t5 = 1/(t1*t3 + t3*t4 + z*z_c + 1)
        t6 = t0*z_c

        return t0*t5*(x*y_c - x_c*y), -t5*(t1*t6 - t2*z + t4*t6)

    return project

@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "coord")
    public JAXBElement<CoordType> createCoord(CoordType value) {
        return new JAXBElement<CoordType>(_Coord_QNAME, CoordType.class, null, value);
    }

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


Question:
Remove directory content
@access public
@param $dir       string : path
@param $removeDir : remove subdirectories too
@param $except : files you don't want to delete
@return void
@since 3.0
@package Gcs\Framework\Core\Terminal

public static function rrmdir($dir, $removeDir = false, $except = []) {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir . "/" . $object) == "dir") {
                        Terminal::rrmdir($dir . "/" . $object, $removeDir, $except);

                        if ($removeDir == true) {
                            rmdir($dir . "/" . $object . '/');
                        }
                    }
                    else {
                        if (!in_array($object, $except)) {
                            unlink($dir . "/" . $object);
                        }
                    }
                }
            }
            reset($objects);
        }
    }

function (section, data, ginaData) {

            try {
                var txt = $json.text();
                if (txt == '' || txt == 'null' ) {
                    $json.text('Empty')
                } else {
                    jsonObject = JSON.parse(txt);
                    ginaJsonObject = JSON.parse($ginaJson.text());
                    $json.text('');

                    // backing up document data
                    if (!originalData) {
                        originalData = {
                            jsonObject      : JSON.parse(JSON.stringify(jsonObject)),
                            ginaJsonObject  : JSON.parse(JSON.stringify(ginaJsonObject))
                        }
                    }
                }

            } catch (err) {
                $json.text('Could not load data');
            }

            if (jsonObject) {

                if (data && !ginaData) {
                    if ( !jsonObject[section] )
                        jsonObject[section] = {};

                    jsonObject[section] = ginaJsonObject[section] = data;

                } else if ( section == 'data-xhr' && !data && jsonObject['data-xhr'] ) {
                    // reset xhr
                    delete jsonObject['data-xhr'];
                } else if (ginaData) {
                    jsonObject      = data;
                    ginaJsonObject  = ginaData;
                }

                // Make folding paths
                makeFoldingPaths(jsonObject, '');
                // Create DOM from JSON
                $htmlData.html('
' + parseObject(jsonObject, ginaJsonObject) +'
');

                // Manage folding state
                settings.currentFile = jsonObject.file;
                if (!settings.currentFile) {
                    // Init currentFile if none exists
                    settings.currentFile = jsonObject.file;
                } else if (jsonObject.file == settings.currentFile) {
                    // If current page is the same as the previous page, unfold code as neede
                    $(document).ready(function () {
                        if ( settings.isUnfolded.length > 0)
                            initFoldingState(settings.isUnfolded, settings.isUnfolded.length, 0);
                    })
                }
            }
        }

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


Question: // Size returns the size of the command in bytes.

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

public void setDocumentSize(int v) {
    if (SourceDocumentInformation_Type.featOkTst && ((SourceDocumentInformation_Type)jcasType).casFeat_documentSize == null)
      jcasType.jcas.throwFeatMissing("documentSize", "org.apache.uima.examples.SourceDocumentInformation");
    jcasType.ll_cas.ll_setIntValue(addr, ((SourceDocumentInformation_Type)jcasType).casFeatCode_documentSize, v);}

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


Question:
Returns the Fluid template source code

@param string $actionName Name of the action. This argument is not used in this view!
@return string Fluid template source
@throws Exception\InvalidTemplateResourceException

protected function getTemplateSource($actionName = null)
    {
        if ($this->templateSource === null && $this->templatePathAndFilename === null) {
            throw new Exception\InvalidTemplateResourceException('No template has been specified. Use either setTemplateSource() or setTemplatePathAndFilename().', 1288085266);
        }
        if ($this->templateSource === null) {
            if (!is_file($this->templatePathAndFilename)) {
                throw new Exception\InvalidTemplateResourceException('Template could not be found at "' . $this->templatePathAndFilename . '".', 1288087061);
            }
            $this->templateSource = file_get_contents($this->templatePathAndFilename);
        }
        return $this->templateSource;
    }

public Observable<ServiceResponse<Void>> publishVideoReviewWithServiceResponseAsync(String teamName, String reviewId) {
        if (this.client.baseUrl() == null) {
            throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
        }
        if (teamName == null) {
            throw new IllegalArgumentException("Parameter teamName is required and cannot be null.");
        }
        if (reviewId == null) {
            throw new IllegalArgumentException("Parameter reviewId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{baseUrl}", this.client.baseUrl());
        return service.publishVideoReview(teamName, reviewId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = publishVideoReviewDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: // Update updates a terminal location.

func Update(id string, params *stripe.TerminalLocationParams) (*stripe.TerminalLocation, error) {
	return getC().Update(id, params)
}

func (ini *INI) SetComments(section, key string, comments ...string) {
	sec := ini.getSection(section)

	if key == "" {
		if sec == nil {
			sec = ini.addSection(section)
		}
		sec.Comments = comments
		return
	}

	if item := sec.getItem(key, ini.isCaseSensitive); item != nil {
		item.Comments = comments
	}
}

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


Question:
@param string $content

@return Mock

private function mockStream($content)
    {
        $mockedStream = $this->mocker->mockCollaborator(StreamInterface::class);
        $mockedStream->shouldReceive('getContents')->once()->andReturn($content);
        $mockedStream->shouldReceive('close')->once()->andReturn();

        return $mockedStream;
    }

public function assertSatisfied()
    {
        foreach ($this->expectations as $expectation) {
            if (!$expectation->isSatisfied()) {
                $comment = $expectation->commentOn($expectation->getMethod(), []);

                if (!$comment) {
                    $comment = "Unsatisfied expectation for method " . $expectation->getMethod();
                }

                throw new UnsatisfiedExpectationException($comment);
            }
        }
    }

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


Question:
获取指定类型的对象实例
@param <T> 对象的类型
@param beanName 实现类在容器中配置的名字

@SuppressWarnings("unchecked")
	public static <T> T getInstance(String beanName) {
		return (T) getInstanceProvider().getInstance(beanName);
	}

public static MethodInstance getGetter(Class clazz, String prop) throws PageException, NoSuchMethodException {
	String getterName = "get" + StringUtil.ucFirst(prop);
	MethodInstance mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(getterName), ArrayUtil.OBJECT_EMPTY);

	if (mi == null) {
	    String isName = "is" + StringUtil.ucFirst(prop);
	    mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(isName), ArrayUtil.OBJECT_EMPTY);
	    if (mi != null) {
		Method m = mi.getMethod();
		Class rtn = m.getReturnType();
		if (rtn != Boolean.class && rtn != boolean.class) mi = null;
	    }
	}

	if (mi == null) throw new ExpressionException("No matching property [" + prop + "] found in [" + Caster.toTypeName(clazz) + "]");
	Method m = mi.getMethod();

	if (m.getReturnType() == void.class)
	    throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] for Property [" + getterName + "] must have return type not void");

	return mi;
    }

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


Question:
Determine if the feature table is indexed

@return true if indexed

public boolean isIndexed() {
		boolean indexed = false;
		Extensions extension = getExtension();
		if (extension != null) {

			ContentsDao contentsDao = geoPackage.getContentsDao();
			try {
				Contents contents = contentsDao.queryForId(tableName);
				if (contents != null) {
					Date lastChange = contents.getLastChange();

					TableIndexDao tableIndexDao = geoPackage.getTableIndexDao();
					TableIndex tableIndex = tableIndexDao.queryForId(tableName);

					if (tableIndex != null) {
						Date lastIndexed = tableIndex.getLastIndexed();
						indexed = lastIndexed != null
								&& lastIndexed.getTime() >= lastChange
										.getTime();
					}
				}
			} catch (SQLException e) {
				throw new GeoPackageException(
						"Failed to check if table is indexed, GeoPackage: "
								+ geoPackage.getName() + ", Table Name: "
								+ tableName, e);
			}
		}
		return indexed;
	}

public function ensureIndex(array $keys, array $options = array())
    {
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
        $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;

        return $this->riakCollection->ensureIndex($keys, $options);
    }

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


Question:
Save the model to the database.

Extends parent to allow automatic many-to-many relationship attachment.

@param array $options
@return bool

public function save(array $options = [])
    {
        return DB::transaction(function() use ($options) {
            $result = parent::save($options);

            foreach ($this->autofilledRelations as $relationship => $relations) {
                if (!empty($relations)) {
                    $this->$relationship()->sync((array)$this->prepForSync($relations));
                }
            }

            return $result;
        });
    }

public function handle()
    {
        $this->line('');
        $this->info('The migration process will create a migration file and a seeder for the states list');

        $this->line('');

        if ($this->confirm("Proceed with the migration creation? [Yes|no]")) {
            $this->line('');

            $this->info("Creating migration and seeder...");
            if ($this->createMigration('states')) {
                $this->line('');

                $this->call('optimize', []);

                $this->line('');

                $this->info("Migration successfully created!");
            } else {
                $this->error(
                    "Coudn't create migration.\n Check the write permissions".
                    " within the app/database/migrations directory."
                );
            }

            $this->line('');
        }
    }

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


Question: // _NET_WM_WINDOW_OPACITY set

func WmWindowOpacitySet(xu *xgbutil.XUtil, win xproto.Window,
	opacity float64) error {

	return xprop.ChangeProp32(xu, win, "_NET_WM_WINDOW_OPACITY", "CARDINAL",
		uint(opacity*0xffffffff))
}

func (c *Connection) getOutMessage() (x *buffer.OutMessage) {
	c.mu.Lock()
	x = (*buffer.OutMessage)(c.outMessages.Get())
	c.mu.Unlock()

	if x == nil {
		x = new(buffer.OutMessage)
	}
	x.Reset()

	return
}

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


Question:
Checks that a URI is safe to be an image source.

<p>Does not return SanitizedContent as there isn't an appropriate type for this.

public static String filterNormalizeMediaUri(String value) {
    if (EscapingConventions.FilterNormalizeMediaUri.INSTANCE
        .getValueFilter()
        .matcher(value)
        .find()) {
      return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.escape(value);
    }
    logger.log(Level.WARNING, "|filterNormalizeMediaUri received bad value ''{0}''", value);
    return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.getInnocuousOutput();
  }

func (trc *TumblrRestClient) Queue(blogname string, options map[string]string) DraftsResponse {
	requestUrl := fmt.Sprintf("/v2/blog/%s/posts/queue", blogname)
	data := trc.request.Get(requestUrl, options)
	var result DraftsResponse
	json.Unmarshal(data.Response, &result)
	return result
}

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


Question:
// Returns true if the array matches (must be json types).
// As is idiomatic for go, an empty array is not the same as a nil array.

func matchesArray(a, b []interface{}) bool {
	if len(a) != len(b) {
		return false
	}
	if (a == nil && b != nil) || (a != nil && b == nil) {
		return false
	}
	for i := range a {
		if !matchesValue(a[i], b[i]) {
			return false
		}
	}
	return true
}

function _collectURLs ( token ) {

        var elem, isArrayElem;

        if ( Array.isArray( token ) ) {

            for ( var i = 0; i < token.length; i++ ) {

                elem = token[ i ];
                isArrayElem = Array.isArray( elem );

                if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) {

                    urls.push( elem );

                } else if ( isArrayElem ) {

                    _collectURLs( elem );

                }

            }

        }

    }

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


Question:
Split the PDF document into pages

@param string|null $filepattern the output name in sprintf format or null for default 'pg_%04d.pdf'
@return bool whether the burst command was successful
@return bool whether the burst operation was successful

public function burst($filepattern = null)
    {
        $this->constrainSingleFile();
        $this->getCommand()->setOperation('burst');
        $this->_output = $filepattern===null ? 'pg_%04d.pdf' : $filepattern;
        return $this->execute();
    }

def parse_options(self, prog_name, arguments):
        """"""
        # Don't want to load configuration to just print the version,
        # so we handle --version manually here.
        if '--version' in arguments:
            self.exit_status(self.version, fh=sys.stdout)
        parser = self.create_parser(prog_name)
        options, args = parser.parse_args(arguments)
        return options, args

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


Question:
Render field value

@param FieldValueInterface $fieldValue

@return mixed

public function render(FieldValueInterface $fieldValue)
    {
        $value = $fieldValue->getValue();
        $value = unserialize($value);

        if (empty($value['src'])) {
            return '';
        }

        $fileName = $this->uploadManager->getTargetDir() . DIRECTORY_SEPARATOR . $value['src'];
        if (!file_exists($fileName)) {
            return '';
        }

        $fileName = $this->assetPackages->getUrl($this->uploadManager->getWebPath() . '/' . $value['src']);

        return '<img src="' . $fileName . '" alt="' . $value['alt'] . '"/>';
    }

public static EmailTextField newEmailTextField(final String id, final IModel<String> model)
	{
		final EmailTextField emailTextField = new EmailTextField(id, model);
		emailTextField.setOutputMarkupId(true);
		return emailTextField;
	}

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


Question: // Source returns a map that will be used to serialize the context query as JSON.

func (q *SuggesterCategoryMapping) Source() interface{} {
	source := make(map[string]interface{})

	x := make(map[string]interface{})
	source[q.name] = x

	x["type"] = "category"

	switch len(q.defaultValues) {
	case 0:
		x["default"] = q.defaultValues
	case 1:
		x["default"] = q.defaultValues[0]
	default:
		x["default"] = q.defaultValues
	}

	if q.fieldName != "" {
		x["path"] = q.fieldName
	}
	return source
}

def from_events(self, instance, ev_args, ctx):

        tag = ev_args[0], ev_args[1]
        cls = self._tag_map[tag]
        obj = yield from cls.parse_events(ev_args, ctx)
        mapping = self.__get__(instance, type(instance))
        mapping[self.key(obj)].append(obj)

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


Question:
Ouvre une connexion

@return boolean

public function connect()
  {
    try {
      $this->cnx = new \PDO($this->dns, $this->user, $this->pass);
      $this->cnx->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      return true;
    } catch (\Exception $e) {
      return false;
    }
  }

public static function connection($name = 'default')
    {
        $name = $name == 'default' ? self::$config['connection']['default'] : $name;

        return isset(self::$connection[$name])
            ? self::$connection[$name]
            : self::$connection[$name] = self::createForConnection($name);
    }

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


Question:
Checks if key exists and not null.

@param string|null $key

@return bool

public function has(?string $key = null) : bool
    {
        $key = $this->constructKey($key);

        return $this->parseKey($key, function ($part, $result) {
            return isset($result[$part]);
        });
    }

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

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


Question:
Prepares and formats a has-one embed for proper insertion into the database.

@param   EmbeddedPropMetadata    $embeddedPropMeta
@param   Embed|null              $embed
@return  mixed

public function getEmbedOneDbValue(EmbeddedPropMetadata $embeddedPropMeta, Embed $embed = null)
    {
        if (null === $embed) {
            return;
        }
        return $this->createEmbed($embeddedPropMeta, $embed);
    }

public function update_meta( $meta_key, $meta_value ) {
		$updated = update_metadata( $this->meta_type, $this->get_id(), $meta_key, $meta_value );

		if ( false !== $updated ) {
			$this->metadata[ $meta_key ] = $meta_value;

			if ( $attribute = $this->get_mapping_attribute( $meta_key ) ) {
				$this->set_attribute( $attribute, $meta_value );
			}

			return true;
		}

		return false;
	}

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


Question:
// killChild is used to forcefully kill the child, first using SIGTERM
// to allow for a graceful cleanup and then using SIGKILL for a hard
// termination.
// On Windows, the child is always hard terminated with a SIGKILL, even
// on the first attempt.

func (c *cmd) killChild(childErr chan error) error {
	// Get the child process
	child := c.child

	// If there is no child process (failed to start), we can quit early
	if child == nil {
		if c.verbose {
			c.UI.Info("No child process to kill")
		}
		return nil
	}

	// Attempt termination first
	if c.verbose {
		c.UI.Info(fmt.Sprintf("Terminating child pid %d", child.Pid))
	}
	if err := signalPid(child.Pid, syscall.SIGTERM); err != nil {
		return fmt.Errorf("Failed to terminate %d: %v", child.Pid, err)
	}

	// Wait for termination, or until a timeout
	select {
	case <-childErr:
		if c.verbose {
			c.UI.Info("Child terminated")
		}
		return nil
	case <-time.After(lockKillGracePeriod):
		if c.verbose {
			c.UI.Info(fmt.Sprintf("Child did not exit after grace period of %v",
				lockKillGracePeriod))
		}
	}

	// Send a final SIGKILL
	if c.verbose {
		c.UI.Info(fmt.Sprintf("Killing child pid %d", child.Pid))
	}
	if err := signalPid(child.Pid, syscall.SIGKILL); err != nil {
		return fmt.Errorf("Failed to kill %d: %v", child.Pid, err)
	}
	return nil
}

func FilterTLFEarlyExitError(ctx context.Context, err error, log logger.Logger, name tlf.CanonicalName) (
	exitEarly bool, retErr error) {
	switch err := errors.Cause(err).(type) {
	case nil:
		// No error.
		return false, nil

	case TlfDoesNotExist:
		log.CDebugf(ctx,
			"TLF %s does not exist, so pretending it's empty",
			name)
		return true, nil

	case tlfhandle.WriteAccessError, kbfsmd.ServerErrorWriteAccess,
		libkbfs.NonExistentTeamForHandleError:
		// No permission to create TLF, so pretend it's still
		// empty.
		//
		// In theory, we need to invalidate this once the TLF
		// is created, but in practice, the Linux kernel
		// doesn't cache readdir results, and probably not
		// OSXFUSE either.
		log.CDebugf(ctx,
			"No permission to write to %s, so pretending it's empty",
			name)
		return true, nil

	default:
		if strings.Contains(err.Error(), "need writer access") {
			// The service returns an untyped error when we try to
			// write a TLF ID into an implicit team sigchain without
			// writer permissions.
			log.CDebugf(ctx,
				"No permission to write to %s, so pretending it's empty",
				name)
			return true, nil
		}

		// Some other error.
		return false, err
	}
}

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


Question: Sets the graphhopper folder.

public GraphHopper setGraphHopperLocation(String ghLocation) {
        ensureNotLoaded();
        if (ghLocation == null)
            throw new IllegalArgumentException("graphhopper location cannot be null");

        this.ghLocation = ghLocation;
        return this;
    }

public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/config/config.php', 'requester');

        $this->app['requester'] = $this->app->share(function ($app) {
            return new Requester(new GuzzleClient(), config('requester'));
        });
    }

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


Question:
Access the sync_map_permissions

        :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList
        :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionList

def sync_map_permissions(self):

        if self._sync_map_permissions is None:
            self._sync_map_permissions = SyncMapPermissionList(
                self._version,
                service_sid=self._solution['service_sid'],
                map_sid=self._solution['sid'],
            )
        return self._sync_map_permissions

public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dynamoDBAction.getTableName(), TABLENAME_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getOperation(), OPERATION_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyField(), HASHKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyValue(), HASHKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyType(), HASHKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyField(), RANGEKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyValue(), RANGEKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyType(), RANGEKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getPayloadField(), PAYLOADFIELD_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Return age string for given date.

@param string      $date1
@param string|null $date2

@return string

public function age($date1, $date2 = null)
    {
        $formatter = new AgeFormatter();

        return $formatter->formatDate($date1, $date2);
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question:
Generate a Nonce string
@param type $length
@return String

public static function getNonce($length = 16)
    {

        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

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


Question: // NewServer returns a Server object to manage the exported file system

func NewServer(driver StorageDriver, host *host.Host, volumesPath string) (*Server, error) {
	if len(driver.ExportPath()) < 9 {
		return nil, fmt.Errorf("export path can not be empty")
	}

	s := &Server{
		host:   host,
		driver: driver,
	}

	return s, nil
}

protected function createFile($directoryPath, $content, Node $node, Deployment $deployment, array $options)
    {
        $commands = [
            'mkdir -p '.escapeshellarg($directoryPath),
            'cd '.escapeshellarg($directoryPath),
            'echo '.escapeshellarg(implode(' | ', $content)).' > '.escapeshellarg($this->getFileName($options)),
        ];
        $this->shell->executeOrSimulate($commands, $node, $deployment);
    }

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


Question:
Generate an instance context for the instance, the context is capable of
performing various actions.  All instance actions are proxied to the context

@return \Twilio\Rest\Serverless\V1\Service\FunctionContext Context for this
FunctionInstance

protected function proxy() {
        if (!$this->context) {
            $this->context = new FunctionContext(
                $this->version,
                $this->solution['serviceSid'],
                $this->solution['sid']
            );
        }

        return $this->context;
    }

def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False):
        """"""
        if len(tokens) == 1:
            decorators, funcdef = "", tokens[0]
        elif len(tokens) == 2:
            decorators, funcdef = tokens
        else:
            raise CoconutInternalException("invalid function definition tokens", tokens)

        # extract information about the function
        raw_lines = funcdef.splitlines(True)
        def_stmt = raw_lines.pop(0)
        func_name, func_args, func_params = None, None, None
        with self.complain_on_err():
            func_name, func_args, func_params = parse(self.split_func_name_args_params, def_stmt)

        undotted_name = None  # the function __name__ if func_name is a dotted name
        if func_name is not None:
            if "." in func_name:
                undotted_name = func_name.rsplit(".", 1)[-1]
                def_stmt = def_stmt.replace(func_name, undotted_name)

        # handle async functions
        if is_async:
            if not self.target:
                raise self.make_err(
                    CoconutTargetError,
                    "async function definition requires a specific target",
                    original, loc,
                    target="sys",
                )
            elif self.target_info >= (3, 5):
                def_stmt = "async " + def_stmt
            else:
                decorators += "@_coconut.asyncio.coroutine\n"

            # only Python 3.3+ supports returning values inside generators
            if self.target_info < (3, 3):
                func_code = self.transform_returns(raw_lines, is_async=True)
            else:
                func_code = "".join(raw_lines)

        # handle normal functions
        else:
            # tre does not work with decorators, though tco does
            attempt_tre = func_name is not None and not decorators
            if attempt_tre:
                use_mock = func_args and func_args != func_params[1:-1]
                func_store = tre_store_var + "_" + str(self.tre_store_count)
                self.tre_store_count += 1
                tre_return_grammar = self.tre_return(func_name, func_args, func_store, use_mock)
            else:
                use_mock = func_store = tre_return_grammar = None

            func_code, tco, tre = self.transform_returns(
                raw_lines,
                tre_return_grammar,
                use_mock,
            )

            if tre:
                comment, rest = split_leading_comment(func_code)
                indent, base, dedent = split_leading_trailing_indent(rest, 1)
                base, base_dedent = split_trailing_indent(base)
                docstring, base = self.split_docstring(base)
                func_code = (
                    comment + indent
                    + (docstring + "\n" if docstring is not None else "")
                    + (
                        "def " + tre_mock_var + func_params + ": return " + func_args + "\n"
                        if use_mock else ""
                    ) + "while True:\n"
                        + openindent + base + base_dedent
                        + ("\n" if "\n" not in base_dedent else "") + "return None"
                        + ("\n" if "\n" not in dedent else "") + closeindent + dedent
                    + func_store + " = " + (func_name if undotted_name is None else undotted_name) + "\n"
                )
            if tco:
                decorators += "@_coconut_tco\n"  # binds most tightly

        out = decorators + def_stmt + func_code
        if undotted_name is not None:
            out += func_name + " = " + undotted_name + "\n"
        return out

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


Question: // Custom marshaller to add the resourceType property, as required by the specification

func (resource *ConceptMap) MarshalJSON() ([]byte, error) {
	resource.ResourceType = "ConceptMap"
	// Dereferencing the pointer to avoid infinite recursion.
	// Passing in plain old x (a pointer to ConceptMap), would cause this same
	// MarshallJSON function to be called again
	return json.Marshal(*resource)
}

public static <T> T unmarshal(Class<T> cl, Reader r) throws JAXBException {
    return unmarshal(cl, new StreamSource(r));
  }

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


Question:
/*
Closes other containers except one related to passed element.
Other containers can be cancelled or submitted (depends on onblur option)

function(element) {
            $('.editable-open').each(function(i, el){
                //do nothing with passed element and it's children
                if(el === element || $(el).find(element).length) {
                    return;
                }

                //otherwise cancel or submit all open containers
                var $el = $(el),
                ec = $el.data('editableContainer');

                if(!ec) {
                    return;
                }

                if(ec.options.onblur === 'cancel') {
                    $el.data('editableContainer').hide('onblur');
                } else if(ec.options.onblur === 'submit') {
                    $el.data('editableContainer').tip().find('form').submit();
                }
            });

        }

def find_write_predecessors(self, address):

        # A write operation must be preceded by:
        #   - The "enclosing writer", which is the writer at the address or
        #     the nearest writer higher (closer to the root) in the tree.
        #   - The "enclosing readers", which are the readers at the address
        #     or higher in the tree.
        #   - The "children writers", which include all writers which are
        #     lower in the tree than the address.
        #   - The "children readers", which include all readers which are
        #     lower in the tree than the address.
        #
        # The enclosing writer must be added as it may have modified a node
        # which must not happen after the current write.
        #
        # Writers which are higher in the tree than the enclosing writer may
        # have modified a node at or under the given address.  However, we do
        # not need to include them here as they will have been considered a
        # predecessor to the enclosing writer.
        #
        # Enclosing readers must be included.  Technically, we only need to add
        # enclosing readers which occurred after the enclosing writer, since
        # the readers preceding the writer will have been considered a
        # predecessor of the enclosing writer.  However, with the current
        # data structure we can not determine the difference between readers
        # so we specify them all; this is mostly harmless as it will not change
        # the eventual sort order generated by the scheduler.
        #
        # Children readers must be added, since their reads must happen prior
        # to the write.

        predecessors = set()

        enclosing_writer = None

        node_stream = self._tree.walk(address)

        address_len = len(address)

        # First, walk down from the root to the address, collecting all readers
        # and updating the enclosing_writer if needed.

        try:
            for node_address, node in node_stream:
                if node is not None:
                    predecessors.update(node.readers)

                    if node.writer is not None:
                        enclosing_writer = node.writer

                    if len(node_address) >= address_len:
                        break

        # If the address isn't on the tree, then there aren't any
        # predecessors below the node to worry about (because there
        # isn't anything at all), so return the predecessors that have
        # already been collected.
        except AddressNotInTree as err:
            if err.match is not None:
                return self.find_write_predecessors(err.match)

            return predecessors

        finally:
            if enclosing_writer is not None:
                predecessors.add(enclosing_writer)

        # Next, descend down the tree starting at the address node and
        # find all descendant readers and writers.

        for _, node in node_stream:
            if node is not None:
                if node.writer is not None:
                    predecessors.add(node.writer)

                predecessors.update(node.readers)

        return predecessors

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


Question:
Returns description of method parameters

@return external_function_parameters
@since 3.1

public static function delete_message_parameters() {
        return new external_function_parameters(
            array(
                'messageid' => new external_value(PARAM_INT, 'The message id'),
                'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
                'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
            )
        );
    }

func (ps *peerState) forAllOutboundPeers(closure func(sp *ServerPeer)) {
	for _, e := range ps.outboundPeers {
		closure(e)
	}
	for _, e := range ps.persistentPeers {
		closure(e)
	}
}

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


Question:
Locates all available non-core primitives of the Rapid language.
@return list of Rapid primitives

synchronized List<AstPrimitive> getAllPrims() {
    List<AstPrimitive> prims = new ArrayList<>();
    for (AstPrimitive prim : _loader) {
      prims.add(prim);
    }
    return prims;
  }

def render_source(output_dir, package_spec):

    path, name = package_spec.filepath
    destination_filename = '%s/%s.proto' % (output_dir, name)
    pb_template = JENV.get_template(MESSAGES_TEMPLATE_NAME)
    includes = [include[:-5] if include.endswith('.yaml') else include for include in package_spec.includes]
    if 'types' in includes:
        includes.remove('types')
    with open(destination_filename, 'w') as f:
        f.write(pb_template.render(
            name=name,
            package=package_spec.identifier,
            messages=package_spec.definitions,
            includes=includes,
            description=package_spec.description,
        ))

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


Question:
// AddScriptToEvaluateOnNewDocument invokes the Page method. Evaluates given
// script in every frame upon creation (before loading frame's scripts).

func (d *domainClient) AddScriptToEvaluateOnNewDocument(ctx context.Context, args *AddScriptToEvaluateOnNewDocumentArgs) (reply *AddScriptToEvaluateOnNewDocumentReply, err error) {
	reply = new(AddScriptToEvaluateOnNewDocumentReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Page.addScriptToEvaluateOnNewDocument", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Page.addScriptToEvaluateOnNewDocument", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Page", Op: "AddScriptToEvaluateOnNewDocument", Err: err}
	}
	return
}

func (e *EvalError) Stack() []*Frame {
	var stack []*Frame
	for fr := e.Frame; fr != nil; fr = fr.parent {
		stack = append(stack, fr)
	}
	return stack
}

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


Question: // SetMaximum sets the Maximum field's value.

func (s *Datapoint) SetMaximum(v float64) *Datapoint {
	s.Maximum = &v
	return s
}

public static Calendar ceiling(Calendar calendar, DateField dateField) {
		return DateModifier.modify(calendar, dateField.getValue(), ModifyType.CEILING);
	}

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