Question: // SetGatewayARN sets the GatewayARN field's value.

func (s *DescribeVTLDevicesOutput) SetGatewayARN(v string) *DescribeVTLDevicesOutput {
	s.GatewayARN = &v
	return s
}

@Override
    public Request<ReplaceNetworkAclAssociationRequest> getDryRunRequest() {
        Request<ReplaceNetworkAclAssociationRequest> request = new ReplaceNetworkAclAssociationRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

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


Question:
This method returns all of the space properties EXCEPT the ACLs

@param spaceId - ID of the space
@return map of space properties

public Map<String, String> getSpaceProperties(String spaceId) {
        Map<String, String> spaceProps = new HashMap<String, String>();
        Map<String, String> allProps = getAllSpaceProperties(spaceId);

        // ONLY include non-ACL properties.
        for (String name : allProps.keySet()) {
            if (!name.startsWith(PROPERTIES_SPACE_ACL)) {
                spaceProps.put(name, allProps.get(name));
            }
        }

        return spaceProps;
    }

func authorizedForSCC(sccName string, info user.Info, namespace string, a authorizer.Authorizer) bool {
	// check against the namespace that the pod is being created in to allow per-namespace SCC grants.
	attr := authorizer.AttributesRecord{
		User:            info,
		Verb:            "use",
		Namespace:       namespace,
		Name:            sccName,
		APIGroup:        security.GroupName,
		Resource:        "securitycontextconstraints",
		ResourceRequest: true,
	}
	decision, reason, err := a.Authorize(attr)
	if err != nil {
		klog.V(5).Infof("cannot authorize for SCC: %v %q %v", decision, reason, err)
		return false
	}
	return decision == authorizer.DecisionAllow
}

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


Question:
Converts SQLHEX to plain text

@param string $value the value to convert

@static
@return string

public static function convertFromSQLHex($value)
    {
        $matches = array();
        if (preg_match_all('/(?:(?:\A|[^\d])0x[a-f\d]{3,}[a-f\d]*)+/im', $value, $matches)) {
            foreach ($matches[0] as $match) {
                $converted = '';
                foreach (str_split($match, 2) as $hex_index) {
                    if (preg_match('/[a-f\d]{2,3}/i', $hex_index)) {
                        $converted .= chr(hexdec($hex_index));
                    }
                }
                $value = str_replace($match, $converted, $value);
            }
        }
        // take care of hex encoded ctrl chars
        $value = preg_replace('/0x\d+/m', ' 1 ', $value);

        return $value;
    }

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

        return;
    }

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


Question: Fails if the element does not have the given count.

public final void hasCount(@NullableDecl Object element, int expectedCount) {
    checkArgument(expectedCount >= 0, "expectedCount(%s) must be >= 0", expectedCount);
    int actualCount = ((Multiset<?>) actual()).count(element);
    check("count(%s)", element).that(actualCount).isEqualTo(expectedCount);
  }

function verify(node) {
	switch (node.type) {
		case esprima.Syntax.FunctionDeclaration:
			if (node.leadingComments && node.leadingComments.length === 1) {
				analyzeFunction(node);
			}
			break;
		default:
			break;
	}
}

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


Question: Load observing mode OB tagger

def load_mode_tagger(obs_mode, node):
    """"""

    # handle tagger:
    ntagger = node.get('tagger')

    if ntagger is None:
        pass
    elif isinstance(ntagger, list):

        def full_tagger(obsres):
            return get_tags_from_full_ob(obsres, reqtags=ntagger)

        obs_mode.tagger = full_tagger
    elif isinstance(ntagger, six.string_types):
        # load function
        obs_mode.tagger = import_object(ntagger)
    else:
        raise TypeError('tagger must be None, a list or a string')

    return obs_mode

public void write_port(final String node, final int id, final int creation) {
	write1(OtpExternal.portTag);
	write_atom(node);
	write4BE(id & 0xfffffff); // 28 bits
	write1(creation & 0x3); // 2 bits
    }

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


Question:
Sets the support_level of this ProductReleaseRest.

        :param support_level: The support_level of this ProductReleaseRest.
        :type: str

def support_level(self, support_level):

        allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
        if support_level not in allowed_values:
            raise ValueError(
                "Invalid value for `support_level` ({0}), must be one of {1}"
                .format(support_level, allowed_values)
            )

        self._support_level = support_level

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question:
Creates the html representation of the website. The website is saved to
 the directory with websites title and needs an erb-template where the
 links are integrated to. An example template can be found at
 templates/syclink.html.erb

def create_website(directory, template_filename)
      template = File.read(template_filename)
      File.open(html_file(directory, website.title), 'w') do |f|
        f.puts website.to_html(template)
      end
    end

def hide_routemap_holder_route_map_content_set_metric_delta_rms(self, **kwargs):

        config = ET.Element("config")
        hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
        route_map = ET.SubElement(hide_routemap_holder, "route-map")
        name_key = ET.SubElement(route_map, "name")
        name_key.text = kwargs.pop('name')
        action_rm_key = ET.SubElement(route_map, "action-rm")
        action_rm_key.text = kwargs.pop('action_rm')
        instance_key = ET.SubElement(route_map, "instance")
        instance_key.text = kwargs.pop('instance')
        content = ET.SubElement(route_map, "content")
        set = ET.SubElement(content, "set")
        metric = ET.SubElement(set, "metric")
        delta_rms = ET.SubElement(metric, "delta-rms")
        delta_rms.text = kwargs.pop('delta_rms')

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

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


Question:
透传消息
@param context
@param miPushMessage

@Override
  public void onReceivePassThroughMessage(Context context, com.xiaomi.mipush.sdk.MiPushMessage miPushMessage) {
    processMiPushMessage(miPushMessage);
  }

public function sendDirectMessage(string $username, string $message): stdClass
	{
		return $this->request(
			'direct_messages/events/new',
			'JSONPOST',
			['event' => [
				'type' => 'message_create',
				'message_create' => [
					'target' => ['recipient_id' => $this->loadUserInfo($username)->id_str],
					'message_data' => ['text' => $message],
				],
			]]
		);
	}

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


Question:
Build an augmented triad on note.

    Example:
    >>> augmented_triad('C')
    ['C', 'E', 'G#']

def augmented_triad(note):

    return [note, intervals.major_third(note),
            notes.augment(intervals.major_fifth(note))]

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
// GetBalanceAsync returns an instance of a type that can be used to get the
// result of the RPC at some future time by invoking the Receive function on the
// returned instance.
//
// See GetBalance for the blocking version and more details.

func (c *Client) GetBalanceAsync(account string) FutureGetBalanceResult {
	cmd := btcjson.NewGetBalanceCmd(&account, nil)
	return c.sendCmd(cmd)
}

def update(self, lb, name=None, algorithm=None, protocol=None,
            halfClosed=None, port=None, timeout=None, httpsRedirect=None):

        body = {}
        if name is not None:
            body["name"] = name
        if algorithm is not None:
            body["algorithm"] = algorithm
        if protocol is not None:
            body["protocol"] = protocol
        if halfClosed is not None:
            body["halfClosed"] = halfClosed
        if port is not None:
            body["port"] = port
        if timeout is not None:
            body["timeout"] = timeout
        if httpsRedirect is not None:
            body["httpsRedirect"] = httpsRedirect
        if not body:
            # Nothing passed
            return
        body = {"loadBalancer": body}
        uri = "/loadbalancers/%s" % utils.get_id(lb)
        try:
            resp, resp_body = self.api.method_put(uri, body=body)
        except exc.ClientException as e:
            message = e.message
            details = e.details
            if message and details:
                errmsg = "%s - %s" % (message, details)
            else:
                errmsg = message
            raise exc.InvalidLoadBalancerParameters(errmsg)
        return resp, resp_body

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


Question:
Generate a dictionary of fields for a given Peewee model.

    See `model_form` docstring for description of parameters.

def model_fields(model, allow_pk=False, only=None, exclude=None,
                 field_args=None, converter=None):

    converter = converter or ModelConverter()
    field_args = field_args or {}

    model_fields = list(model._meta.sorted_fields)
    if not allow_pk:
        model_fields.pop(0)

    if only:
        model_fields = [x for x in model_fields if x.name in only]
    elif exclude:
        model_fields = [x for x in model_fields if x.name not in exclude]

    field_dict = {}
    for model_field in model_fields:
        name, field = converter.convert(
            model,
            model_field,
            field_args.get(model_field.name))
        field_dict[name] = field

    return field_dict

def _ParseEntry(self, key, val):

    if key in self._repeated:
      setting = self.section.setdefault(key, [])
      setting.extend(val)
    else:
      self.section.setdefault(key, val)

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


Question:
Handles GET action

@return array
@throws \DreamFactory\Core\Exceptions\NotFoundException

protected function handleGET()
    {
        if (!empty($this->resource)) {
            /** @type ScriptEngineTypeInterface $type */
            if (null === $type = ScriptEngineManager::getScriptEngineType($this->resource)) {
                throw new NotFoundException("Script engine type '{$this->resource}' not found.");
            }

            return $type->toArray();
        }

        $resources = [];
        $types = ScriptEngineManager::getScriptEngineTypes();
        /** @type ScriptEngineTypeInterface $type */
        foreach ($types as $type) {
            $resources[] = $type->toArray();
        }

        return ResourcesWrapper::wrapResources($resources);
    }

func (api *CloudSpecAPI) CloudSpec() (environs.CloudSpec, error) {
	var results params.CloudSpecResults
	args := params.Entities{Entities: []params.Entity{{api.modelTag.String()}}}
	err := api.facade.FacadeCall("CloudSpec", args, &results)
	if err != nil {
		return environs.CloudSpec{}, err
	}
	if n := len(results.Results); n != 1 {
		return environs.CloudSpec{}, errors.Errorf("expected 1 result, got %d", n)
	}
	result := results.Results[0]
	if result.Error != nil {
		return environs.CloudSpec{}, errors.Annotate(result.Error, "API request failed")
	}
	return api.MakeCloudSpec(result.Result)
}

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


Question:
returns a array of form errors

@return      array

public function getErrors()
    {
        $errors = array();

        $entityContainers = $this->getEntityContainerMap()->getAll();

        /**
         * @var EntityContainerInterface $entityContainer
         */
        foreach ($entityContainers as $entityContainer) {
            if ($entityContainer->hasErrors()) {
                $errors[$entityContainer->getName()] = $entityContainer->getErrors();
            }
        }

        return $errors;
    }

private function addTranslatableError(string $messageKey, string $defaultMessage) : void
    {
        $message = $defaultMessage;

        if (null !== $translator = $this->form->getTranslator()) {
            $translatedMessage = $translator($messageKey);
            if ($translatedMessage !== null) {
                $message = $translatedMessage;
            }
        }

        $this->addError($message);
    }

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


Question: // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (in *PodSecurityPolicySelfSubjectReviewSpec) DeepCopyInto(out *PodSecurityPolicySelfSubjectReviewSpec) {
	*out = *in
	in.Template.DeepCopyInto(&out.Template)
	return
}

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

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


Question: This command minified js files with UglifyJS

def minify_js_files():

    for k, v in JS_FILE_MAPPING.items():
        input_files = " ".join(v["input_files"])
        output_file = v["output_file"]

        uglifyjs_command = "uglifyjs {input_files} -o {output_file}".format(
            input_files=input_files,
            output_file=output_file
        )
        local(uglifyjs_command)

function run(cmd){

        var proc = require('child_process'),
            done = grunt.task.current.async(); // Tells Grunt that an async task is complete

        proc.exec(cmd,
            function(error, stdout, stderr){
                if(stderr){
                    grunt.log.writeln('ERROR: ' + stderr).error();
                }
                grunt.log.writeln(stdout);
                done(error);
            }
        );
    }

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


Question: Execute the command against the namespace.

def program_rtr(self, args, rout_id, namespace=None):

        if namespace is None:
            namespace = self.find_rtr_namespace(rout_id)
        if namespace is None:
            LOG.error("Unable to find namespace for router %s", rout_id)
            return False
        final_args = ['ip', 'netns', 'exec', namespace] + args
        try:
            utils.execute(final_args, root_helper=self.root_helper)
        except Exception as e:
            LOG.error("Unable to execute %(cmd)s. "
                      "Exception: %(exception)s",
                      {'cmd': final_args, 'exception': e})
            return False
        return True

public static function sequence(...$items){
        $cmd = [];
        foreach ($items as $item) {
            $cmd[] = ($item instanceof static)?$item->getShellCommand():$item;
        }
        return new static(implode(' && ',$cmd));
    }

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


Question: // Param replaces a path param based on the given param name and value.

func (r *Request) Param(name, value string) *Request {
	r.Use(url.Param(name, value))
	return r
}

def allpathsX(args):

    p = OptionParser(allpathsX.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    folder, tag = args
    tag = tag.split(",")
    for p, pf in iter_project(folder):
        assemble_pairs(p, pf, tag)

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


Question:
Determine if 'map' has empty sources
@param {Object} map
@returns {Boolean}

function emptySources(map) {
  return !map.sources ||
    !map.sources.length ||
    !map.sourcesContent ||
    !map.sourcesContent.length ||
    map.sources.length != map.sourcesContent.length;
}

public static <T extends Collection<?>> T checkNonEmpty(T collection, String name) {
        checkNotNull(collection, name);
        checkPositive(collection.size(), name + ".size");
        return collection;
    }

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


Question: Evaluates one cell and returns its result

def _eval_cell(self, key, code):
        """"""

        # Flatten helper function
        def nn(val):
            """Returns flat numpy arraz without None values"""
            try:
                return numpy.array(filter(None, val.flat))

            except AttributeError:
                # Probably no numpy array
                return numpy.array(filter(None, val))

        # Set up environment for evaluation

        env_dict = {'X': key[0], 'Y': key[1], 'Z': key[2], 'bz2': bz2,
                    'base64': base64, 'charts': charts, 'nn': nn,
                    'R': key[0], 'C': key[1], 'T': key[2], 'S': self,
                    'vlcpanel_factory': vlcpanel_factory}
        env = self._get_updated_environment(env_dict=env_dict)

        #_old_code = self(key)

        # Return cell value if in safe mode

        if self.safe_mode:
            return code

        # If cell is not present return None

        if code is None:
            return

        elif is_generator_like(code):
            # We have a generator object

            return numpy.array(self._make_nested_list(code), dtype="O")

        # If only 1 term in front of the "=" --> global

        try:
            assignment_target_error = None
            module = ast.parse(code)
            assignment_target_end = self._get_assignment_target_end(module)

        except ValueError, err:
            assignment_target_error = ValueError(err)

        except AttributeError, err:
            # Attribute Error includes RunTimeError
            assignment_target_error = AttributeError(err)

        except Exception, err:
            assignment_target_error = Exception(err)

        if assignment_target_error is None and assignment_target_end != -1:
            glob_var = code[:assignment_target_end]
            expression = code.split("=", 1)[1]
            expression = expression.strip()

            # Delete result cache because assignment changes results
            self.result_cache.clear()

        else:
            glob_var = None
            expression = code

        if assignment_target_error is not None:
            result = assignment_target_error

        else:

            try:
                import signal

                signal.signal(signal.SIGALRM, self.handler)
                signal.alarm(config["timeout"])

            except:
                # No POSIX system
                pass

            try:
                result = eval(expression, env, {})

            except AttributeError, err:
                # Attribute Error includes RunTimeError
                result = AttributeError(err)

            except RuntimeError, err:
                result = RuntimeError(err)

            except Exception, err:
                result = Exception(err)

            finally:
                try:
                    signal.alarm(0)
                except:
                    # No POSIX system
                    pass

        # Change back cell value for evaluation from other cells
        #self.dict_grid[key] = _old_code

        if glob_var is not None:
            globals().update({glob_var: result})

        return result

function focusToCell(sq, range, targetCell) {
  range.selectNodeContents(targetCell);
  range.collapse(true);
  sq.setSelection(range);
}

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


Question:
Run the repository log command

        Returns:
            str: output of log command (``hg log -l <n> <--kwarg=value>``)

def log(self, n=None, **kwargs):

        cmd = ['hg', 'log']
        if n:
            cmd.extend('-l%d' % n)
        cmd.extend(
            (('--%s=%s' % (k, v)) for (k, v)
                in iteritems(kwargs))
        )
        return self.sh(cmd, shell=False)

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


Question:
Parses strong element: ** ... **
@marker **

protected function parseStrong($text)
	{
		$pattern =<<< REGEXP
/^\*\*(
  (.*?{{{.*?}}}.*?)+?|  # including inline code span
  (?!.*{{{.*?}}}).*?    # without inline code span
)\*\*/sx
REGEXP;
		if (preg_match($pattern, $text, $matches)) {
			return [
				[
					'strong',
					$this->parseInline($matches[1])
				],
				strlen($matches[0])
			];
		} else {
			// no ending ** ... should be treated as strong
			return [
				[
					'strong',
					$this->parseInline(substr($text,2))
				],
				strlen($text)
			];
		}
	}

def new_select
      quant_list = [ :ALL, :DISTINCT ]
      select_list = [ :ASTERISK, :STRING ]

      select_tok = Tree::Select.new(basic_options)

      # handle an optional set quantifier (ALL or DISTINCT)
      if quant_list.include? peek_token.token
        select_tok.set_quantifier = read_token.token
      end

      # handle a select list (ASTERISK or search terms)
      if select_list.include? peek_token.token

        # read in all search terms from the query:
        while peek_token.token == :STRING
          select_tok.add_search_term(read_token.lexeme)
          read_token if peek_token.token == :COMMA
        end

      else
        raise SyntaxError "No valid select list given (#{error_location})"
      end

      select_tok
    end

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


Question:
(non-PHPdoc)

Mostly copy/pasted code from views_handler_argument_formula.

@see views_handler_argument_formula::query()

public function query($group_by = false)
    {
        $this->ensure_my_table();

        $date = null;

        if (is_numeric($this->argument) && (@$date = new DateTime('@' . $this->argument))) {
          // Ok got it.
            time();
        } else if (10 === strlen($this->argument) && (@$date = DateTime::createFromFormat('Y-m-d', $this->argument))) {
            // Ok got it.
            time();
        } else {
            // Nope.
        }

        $bounds = Udate_ViewsDateHelper::getBounds($date, $this->options['granularity']);

        if (null !== $date && $bounds) {

            $table = $this->table_alias;
            $field = $this->real_field;

            // @see calendar_plugin_style::render()
            if (class_exists('DateObject')) {
                $bounds[0] = new DateObject($bounds[0]->format(DateTime::ISO8601));
                $bounds[1] = new DateObject($bounds[1]->format(DateTime::ISO8601));
            }
            $this->date_range = $bounds;
            $this->min_date   = $bounds[0];
            $this->max_date   = $bounds[1];
            $this->limit      = array($date->format('Y') - 3, $date->format('Y') + 3);
            $this->query->add_field($table, $field, 'calendar_start_date');
            $this->query->add_field($table, $field);

            switch ($this->options['granularity']) {

              case UDATE_GRANULARITY_SECOND:
                  $this->query->add_where_expression(
                      0,
                      $table . "." . $field
                          . " = '" . $date->format(UDATE_PHP_DATETIME) . "'"
                  );
                  break;

              default:
                  $this->query->add_where_expression(
                      0,
                      $table . "." . $field
                          . " BETWEEN '" . $bounds[0]->format(UDATE_PHP_DATETIME)
                          . "' AND '" . $bounds[1]->format(UDATE_PHP_DATETIME) . "'"
                  );
                  break;
            }
        }
    }

protected function _callQuery($query)
    {
        $query->contain($this->type['contain']);
        $extQuery = $this->type['query'];
        return $extQuery($query);
    }

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


Question:
updated_current_fields

        :param update_fields: dict with values for
                              updating fields_to_add

def updated_current_fields(
            self,
            update_fields):

        self.fields_to_add = {}
        for k in self.org_fields:
            self.fields_to_add[k] = self.org_fields[k]
        self.fields_to_add.update(update_fields)

def set_metadata(self, layer_id, version_id, fp):

        base_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
        self._metadata.set(base_url, fp)

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *ImportKeyPairInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ImportKeyPairInput"}
	if s.KeyPairName == nil {
		invalidParams.Add(request.NewErrParamRequired("KeyPairName"))
	}
	if s.PublicKeyBase64 == nil {
		invalidParams.Add(request.NewErrParamRequired("PublicKeyBase64"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
Analyzes a method body, tracking the set of held locks and checking accesses to guarded
members.

public static void analyze(
      VisitorState state, LockEventListener listener, Predicate<Tree> isSuppressed) {
    HeldLockSet locks = HeldLockSet.empty();
    locks = handleMonitorGuards(state, locks);
    new LockScanner(state, listener, isSuppressed).scan(state.getPath(), locks);
  }

func (g *Graph) getVertex_rlocked(vertexType vertexType, namespace, name string) (*namedVertex, bool) {
	vertex, exists := g.vertices[vertexType][namespace][name]
	return vertex, exists
}

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


Question: // SubscribeDeviceUplink subscribes to all uplink messages for the given application and device

func (s *DefaultSubscriber) SubscribeDeviceUplink(appID, devID string, handler UplinkHandler) error {
	key := DeviceKey{appID, devID, DeviceUplink, ""}
	messages, err := s.subscribe(key.String())
	if err != nil {
		return err
	}

	go s.handleUplink(messages, handler)
	return nil
}

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

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

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


Question:
Get value of evercookie by key
 == Examples:
   evercookie_get_value(:key)

def evercookie_get_value(key)
      if session[Evercookie.hash_name_for_saved].present?
        session[Evercookie.hash_name_for_saved][key]
      else
        nil
      end
    end

def get_dict(self, domain=None, path=None):
        """"""
        dictionary = {}
        for cookie in iter(self):
            if (domain is None or cookie.domain == domain) and (path is None
                                                or cookie.path == path):
                dictionary[cookie.name] = cookie.value
        return dictionary

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


Question:
Execute all steps for current instance
- Clean history
- Add log
- Save current instance state

public function execute()
    {
        $this->cleanHistory();
        $this->log();
        $this->instanceManager->update($this->instance);
    }

private Map<String, PipelineCommit> getCommitsAfterStage(PipelineStage stage, Pipeline pipeline, Dashboard dashboard,List<PipelineStage> pipelineStageList,Map<String,String> orderMap){
        Map<String, PipelineCommit> unionOfAllSets = new HashMap<>();
        // get key(ordinal) for stage name
        List<String> list = getKeysByValue(orderMap,stage.getName());
        int ordinal = Integer.parseInt(list.get(0));
        for (int systemStageOrdinal = ordinal+1; systemStageOrdinal < pipelineStageList.size(); ++systemStageOrdinal) {
            PipelineStage systemStage = null;
            for (Map.Entry<String, String> entry : orderMap.entrySet()) {
                String stageOrder = entry.getKey();
                String stageName = entry.getValue();
                if(Integer.parseInt(stageOrder) == systemStageOrdinal){
                    for(PipelineStage currentStage : pipelineStageList){
                        if(stageName.equalsIgnoreCase(currentStage.getName())){
                             systemStage = currentStage;
                        }
                    }
                }
            }
            Map<String, PipelineCommit> commits = findCommitsForStage(dashboard, pipeline, systemStage);
            unionOfAllSets.putAll(commits);
        }
        return unionOfAllSets;
    }

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


private static<T extends ParamValidator> void addValidators (ConcurrentHashMap<Class, List<ParamValidator>> map, Class<T> clazz,
                                                                 T requiredValidator, T noneRequiredValidator) {

        // use <CopyOnWriteArrayList> in case validators are added while initializing parameters through <getValidator> method.
        List validators = new CopyOnWriteArrayList(new ParamValidator[]{requiredValidator, noneRequiredValidator});
        map.put(clazz, validators);
    }

function paragraph(eat, value, silent) {
  var self = this
  var settings = self.options
  var commonmark = settings.commonmark
  var gfm = settings.gfm
  var tokenizers = self.blockTokenizers
  var interruptors = self.interruptParagraph
  var index = value.indexOf(lineFeed)
  var length = value.length
  var position
  var subvalue
  var character
  var size
  var now

  while (index < length) {
    // Eat everything if there’s no following newline.
    if (index === -1) {
      index = length
      break
    }

    // Stop if the next character is NEWLINE.
    if (value.charAt(index + 1) === lineFeed) {
      break
    }

    // In commonmark-mode, following indented lines are part of the paragraph.
    if (commonmark) {
      size = 0
      position = index + 1

      while (position < length) {
        character = value.charAt(position)

        if (character === tab) {
          size = tabSize
          break
        } else if (character === space) {
          size++
        } else {
          break
        }

        position++
      }

      if (size >= tabSize && character !== lineFeed) {
        index = value.indexOf(lineFeed, index + 1)
        continue
      }
    }

    subvalue = value.slice(index + 1)

    // Check if the following code contains a possible block.
    if (interrupt(interruptors, tokenizers, self, [eat, subvalue, true])) {
      break
    }

    // Break if the following line starts a list, when already in a list, or
    // when in commonmark, or when in gfm mode and the bullet is *not* numeric.
    if (
      tokenizers.list.call(self, eat, subvalue, true) &&
      (self.inList ||
        commonmark ||
        (gfm && !decimal(trim.left(subvalue).charAt(0))))
    ) {
      break
    }

    position = index
    index = value.indexOf(lineFeed, index + 1)

    if (index !== -1 && trim(value.slice(position, index)) === '') {
      index = position
      break
    }
  }

  subvalue = value.slice(0, index)

  if (trim(subvalue) === '') {
    eat(subvalue)

    return null
  }

  /* istanbul ignore if - never used (yet) */
  if (silent) {
    return true
  }

  now = eat.now()
  subvalue = trimTrailingLines(subvalue)

  return eat(subvalue)({
    type: 'paragraph',
    children: self.tokenizeInline(subvalue, now)
  })
}

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


Question:
Execute the code $js
@param string $js Code to execute
@param boolean $immediatly diffère l'exécution si false
@return String

public function _exec($js, $immediatly=false) {
		$script=$js."\n";
		if ($immediatly)
			$this->jquery_code_for_compile[]=$script;
			return $script;
	}

function () {
    console.log( package.title );
    console.log( package.description );
    console.log( "Version " + package.version );
    console.log();
    console.log( "Commands:" );
    console.log( "sqs buster       Delete local site cache" );
    console.log( "sqs server       Start the local server" );
    console.log();
    console.log( "Options:" );
    console.log( "sqs --version    Print package version" );
    console.log( "sqs --forever    Start server using forever" );
    console.log( "sqs --fornever   Stop server started with forever" );
    console.log( "sqs --port=XXXX  Use the specified port" );
    console.log( "sqs --quiet      Silence the logger" );
    console.log( "sqs --open       Open a new tab for the server when it starts" );
    console.log();
    console.log( "Examples:" );
    console.log( "sqs server --port=8000" );
    process.exit();
}

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


Question: Start twitter stream

private void startTwitterStream() {
        logger.info("starting {} twitter stream", streamType);

        if (stream == null) {
            logger.debug("creating twitter stream");

            stream = new TwitterStreamFactory(buildTwitterConfiguration()).getInstance();
            if (streamType.equals("user")) {
                stream.addListener(new UserStreamHandler());
            } else {
                stream.addListener(new StatusHandler());
            }

            logger.debug("twitter stream created");
        }

        if (riverStatus != RiverStatus.STOPPED && riverStatus != RiverStatus.STOPPING) {
            if (streamType.equals("filter") || filterQuery != null) {
                stream.filter(filterQuery);
            } else if (streamType.equals("firehose")) {
                stream.firehose(0);
            } else if (streamType.equals("user")) {
                stream.user();
            } else {
                stream.sample();
            }
        }
        logger.debug("{} twitter stream started!", streamType);
    }

public static void main(String args[]) {
		try {
			Display display = Display.getDefault();
			WebcamPanelShell shell = new WebcamPanelShell(display);
			shell.open();
			shell.layout();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

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


Question:
Handle on meta data received

@param array $metaData The meta data received
@param Node  $source   The source sending data

@return null

public function receiveMeta($metaData, $source)
    {
        if ($source === $this->container[0]["source"]) {
            $this->container[0]["meta"] = $metaData;
        } else {
            $this->container[1]["meta"] = $metaData;
        }
        if ($this->container[0]["meta"] && $this->container[1]["meta"]) {
            $meta = array(
                "columns" => array_merge(
                    $this->container[0]["meta"]["columns"],
                    $this->container[1]["meta"]["columns"]
                ),
            );
            $this->sendMeta($meta);
        }
    }

protected function doExecute(&$curlHandle) {
        $this->setCurlOpts($curlHandle);
        $response = \curl_exec($curlHandle);

        $header_size = \curl_getinfo($curlHandle, CURLINFO_HEADER_SIZE);

        $this->response_body = substr($response, $header_size);

        $this->response_headers = [];

        $lines = explode("\r\n", substr($response, 0, $header_size));
        foreach ($lines as $i => $line) {
            if ($i === 0) {
                $this->response_headers['http_code'] = $line;
                $piece = explode(" ", $line);
                if (count($piece) > 1) {
                    $this->response_headers['protocol'] = $piece[0];
                    $this->response_headers['status_code'] = $piece[1];
                    array_splice($piece, 0, 2); //Remove protocol and code
                    $this->response_headers['reason_phrase'] = implode(" ", $piece);
                }
            } else {
                $piece = explode(': ', $line, 2);
                if (count($piece) == 2) {
                    list ($key, $value) = $piece;

                    if (trim($key) !== "") {
                        $this->response_headers[$key] = trim($value);
                    }
                }
            }
        }
        $this->response_info = \curl_getinfo($curlHandle);

        \curl_close($curlHandle);
    }

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


Question:
فهرست خصوصیت‌های عمومی را تعیین می‌کند.

@return

public function getGeneralParam()
    {
        $params = array();
        $params[] = array(
            'name' => 'title',
            'type' => 'String',
            'unit' => 'none',
            'title' => 'title',
            'description' => 'beackend title',
            'editable' => true,
            'visible' => true,
            'priority' => 5,
            'symbol' => 'title',
            'defaultValue' => 'no title',
            'validators' => [
                'NotNull',
                'NotEmpty'
            ]
        );
        $params[] = array(
            'name' => 'description',
            'type' => 'String',
            'unit' => 'none',
            'title' => 'description',
            'description' => 'beackend description',
            'editable' => true,
            'visible' => true,
            'priority' => 5,
            'symbol' => 'title',
            'defaultValue' => 'description',
            'validators' => []
        );
        $params[] = array(
            'name' => 'symbol',
            'type' => 'String',
            'unit' => 'none',
            'title' => 'Symbol',
            'description' => 'beackend symbol',
            'editable' => true,
            'visible' => true,
            'priority' => 5,
            'symbol' => 'icon',
            'defaultValue' => '',
            'validators' => []
        );
        return $params;
    }

public function make($identifier, $expireTime = 3600)
    {
        $json = [
            'TLS.account_type' => $this->accountType,
            'TLS.identifier' => (string)$identifier,
            'TLS.appid_at_3rd' => (string)$this->appId,
            'TLS.sdk_appid' => (string)$this->appId,
            'TLS.expire_after' => (string)$expireTime,
            'TLS.version' => '201512300000',
            'TLS.time' => (string)time()
        ];

        $content = $this->genSignatureContent($json);
        $signature = $this->makeSignature($content);
        $json['TLS.sig'] = base64_encode($signature);
        if ($json['TLS.sig'] === false) {
            throw new SignatureException('base64_encode error.');
        }
        $json_text = json_encode($json);
        if ($json_text === false) {
            throw new SignatureException('json_encode error.');
        }
        $compressed = gzcompress($json_text);
        if ($compressed === false) {
            throw new SignatureException('gzcompress error.');
        }
        return $this->base64Encode($compressed);

    }

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


Question:
\
        Display symbols.
            p               Display names of inspectable objects.
            p <id>          Display the content of an object.

def _do_print(self, cmd, args):

        name = args[0].strip()
        if not name:
            self.stderr.write('TODO: Display names of inspectable objects.\n')
            return
        try:
            code = textwrap.dedent(r'''
                    self.stdout.write(name + ':\n' + textwrap.indent(pprint.pformat({}), '    ') + '\n')
                    ''').format(name).strip()
            eval(code, globals(), locals())
        except NameError:
            self.stderr.write("p: name '{}' is not defined\n".format(name))
        self.stdout.flush()

function objToString(obj, commentFix = false) {
  const comment = commentFix ? '/**/' : ''

  return Object.keys(obj).reduce((acc, k) => {
    let value = obj[k]

    if (k.startsWith('__spread__')) {
      return acc + '${' + value + '};' + comment
    }

    if (typeof value === 'string') {
      if (value[0] === '$') {
        value = '${' + value.substr(1) + '}'
      }
      return acc + camelToKebab(k) + ':' + value + ';' + comment
    } else {
      value = objToString(value)
      let key = k[0] === ':' ? '&' + k : k
      key = key[0] === '`' ? key.substr(1, key.length - 2) : key
      return acc + camelToKebab(key) + '{' + value + '};' + comment
    }
  }, '')
}

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


Question:
Sets has many relation

@param mixed $id
@param \JSONSimpleStorage $object
@param mixed[] $foreignIds

public function hasMany($id, \JSONSimpleStorage $object, array $foreignIds) {
        // set has one on foreign data
        foreach ($foreignIds as $foreignId) {
            $object->hasOne($foreignId, $this, $id);
        }
    }

def _detect(self):

        results = []

        self.results = []
        self.visited_all_paths = {}

        for contract in self.slither.contracts:
            for function in contract.functions:
                if function.is_implemented:
                    uninitialized_storage_variables = [v for v in function.local_variables if v.is_storage and v.uninitialized]
                    function.entry_point.context[self.key] = uninitialized_storage_variables
                    self._detect_uninitialized(function, function.entry_point, [])

        for(function, uninitialized_storage_variable) in self.results:
            var_name = uninitialized_storage_variable.name

            info = "{} in {}.{} ({}) is a storage variable never initialiazed\n"
            info = info.format(var_name, function.contract.name, function.name, uninitialized_storage_variable.source_mapping_str)

            json = self.generate_json_result(info)
            self.add_variable_to_json(uninitialized_storage_variable, json)
            self.add_function_to_json(function, json)
            results.append(json)

        return results

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


Question: Builds the APIs resource table

function(api) {
        if( ! _.isObject(api) )
            throw new Error('utils.handler.buildResourceTable needs an espressojs API');

        api._resources = _( api._ids ).values().reject( _.isUndefined ).value();
    }

func (ar *ActionRepository) RegisterTabletAction(name, role string, method actionTabletMethod) {
	ar.tabletActions[name] = actionTabletRecord{
		role:   role,
		method: method,
	}
}

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


Question: // Imag renders the imag built-in function.

func (g *Group) Imag(c Code) *Statement {
	s := Imag(c)
	g.items = append(g.items, s)
	return s
}

def get_thumbnail_source(self, obj):

        if hasattr(self, 'thumbnail_field') and self.thumbnail_field:
            return resolve(obj, self.thumbnail_field)

        # try get_list_image, from ListableMixin
        if hasattr(obj, 'get_list_image'):
            return resolve(obj, "get_list_image")

        logger.warning('ThumbnailAdminMixin.thumbnail_field unspecified')
        return None

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


Question:
// Get registers a route for the Get http method.
//
// Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (api *APIBuilder) Get(relativePath string, handlers ...context.Handler) *Route {
	return api.Handle(http.MethodGet, relativePath, handlers...)
}

public function post($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('POST', $pattern, $handler, $requirements, $defaults);
    }

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


Question:
Load configuration of Sharding-Proxy.

@return configuration of Sharding-Proxy
@throws IOException IO exception

public ShardingConfiguration load() throws IOException {
        Collection<String> schemaNames = new HashSet<>();
        YamlProxyServerConfiguration serverConfig = loadServerConfiguration(new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH + SERVER_CONFIG_FILE).getFile()));
        File configPath = new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH).getFile());
        Collection<YamlProxyRuleConfiguration> ruleConfigurations = new LinkedList<>();
        for (File each : findRuleConfigurationFiles(configPath)) {
            Optional<YamlProxyRuleConfiguration> ruleConfig = loadRuleConfiguration(each, serverConfig);
            if (ruleConfig.isPresent()) {
                Preconditions.checkState(schemaNames.add(ruleConfig.get().getSchemaName()), "Schema name `%s` must unique at all rule configurations.", ruleConfig.get().getSchemaName());
                ruleConfigurations.add(ruleConfig.get());
            }
        }
        Preconditions.checkState(!ruleConfigurations.isEmpty() || null != serverConfig.getOrchestration(), "Can not find any sharding rule configuration file in path `%s`.", configPath.getPath());
        Map<String, YamlProxyRuleConfiguration> ruleConfigurationMap = new HashMap<>(ruleConfigurations.size(), 1);
        for (YamlProxyRuleConfiguration each : ruleConfigurations) {
            ruleConfigurationMap.put(each.getSchemaName(), each);
        }
        return new ShardingConfiguration(serverConfig, ruleConfigurationMap);
    }

def _couple_nic(self, userid, vdev, vswitch_name,
                    active=False):
        """"""
        if active:
            self._is_active(userid)

        msg = ('Start to couple nic device %(vdev)s of guest %(vm)s '
               'with vswitch %(vsw)s'
                % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name})
        LOG.info(msg)
        requestData = ' '.join((
            'SMAPI %s' % userid,
            "API Virtual_Network_Adapter_Connect_Vswitch_DM",
            "--operands",
            "-v %s" % vdev,
            "-n %s" % vswitch_name))

        try:
            self._request(requestData)
        except exception.SDKSMTRequestFailed as err:
            LOG.error("Failed to couple nic %s to vswitch %s for user %s "
                      "in the guest's user direct, error: %s" %
                      (vdev, vswitch_name, userid, err.format_message()))
            self._couple_inactive_exception(err, userid, vdev, vswitch_name)

        # the inst must be active, or this call will failed
        if active:
            requestData = ' '.join((
                'SMAPI %s' % userid,
                'API Virtual_Network_Adapter_Connect_Vswitch',
                "--operands",
                "-v %s" % vdev,
                "-n %s" % vswitch_name))

            try:
                self._request(requestData)
            except (exception.SDKSMTRequestFailed,
                    exception.SDKInternalError) as err1:
                results1 = err1.results
                msg1 = err1.format_message()
                if ((results1 is not None) and
                    (results1['rc'] == 204) and
                    (results1['rs'] == 20)):
                    LOG.warning("Virtual device %s already connected "
                                "on the active guest system", vdev)
                else:
                    persist_OK = True
                    requestData = ' '.join((
                        'SMAPI %s' % userid,
                        'API Virtual_Network_Adapter_Disconnect_DM',
                        "--operands",
                        '-v %s' % vdev))
                    try:
                        self._request(requestData)
                    except (exception.SDKSMTRequestFailed,
                            exception.SDKInternalError) as err2:
                        results2 = err2.results
                        msg2 = err2.format_message()
                        if ((results2 is not None) and
                            (results2['rc'] == 212) and
                            (results2['rs'] == 32)):
                            persist_OK = True
                        else:
                            persist_OK = False
                    if persist_OK:
                        self._couple_active_exception(err1, userid, vdev,
                                                      vswitch_name)
                    else:
                        raise exception.SDKNetworkOperationError(rs=3,
                                    nic=vdev, vswitch=vswitch_name,
                                    couple_err=msg1, revoke_err=msg2)

        """Update information in switch table."""
        self._NetDbOperator.switch_update_record_with_switch(userid, vdev,
                                                             vswitch_name)
        msg = ('Couple nic device %(vdev)s of guest %(vm)s '
               'with vswitch %(vsw)s successfully'
                % {'vdev': vdev, 'vm': userid, 'vsw': vswitch_name})
        LOG.info(msg)

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


Question:
the extension hook for the various types of encoding; must work with Object values to ensure
that non String values can be used as is

@param value the value (String) to encode
@return the encoded String or an appropriate Object

protected Object escape(Object value) {
        EscapeFunction function = ESCAPE_FUNCTION_MAP.get(this.type);
        return function != null ? function.escape(TagUtil.getRequest(this.pageContext), value) : CpnlElFunctions.text(toString(value));
    }

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

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


Question: Closes the underlying socket.

public void close()
    throws IOException
  {
    ServerSocketChannel ss = _ss;
    _ss = ss;

    if (ss != null) {
      try {
        ss.close();
      } catch (Exception e) {
      }
    }
  }

public static boolean isEndState(TraceEvent te)
   {
      if (te.getType() == TraceEvent.RETURN_CONNECTION_LISTENER ||
          te.getType() == TraceEvent.RETURN_CONNECTION_LISTENER_WITH_KILL ||
          te.getType() == TraceEvent.RETURN_INTERLEAVING_CONNECTION_LISTENER ||
          te.getType() == TraceEvent.RETURN_INTERLEAVING_CONNECTION_LISTENER_WITH_KILL ||
          te.getType() == TraceEvent.CLEAR_CONNECTION_LISTENER)
         return true;

      return false;
   }

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


Question: // readBytes reads the given number of bytes from the reader

func (s *stream) readBytes(n uint32) ([]byte, error) {
	if n > s.size {
		s.buf = make([]byte, n)
		s.size = n
	}

	if _, err := io.ReadFull(s.Reader, s.buf[:n]); err != nil {
		return nil, err
	}

	return s.buf[:n], nil
}

public BufferedReader newBufferedReader(Path path, Charset cs)
    {
        try {
            return Files.newBufferedReader(path, cs);
        } catch (IOException e) {
            return null;
        }
    }

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


Question:
// Field returns an entry field value by name or empty string and error if it
// does not exist.

func (entry *Entry) Field(name string) (value string, err error) {
	value, ok := entry.fields[name]
	if !ok {
		err = fmt.Errorf("field '%v' does not found in record %+v", name, *entry)
	}
	return
}

public function err($text = '', $nl = true)
	{
		fwrite(STDERR, $this->processor->process($text) . ($nl ? "\n" : null));

		return $this;
	}

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


Question: // Watch for changes on the lock

func (lk *etcdLock) watchLock() {
	keyName := "/contiv.io/lock/" + lk.name

	watcher := lk.kapi.Watcher(keyName, nil)
	if watcher == nil {
		log.Errorf("Error creating the watcher")
		return
	}
	for {
		resp, err := watcher.Next(lk.watchCtx)
		if err != nil && (err.Error() == client.ErrClusterUnavailable.Error() ||
			strings.Contains(err.Error(), "context canceled")) {
			log.Infof("Stopping watch on key %s", keyName)
			return
		} else if err != nil {
			log.Errorf("Error watching the key %s, Err %v.", keyName, err)
		} else {
			log.Debugf("Got Watch Resp: %+v", resp)

			// send the event to watch channel
			lk.watchCh <- resp
		}

		lk.mutex.Lock()
		// If the lock is released, we are done
		if lk.isReleased {
			lk.mutex.Unlock()
			return
		}
		lk.mutex.Unlock()
	}
}

def on_msg(msg)

      puts(fancy_print(msg, @noisy)) if @noisy

      return if msg['action'] == 'noop'

      @mutex.synchronize do

        @seen << msg
        @log << msg

        while @log.size > @log_max; @log.shift; end
        while @seen.size > @log_max; @seen.shift; end
      end
    end

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


Question:
Retrieve the first object of type ``ObjectClass``,
        matching the specified filters in ``**kwargs`` -- case sensitive.

def find_first_object(self, ObjectClass, **kwargs):

        filter = None
        for k, v in kwargs.items():
            cond = getattr(ObjectClass, k) == v
            filter = cond if filter is None else filter & cond

        return list(ObjectClass.scan(filter, limit=1))[0]

def get_name(self, properly_capitalized=False):
        """"""

        if properly_capitalized:
            self.name = _extract(
                self._request(self.ws_prefix + ".getInfo", True), "name"
            )

        return self.name

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


Question: // Parse parses date/time string

func (pt *ParseTime) Parse(value string) (time.Time, error) {
	times := make(sortedTimes, 0)
	t, priority, _ := parseISO8601(value, pt.location)
	if !t.IsZero() {
		times = append(times, sortedTime{time: t, priority: priority})
	}

	t, priority, _ = parseRFC8xx1123(value, pt.location)
	if !t.IsZero() {
		times = append(times, sortedTime{time: t, priority: priority})
	}

	t, priority, _ = parseANSIC(value, pt.location)
	if !t.IsZero() {
		times = append(times, sortedTime{time: t, priority: priority})
	}

	t, priority, _ = parseUS(value, pt.location)
	if !t.IsZero() {
		times = append(times, sortedTime{time: t, priority: priority})
	}

	if len(times) == 0 {
		var tmpT time.Time
		return tmpT, errInvalidDateTime
	}

	sort.Sort(times)

	return times[0].time, nil
}

def CopyToDateTimeString(self):

    if (self._timestamp is None or self._timestamp < self._INT64_MIN or
        self._timestamp > self._INT64_MAX):
      return None

    return super(JavaTime, self).CopyToDateTimeString()

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


Question:
@param string $directory
@param bool $recursive

@return \Nexus\CustomCommand\Business\Model\Hydrator\CommandHydratorInterface

public function createCommandHydrator(string $directory, bool $recursive) : CommandHydratorInterface
    {
        return new CommandHydrator(
            $this->createCommandFinder(
                $directory,
                $recursive
            )
        );
    }

func newRouter(handler *Handler) *mux.Router {
	router := mux.NewRouter()
	router.HandleFunc("/", handler.handleHome).Methods("GET").Name("Home")
	router.HandleFunc("/cluster/resize/abort", handler.handlePostClusterResizeAbort).Methods("POST").Name("PostClusterResizeAbort")
	router.HandleFunc("/cluster/resize/remove-node", handler.handlePostClusterResizeRemoveNode).Methods("POST").Name("PostClusterResizeRemoveNode")
	router.HandleFunc("/cluster/resize/set-coordinator", handler.handlePostClusterResizeSetCoordinator).Methods("POST").Name("PostClusterResizeSetCoordinator")
	router.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux).Methods("GET")
	router.Handle("/debug/vars", expvar.Handler()).Methods("GET")
	router.HandleFunc("/export", handler.handleGetExport).Methods("GET").Name("GetExport")
	router.HandleFunc("/index", handler.handleGetIndexes).Methods("GET").Name("GetIndexes")
	router.HandleFunc("/index/{index}", handler.handleGetIndex).Methods("GET").Name("GetIndex")
	router.HandleFunc("/index/{index}", handler.handlePostIndex).Methods("POST").Name("PostIndex")
	router.HandleFunc("/index/{index}", handler.handleDeleteIndex).Methods("DELETE").Name("DeleteIndex")
	//router.HandleFunc("/index/{index}/field", handler.handleGetFields).Methods("GET") // Not implemented.
	router.HandleFunc("/index/{index}/field/{field}", handler.handlePostField).Methods("POST").Name("PostField")
	router.HandleFunc("/index/{index}/field/{field}", handler.handleDeleteField).Methods("DELETE").Name("DeleteField")
	router.HandleFunc("/index/{index}/field/{field}/import", handler.handlePostImport).Methods("POST").Name("PostImport")
	router.HandleFunc("/index/{index}/field/{field}/import-roaring/{shard}", handler.handlePostImportRoaring).Methods("POST").Name("PostImportRoaring")
	router.HandleFunc("/index/{index}/query", handler.handlePostQuery).Methods("POST").Name("PostQuery")
	router.HandleFunc("/info", handler.handleGetInfo).Methods("GET").Name("GetInfo")
	router.HandleFunc("/recalculate-caches", handler.handleRecalculateCaches).Methods("POST").Name("RecalculateCaches")
	router.HandleFunc("/schema", handler.handleGetSchema).Methods("GET").Name("GetSchema")
	router.HandleFunc("/schema", handler.handlePostSchema).Methods("POST").Name("PostSchema")
	router.HandleFunc("/status", handler.handleGetStatus).Methods("GET").Name("GetStatus")
	router.HandleFunc("/version", handler.handleGetVersion).Methods("GET").Name("GetVersion")

	// /internal endpoints are for internal use only; they may change at any time.
	// DO NOT rely on these for external applications!
	router.HandleFunc("/internal/cluster/message", handler.handlePostClusterMessage).Methods("POST").Name("PostClusterMessage")
	router.HandleFunc("/internal/fragment/block/data", handler.handleGetFragmentBlockData).Methods("GET").Name("GetFragmentBlockData")
	router.HandleFunc("/internal/fragment/blocks", handler.handleGetFragmentBlocks).Methods("GET").Name("GetFragmentBlocks")
	router.HandleFunc("/internal/fragment/data", handler.handleGetFragmentData).Methods("GET").Name("GetFragmentData")
	router.HandleFunc("/internal/fragment/nodes", handler.handleGetFragmentNodes).Methods("GET").Name("GetFragmentNodes")
	router.HandleFunc("/internal/index/{index}/attr/diff", handler.handlePostIndexAttrDiff).Methods("POST").Name("PostIndexAttrDiff")
	router.HandleFunc("/internal/index/{index}/field/{field}/attr/diff", handler.handlePostFieldAttrDiff).Methods("POST").Name("PostFieldAttrDiff")
	router.HandleFunc("/internal/index/{index}/field/{field}/remote-available-shards/{shardID}", handler.handleDeleteRemoteAvailableShard).Methods("DELETE")
	router.HandleFunc("/internal/nodes", handler.handleGetNodes).Methods("GET").Name("GetNodes")
	router.HandleFunc("/internal/shards/max", handler.handleGetShardsMax).Methods("GET").Name("GetShardsMax") // TODO: deprecate, but it's being used by the client
	router.HandleFunc("/internal/translate/data", handler.handleGetTranslateData).Methods("GET").Name("GetTranslateData")
	router.HandleFunc("/internal/translate/keys", handler.handlePostTranslateKeys).Methods("POST").Name("PostTranslateKeys")

	router.Use(handler.queryArgValidator)
	router.Use(handler.extractTracing)
	return router
}

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


Question: Returns the url to redirect the user to for user consent

def authorize_url(self, scope='', **kwargs):

        self._check_configuration("site", "authorization_url", "redirect_uri",
                                  "client_id")
        if isinstance(scope, (list, tuple, set, frozenset)):
            self._check_configuration("scope_sep")
            scope = self.scope_sep.join(scope)
        oauth_params = {
            'redirect_uri': self.redirect_uri,
            'client_id': self.client_id,
            'scope': scope,
        }
        oauth_params.update(kwargs)
        return "%s%s?%s" % (self.site, quote(self.authorization_url),
                            urlencode(oauth_params))

def request_setup req_or_uri # :nodoc:
    req = if URI === req_or_uri then
            Net::HTTP::Get.new req_or_uri.request_uri
          else
            req_or_uri
          end

    @headers.each do |pair|
      req.add_field(*pair)
    end

    @override_headers.each do |name, value|
      req[name] = value
    end

    unless req['Connection'] then
      req.add_field 'Connection', 'keep-alive'
      req.add_field 'Keep-Alive', @keep_alive
    end

    req
  end

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


Question: Return our appropriate resampler when grouping as well.

def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None,
                               limit=None, kind=None, **kwargs):

    # .resample uses 'on' similar to how .groupby uses 'key'
    kwargs['key'] = kwargs.pop('on', None)

    tg = TimeGrouper(freq=rule, **kwargs)
    resampler = tg._get_resampler(groupby.obj, kind=kind)
    r = resampler._get_resampler_for_grouping(groupby=groupby)
    return _maybe_process_deprecations(r,
                                       how=how,
                                       fill_method=fill_method,
                                       limit=limit)

func ExtractPayloadOrPanic(envelope *cb.Envelope) *cb.Payload {
	payload, err := ExtractPayload(envelope)
	if err != nil {
		panic(err)
	}
	return payload
}

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


Question:
Reads in a JSON object and try to create a LatLng in one of the following formats.

<pre>{
"lat" : -33.8353684,
"lng" : 140.8527069
}

{
"latitude": -33.865257570508334,
"longitude": 151.19287000481452
}</pre>

@Override
  public LatLng read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
      reader.nextNull();
      return null;
    }

    double lat = 0;
    double lng = 0;
    boolean hasLat = false;
    boolean hasLng = false;

    reader.beginObject();
    while (reader.hasNext()) {
      String name = reader.nextName();
      if ("lat".equals(name) || "latitude".equals(name)) {
        lat = reader.nextDouble();
        hasLat = true;
      } else if ("lng".equals(name) || "longitude".equals(name)) {
        lng = reader.nextDouble();
        hasLng = true;
      }
    }
    reader.endObject();

    if (hasLat && hasLng) {
      return new LatLng(lat, lng);
    } else {
      return null;
    }
  }

def meters(self):
        """"""
        latitude, longitude = self.latitude_longitude
        meter_x = longitude * ORIGIN_SHIFT / 180.0
        meter_y = math.log(math.tan((90.0 + latitude) * math.pi / 360.0)) / (math.pi / 180.0)
        meter_y = meter_y * ORIGIN_SHIFT / 180.0
        return meter_x, meter_y

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


Question:
A closure which will create a record from a database row.

@return Closure

public static function rowMapper(): Closure
    {
        return static function (stdClass $row): Individual {
            $individual = Individual::getInstance($row->i_id, Tree::findById((int) $row->i_file), $row->i_gedcom);

            if ($row->n_num ?? null) {
                $individual = clone $individual;
                $individual->setPrimaryName($row->n_num);

                return $individual;
            }

            return $individual;
        };
    }

private function processClosingField($value, array $option)
    {
        $cell = $this->trimRightEnclosure($value, $option['enclosure']);
        $cell = $this->unescapeEnclosure($cell, $option['enclosure']);

        $this->joinCell($this->revert . $cell);
        $this->continue = false;
        $this->col++;
    }

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


Question: Get an instance of Api V4 IPv4 services facade.

def create_api_v4_ipv4(self):
        """"""

        return ApiV4IPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

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


Question:
Construct Pencil objects from a JSON
@param {Object} json - Valid JSON
@return {*}

function from (json) {
    const instance = exportableClasses[json.constructor].from(json);
    if (json.children) {
        instance.add(...json.children.map(child => from(child)));
    }
    return instance;
}

private void parsePointMetadata(JsonParser jp) throws IOException, SQLException {
        jp.nextToken(); // FIELD_NAME coordinates
        String coordinatesField = jp.getText();
        if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
            jp.nextToken(); // START_ARRAY [ to parse the coordinate
            parseCoordinateMetadata(jp);
        } else {
            throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
        }
    }

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


Question: // PostForm mocks base method

func (m *MockRCHTTPClienter) PostForm(arg0 context.Context, arg1 string, arg2 url.Values) (*http.Response, error) {
	ret := m.ctrl.Call(m, "PostForm", arg0, arg1, arg2)
	ret0, _ := ret[0].(*http.Response)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

public function dispatch(
        MetaboxModel $metabox,
        MetaboxFactory $factory,
        HookFactory $hook
    ) {
        $this->metabox = $metabox;
        $this->factory = $factory;
        $this->hook = $hook;
    }

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


Question:
Launches system editor to edit the wp-config.php file.

## EXAMPLES

# Launch system editor to edit wp-config.php file
$ wp config edit

# Edit wp-config.php file in a specific editor
$ EDITOR=vim wp config edit

@when before_wp_load

public function edit() {
		$config_path = $this->get_config_path();
		$contents    = file_get_contents( $config_path );
		$r           = Utils\launch_editor_for_input( $contents, 'wp-config.php', 'php' );
		if ( false === $r ) {
			WP_CLI::warning( 'No changes made to wp-config.php.', 'Aborted' );
		} else {
			file_put_contents( $config_path, $r );
		}
	}

def new(self, fname=None, editorstack=None, text=None):

        # If no text is provided, create default content
        empty = False
        try:
            if text is None:
                default_content = True
                text, enc = encoding.read(self.TEMPLATE_PATH)
                enc_match = re.search(r'-*- coding: ?([a-z0-9A-Z\-]*) -*-',
                                      text)
                if enc_match:
                    enc = enc_match.group(1)
                # Initialize template variables
                # Windows
                username = encoding.to_unicode_from_fs(
                                os.environ.get('USERNAME', ''))
                # Linux, Mac OS X
                if not username:
                    username = encoding.to_unicode_from_fs(
                                   os.environ.get('USER', '-'))
                VARS = {
                    'date': time.ctime(),
                    'username': username,
                }
                try:
                    text = text % VARS
                except Exception:
                    pass
            else:
                default_content = False
                enc = encoding.read(self.TEMPLATE_PATH)[1]
        except (IOError, OSError):
            text = ''
            enc = 'utf-8'
            default_content = True
            empty = True

        create_fname = lambda n: to_text_string(_("untitled")) + ("%d.py" % n)
        # Creating editor widget
        if editorstack is None:
            current_es = self.get_current_editorstack()
        else:
            current_es = editorstack
        created_from_here = fname is None
        if created_from_here:
            while True:
                fname = create_fname(self.untitled_num)
                self.untitled_num += 1
                if not osp.isfile(fname):
                    break
            basedir = getcwd_or_home()

            if self.main.projects.get_active_project() is not None:
                basedir = self.main.projects.get_active_project_path()
            else:
                c_fname = self.get_current_filename()
                if c_fname is not None and c_fname != self.TEMPFILE_PATH:
                    basedir = osp.dirname(c_fname)
            fname = osp.abspath(osp.join(basedir, fname))
        else:
            # QString when triggered by a Qt signal
            fname = osp.abspath(to_text_string(fname))
            index = current_es.has_filename(fname)
            if index is not None and not current_es.close_file(index):
                return

        # Creating the editor widget in the first editorstack (the one that
        # can't be destroyed), then cloning this editor widget in all other
        # editorstacks:
        finfo = self.editorstacks[0].new(fname, enc, text, default_content,
                                         empty)
        finfo.path = self.main.get_spyder_pythonpath()
        self._clone_file_everywhere(finfo)
        current_editor = current_es.set_current_filename(finfo.filename)
        self.register_widget_shortcuts(current_editor)
        if not created_from_here:
            self.save(force=True)

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


Question:
Convert the grayscale image to a ColorImage.

        Returns
        -------
        :obj:`ColorImage`
            A color image equivalent to the grayscale one.

def to_color(self):

        color_data = np.repeat(self.data[:,:,np.newaxis], 3, axis=2)
        return ColorImage(color_data, self._frame)

func setBlendFunc(cmp pixel.ComposeMethod) {
	switch cmp {
	case pixel.ComposeOver:
		glhf.BlendFunc(glhf.One, glhf.OneMinusSrcAlpha)
	case pixel.ComposeIn:
		glhf.BlendFunc(glhf.DstAlpha, glhf.Zero)
	case pixel.ComposeOut:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.Zero)
	case pixel.ComposeAtop:
		glhf.BlendFunc(glhf.DstAlpha, glhf.OneMinusSrcAlpha)
	case pixel.ComposeRover:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.One)
	case pixel.ComposeRin:
		glhf.BlendFunc(glhf.Zero, glhf.SrcAlpha)
	case pixel.ComposeRout:
		glhf.BlendFunc(glhf.Zero, glhf.OneMinusSrcAlpha)
	case pixel.ComposeRatop:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.SrcAlpha)
	case pixel.ComposeXor:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.OneMinusSrcAlpha)
	case pixel.ComposePlus:
		glhf.BlendFunc(glhf.One, glhf.One)
	case pixel.ComposeCopy:
		glhf.BlendFunc(glhf.One, glhf.Zero)
	default:
		panic(errors.New("Canvas: invalid compose method"))
	}
}

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


Question: Render the configuration as text.

def _config_to_text(self):
        """"""
        r = u'' # unicode('',"UTF-8")
        for k in self._config:
            # if k == 'creation_date':
            #     r +=  k + ": " + self._config[k][0] + '\n'
            # else:
            #uk = unicode(k,"UTF-8")
            cosa = '\n        '.join(self._config[k]) + '\n'
            r += k + ": " + cosa
            #r += k + ": " + '\n        '.join(self._config[k]) + '\n'
        r += '\n'
        return r

def get_config(self):

        # Fill this dict with config data
        return {
            'hash_name': self.hash_name,
            'dim': self.dim,
            'projection_count': self.projection_count,
            'normals': self.normals,
            'tree_root': self.tree_root,
            'minimum_result_size': self.minimum_result_size
        }

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


Question:
Retrieve server version in PHP style
Pdo_Idm doesn't support getAttribute(PDO::ATTR_SERVER_VERSION)
@return string

public function getServerVersion()
    {
        try {
            $stmt = $this->query('SELECT service_level, fixpack_num FROM TABLE (sysproc.env_get_inst_info()) as INSTANCEINFO');
            $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
            if (count($result)) {
                $matches = null;
                if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $result[0][0], $matches)) {
                    return $matches[1];
                } else {
                    return null;
                }
            }
            return null;
        } catch (PDOException $e) {
            return null;
        }
    }

public function check($ip, Limit $limit)
    {
        $this->assertReady();

        if ($this->cleanOnCheck) {
            $this->clean();
        }

        $sql = sprintf("SELECT count(*) as count FROM %s WHERE %s=:ip AND %s=:type AND %s >= NOW() - INTERVAL %d SECOND",
            $this->dbAdapter->platform->quoteIdentifier($this->table),
            $this->dbAdapter->platform->quoteIdentifier($this->ipColumn),
            $this->dbAdapter->platform->quoteIdentifier($this->typeColumn),
            $this->dbAdapter->platform->quoteIdentifier($this->timestampColumn),
            $limit->getInterval()->toSeconds());

        $parameters = array(
            'ip' => $ip,
            'type' => $limit->getName(),
        );

        $result = $this->dbAdapter->query($sql, $parameters);
        $count = $result->current()->count;
        return $count >= $limit->getLimit();
    }

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


Question:
Assemble the chunk so that it can be used to construct the VoltTable that
will be passed to EE.

@param buf
@return

public static ByteBuffer getNextChunk(byte[] schemaBytes, ByteBuffer buf,
                                          CachedByteBufferAllocator resultBufferAllocator) {
        buf.position(buf.position() + 4);//skip partition id
        int length = schemaBytes.length + buf.remaining();

        ByteBuffer outputBuffer = resultBufferAllocator.allocate(length);
        outputBuffer.put(schemaBytes);
        outputBuffer.put(buf);
        outputBuffer.flip();

        return outputBuffer;
    }

public function writeTextualData($key, $value)
    {
        $this->buffer->startChunk("tEXt");
        $this->buffer->writeString($key);
        $this->buffer->writeUInt8(0);
        $this->buffer->writeString($value);
        $this->buffer->endChunk();
    }

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


Question:
Tenured Space Pool can be determined by it being of type HEAP and by it
being possible to set the usage threshold.

@return MXBean for the Tenured Space Pool

private static MemoryPoolMXBean findTenuredGenPool() {
        // I don't know whether this approach is better, or whether
        // we should rather check for the pool name "Tenured Gen"?
        for (final MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans())
            if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
                return pool;
            }
        throw new AssertionError("Could not find tenured space");
    }

def simulate(self, action):

    with tf.name_scope('environment/simulate'):
      if action.dtype in (tf.float16, tf.float32, tf.float64):
        action = tf.check_numerics(action, 'action')
      observ_dtype = self._parse_dtype(self._batch_env.observation_space)
      observ, reward, done = tf.py_func(
          lambda a: self._batch_env.step(a)[:3], [action],
          [observ_dtype, tf.float32, tf.bool], name='step')
      observ = tf.check_numerics(observ, 'observ')
      reward = tf.check_numerics(reward, 'reward')
      return tf.group(
          self._observ.assign(observ),
          self._action.assign(action),
          self._reward.assign(reward),
          self._done.assign(done))

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


Question:
@param string $size

@return $this

public function setSize($size)
    {
        if (strpos($size, 'col-') === false) {
            $size = 'col-'.$size.'-';
        }

        $this->size = $size;

        return $this;
    }

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

}

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


Question:
Handles EIP binding process in AWS Cloud.

@throws InterruptedException

private void handleEIPBinding() throws InterruptedException {
        int retries = serverConfig.getEIPBindRebindRetries();
        // Bind to EIP if needed
        for (int i = 0; i < retries; i++) {
            try {
                if (isEIPBound()) {
                    break;
                } else {
                    bindEIP();
                }
            } catch (Throwable e) {
                logger.error("Cannot bind to EIP", e);
                Thread.sleep(EIP_BIND_SLEEP_TIME_MS);
            }
        }
        // Schedule a timer which periodically checks for EIP binding.
        timer.schedule(new EIPBindingTask(), serverConfig.getEIPBindingRetryIntervalMsWhenUnbound());
    }

def callback(self, ch, method, properties, body):

        index = method.routing_key.split('.')[1]
        index = index.replace('/', '-')
        failed = False
        body = str(body)
        try:
            doc = json.loads(body)
        except Exception as e:  # pragma: no cover
            try:
                body = body.strip().replace('"', '\"')
                body = '{"log":"' + body + '"}'
                doc = json.loads(body)
            except Exception as e:  # pragma: no cover
                failed = True

        if not failed:
            try:
                self.es_conn.index(index=index,
                                   doc_type=method.routing_key.split('.')[1],
                                   id=method.routing_key + '.' +
                                   str(uuid.uuid4()),
                                   body=doc)
            except Exception as e:  # pragma: no cover
                print('Failed to send document to elasticsearch because: ' + str(e))

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


Question:
Renders the results.
@param OutputInterface  $output  Output Interface.
@param ResultCollection $results Result Collection.
@return void

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

public Object get(Object objKey) {
        if (objKey == null) {
            throw new IllegalArgumentException("The key parameter must not be null.");
        }
        final String key = objKey.toString();
        final int pos = key.lastIndexOf(INDEXED_DELIM);
        if (pos > 0) {
            final int endPos = key.lastIndexOf(INDEXED_DELIM2);
            if (pos >= endPos) {
                throw new IllegalArgumentException("The key(" + key + ") is invalid.");
            }
            final int index = Integer.valueOf(key.substring(pos + 1, endPos));
            final String name = key.substring(0, pos);
            final Object value;
            final Class<?> type;
            if (name.indexOf(INDEXED_DELIM) > 0) {
                value = get(name);
                type = value.getClass();
            } else {
                PropertyDesc pd = beanDesc.getPropertyDesc(name);
                if (!pd.isReadable()) {
                    return null;
                }
                value = pd.getValue(bean);
                if (value == null) {
                    return null;
                }
                type = pd.getPropertyType();
            }
            if (type.isArray()) {
                return LaParamWrapperUtil.convert(Array.get(value, index));
            }
            if (List.class.isAssignableFrom(type)) {
                return LaParamWrapperUtil.convert(((List<?>) value).get(index));
            }
            throw new IllegalStateException("Index property must be an array or a list.");
        }
        final PropertyDesc pd = beanDesc.getPropertyDesc(key);
        if (!pd.isReadable()) {
            return null;
        }
        return LaParamWrapperUtil.convert(pd.getValue(bean));
    }

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


Question:
Given a hash get the first occurance's record id.

@param hash
@return
@throws SQLException

protected int selectRecordId(String hash) throws SQLException {
        int id = -1;
        Connection connection = getConnection();
        try {
            PreparedStatement ps = setObjects(connection, Query.GET_RECORD_ID,
                    hash);
            ResultSet rs = ps.executeQuery();
            try {
                while (rs.next()) {
                    id = rs.getInt("id");
                    break;
                }
            } finally {
                rs.close();
                ps.close();
            }
        } finally {
            connection.close();
        }
        return id;
    }

def genargs(prog: Optional[str] = None) -> ArgumentParser:

    parser = ArgumentParser(prog)
    parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options")
    parser.add_argument("shex", help="ShEx specification")
    parser.add_argument("-f", "--format", help="Input RDF Format", default="turtle")
    parser.add_argument("-s", "--start", help="Start shape. If absent use ShEx start node.")
    parser.add_argument("-ut", "--usetype", help="Start shape is rdf:type of focus", action="store_true")
    parser.add_argument("-sp", "--startpredicate", help="Start shape is object of this predicate")
    parser.add_argument("-fn", "--focus", help="RDF focus node")
    parser.add_argument("-A", "--allsubjects", help="Evaluate all non-bnode subjects in the graph", action="store_true")
    parser.add_argument("-d", "--debug", action="store_true", help="Add debug output")
    parser.add_argument("-ss", "--slurper", action="store_true", help="Use SPARQL slurper graph")
    parser.add_argument("-cf", "--flattener", action="store_true", help="Use RDF Collections flattener graph")
    parser.add_argument("-sq", "--sparql", help="SPARQL query to generate focus nodes")
    parser.add_argument("-se", "--stoponerror", help="Stop on an error", action="store_true")
    parser.add_argument("--stopafter", help="Stop after N nodes", type=int)
    parser.add_argument("-ps", "--printsparql", help="Print SPARQL queries as they are executed", action="store_true")
    parser.add_argument("-pr", "--printsparqlresults", help="Print SPARQL query and results", action="store_true")
    parser.add_argument("-gn", "--graphname", help="Specific SPARQL graph to query - use '' for any named graph")
    parser.add_argument("-pb", "--persistbnodes", help="Treat BNodes as persistent in SPARQL endpoint",
                        action="store_true")
    return parser

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


Question: // Upload a software image

func (b *BigIP) UploadSoftwareImage(f *os.File) (*Upload, error) {
	if !strings.HasSuffix(f.Name(), ".iso") {
		err := fmt.Errorf("File must have .iso extension")
		return nil, err
	}
	info, err := f.Stat()
	if err != nil {
		return nil, err
	}
	return b.Upload(f, info.Size(), uriCm, uriAutodeploy, uriSoftwareImageUploads, info.Name())
}

public function outputImage($path, array $params = [], $skipValidation = false)
    {
        $this->validateRequest($path, $params, $skipValidation);

        $this->getLeagueGlideServer()->outputImage($path, $params);
    }

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


Question:
Get loaded object. If object is not loaded yet, then load it and save it
locally. Otherwise, just return the pre-loaded object.

@return mixed Loaded object

public function get()
    {
        if ($this->customer instanceof CustomerInterface) {
            return $this->customer;
        }

        $customer = $this->getCustomerFromToken();

        if (null === $customer) {
            $customer = $this->customerFactory->create();
        }

        $this->customer = $customer;

        return $customer;
    }

func (p *pinner) Flush() error {
	p.lock.Lock()
	defer p.lock.Unlock()

	ctx := context.TODO()

	internalset := cid.NewSet()
	recordInternal := internalset.Add

	root := &mdag.ProtoNode{}
	{
		n, err := storeSet(ctx, p.internal, p.directPin.Keys(), recordInternal)
		if err != nil {
			return err
		}
		if err := root.AddNodeLink(linkDirect, n); err != nil {
			return err
		}
	}

	{
		n, err := storeSet(ctx, p.internal, p.recursePin.Keys(), recordInternal)
		if err != nil {
			return err
		}
		if err := root.AddNodeLink(linkRecursive, n); err != nil {
			return err
		}
	}

	// add the empty node, its referenced by the pin sets but never created
	err := p.internal.Add(ctx, new(mdag.ProtoNode))
	if err != nil {
		return err
	}

	err = p.internal.Add(ctx, root)
	if err != nil {
		return err
	}

	k := root.Cid()

	internalset.Add(k)
	if err := p.dstore.Put(pinDatastoreKey, k.Bytes()); err != nil {
		return fmt.Errorf("cannot store pin state: %v", err)
	}
	p.internalPin = internalset
	return nil
}

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


Question:
Tries to extract charset from pre-parsed part of Content-Type value

@param array $contentTypeParts
@return null|string

private static function extractCharset(array $contentTypeParts)
    {
        foreach ($contentTypeParts as $part) {
            $elements = explode('=', $part);
            $key = trim(array_shift($elements));
            if (strtolower($key) === 'charset') {
                $value = trim(reset($elements));
                return $value ?: null;
            }
        }
        return null;
    }

public function getHeadersAsString($status = true, $eol = "\n")
    {
        $headers = '';

        if ($status) {
            $headers = "HTTP/{$this->version} {$this->code} {$this->reasonPhrase}{$eol}";
        }

        foreach ($this->headers as $name => $value) {
            $headers .= "{$name}: {$value}{$eol}";
        }

        return $headers;
    }

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


Question:
Adds a key to the bot's data

    Args:
        key: The name of the key to add
        value: The value for the key

def add_api_key(key, value):

    if key is None or key == "":
        logger.error("Key cannot be empty")

    if value is None or value == "":
        logger.error("Value cannot be empty")

    from .. import datatools
    data = datatools.get_data()

    if "keys" not in data["discord"]:
        data["discord"]["keys"] = {}

    is_key_new = False
    if key not in data["discord"]["keys"]:
        is_key_new = True
    elif data["discord"]["keys"][key] == value:
        logger.info("API key '{}' already has value '{}'".format(key, value))
        return

    data["discord"]["keys"][key] = value
    datatools.write_data(data)

    key_text = "added" if is_key_new else "updated"
    logger.info("API key '{}' {} with value '{}'".format(key, key_text, value))

def get_item_api(self, resource):

        parameters = self.get_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            'operations': [
                {
                    'httpMethod': 'GET',
                    'nickname': 'get%s' % resource.model.__name__,
                    'summary': 'Get %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

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


Question:
Creates select query, executes it and returns the result as assoc array.
@return string[]

public function get()
    {
        $q = "SELECT " . $this->fields . " FROM `" . $this->table . "` " . $this->join;
        if ($this->condition) {
            $q .= " WHERE {$this->condition}";
        }
        if ($this->group) {
            $q .= " GROUP BY {$this->group}";
            if ($this->having) {
                $q .= " HAVING {$this->having}";
            }
        }
        if ($this->order) {
            $q .= " ORDER BY {$this->order}";
        }
        if ($this->limit) {
            $q .= " LIMIT {$this->limit}";
        }
        if ($this->offset) {
            $q .= " OFFSET {$this->offset}";
        }
        if ($this->procedure) {
            $q .= " PROCEDURE {$this->procedure}";
        }
        if ($this->into) {
            $q .= " INTO {$this->into}";
        }
        if ($this->for_update) {
            $q .= " FOR UPDATE";
        }
        if ($this->lock_in_share_mode) {
            $q .= " LOCK IN SHARE MODE";
        }
        return $this->connection->queryAssoc($q, $this->params);
    }

function show(req, res, next) {
  db.tags.find(req.params.tag, function(err, tag) {
    if(err) { return next(err); }
    res.json(tag);
  });
}

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


Question:
Mark a job as Completed, removing it from the queue.

@param \Queue\Model\Entity\QueuedJob $job Job
@return bool Success

public function markJobDone(QueuedJob $job) {
		$fields = [
			'completed' => $this->getDateTime(),
		];
		$job = $this->patchEntity($job, $fields);

		return (bool)$this->save($job);
	}

protected function enqueueDeployment() {
		$environment = $this->Environment();
		$project = $environment->Project();
		$log = $this->log();

		$args = array(
			'environmentName' => $environment->Name,
			'sha' => $this->SHA,
			'repository' => $project->LocalCVSPath,
			'logfile' => $this->logfile(),
			'projectName' => $project->Name,
			'env' => $project->getProcessEnv(),
			'deploymentID' => $this->ID,
			'leaveMaintenacePage' => $this->LeaveMaintenacePage
		);

		if(!$this->DeployerID) {
			$this->DeployerID = Member::currentUserID();
		}

		if($this->DeployerID) {
			$deployer = $this->Deployer();
			$message = sprintf(
				'Deploy to %s initiated by %s (%s), with IP address %s',
				$environment->getFullName(),
				$deployer->getName(),
				$deployer->Email,
				Controller::curr()->getRequest()->getIP()
			);
			$log->write($message);
		}

		return Resque::enqueue('deploy', 'DeployJob', $args, true);
	}

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


Question:
将键值对加入到值为List类型的Map中

@param params 参数
@param name key
@param value value
@param charset 编码

private static void addParam(Map<String, List<String>> params, String name, String value, String charset) {
		name = URLUtil.decode(name, charset);
		value = URLUtil.decode(value, charset);
		List<String> values = params.get(name);
		if (values == null) {
			values = new ArrayList<String>(1); // 一般是一个参数
			params.put(name, values);
		}
		values.add(value);
	}

private Dimension[] parseResolutions(Pad pad) {

		Caps caps = pad.getCaps();

		format = findPreferredFormat(caps);

		LOG.debug("Best format is {}", format);

		Dimension r = null;
		Structure s = null;
		String mime = null;

		final int n = caps.size();
		int i = 0;

		Map<String, Dimension> map = new HashMap<String, Dimension>();

		do {

			s = caps.getStructure(i++);

			LOG.debug("Found format structure {}", s);

			mime = s.getName();

			if (mime.equals(format)) {
				if ((r = capStructToResolution(s)) != null) {
					map.put(r.width + "x" + r.height, r);
				}
			}

		} while (i < n);

		final Dimension[] resolutions = new ArrayList<Dimension>(map.values()).toArray(new Dimension[0]);

		if (LOG.isDebugEnabled()) {
			for (Dimension d : resolutions) {
				LOG.debug("Resolution detected {} with format {}", d, format);
			}
		}

		return resolutions;
	}

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