Question:
Private method to automatically initialize the snapshot
        when you try to use it without calling any of the scan_*
        methods first. You don't need to call this yourself.

def __initialize_snapshot(self):

        if not self.__processDict:
            try:
                self.scan_processes()       # remote desktop api (relative fn)
            except Exception:
                self.scan_processes_fast()  # psapi (no filenames)
            self.scan_process_filenames()

def manipulate(self, stored_instance, component_instance):

        # Store the stored instance...
        self._ipopo_instance = stored_instance

        # ... and the bundle context
        self._context = stored_instance.bundle_context

        # Set the default value for the field: an empty dictionary
        setattr(component_instance, self._field, {})

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


Question:
新建一个List

@param <T> 集合元素类型
@param isLinked 是否新建LinkedList
@param collection 集合
@return List对象
@since 4.1.2

public static <T> List<T> list(boolean isLinked, Collection<T> collection) {
		if (null == collection) {
			return list(isLinked);
		}
		return isLinked ? new LinkedList<T>(collection) : new ArrayList<T>(collection);
	}

public final hqlParser.groupByClause_return groupByClause() throws RecognitionException {
		hqlParser.groupByClause_return retval = new hqlParser.groupByClause_return();
		retval.start = input.LT(1);

		CommonTree root_0 = null;

		Token GROUP121=null;
		Token string_literal122=null;
		Token COMMA124=null;
		ParserRuleReturnScope expression123 =null;
		ParserRuleReturnScope expression125 =null;

		CommonTree GROUP121_tree=null;
		CommonTree string_literal122_tree=null;
		CommonTree COMMA124_tree=null;

		try {
			// hql.g:331:2: ( GROUP ^ 'by' ! expression ( COMMA ! expression )* )
			// hql.g:331:4: GROUP ^ 'by' ! expression ( COMMA ! expression )*
			{
			root_0 = (CommonTree)adaptor.nil();

			GROUP121=(Token)match(input,GROUP,FOLLOW_GROUP_in_groupByClause1573);
			GROUP121_tree = (CommonTree)adaptor.create(GROUP121);
			root_0 = (CommonTree)adaptor.becomeRoot(GROUP121_tree, root_0);

			string_literal122=(Token)match(input,LITERAL_by,FOLLOW_LITERAL_by_in_groupByClause1579);
			pushFollow(FOLLOW_expression_in_groupByClause1582);
			expression123=expression();
			state._fsp--;

			adaptor.addChild(root_0, expression123.getTree());

			// hql.g:332:20: ( COMMA ! expression )*
			loop39:
			while (true) {
				int alt39=2;
				int LA39_0 = input.LA(1);
				if ( (LA39_0==COMMA) ) {
					alt39=1;
				}

				switch (alt39) {
				case 1 :
					// hql.g:332:22: COMMA ! expression
					{
					COMMA124=(Token)match(input,COMMA,FOLLOW_COMMA_in_groupByClause1586);
					pushFollow(FOLLOW_expression_in_groupByClause1589);
					expression125=expression();
					state._fsp--;

					adaptor.addChild(root_0, expression125.getTree());

					}
					break;

				default :
					break loop39;
				}
			}

			}

			retval.stop = input.LT(-1);

			retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
			adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
			retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
		}
		finally {
			// do for sure before leaving
		}
		return retval;
	}

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


Question:
Sets whether to show markers for this series in the JS Writer
@param bool $bool
@return \Altamira\Series provides fluent interface

public function showMarker( $bool = true )
	{
	    if ( $this->jsWriter instanceOf \Altamira\JsWriter\Ability\Lineable ) {
	        $this->jsWriter->setSeriesShowMarker( $this->getTitle(), $bool );
	    }
	    return $this;
	}

function (name, value) {
        var self = this, elm = self.getEl(self.ariaTarget);

        if (typeof value === "undefined") {
          return self._aria[name];
        }

        self._aria[name] = value;

        if (self.state.get('rendered')) {
          elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
        }

        return self;
      }

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


Question:
Execute the console command.

@return bool|null

public function fire()
    {
        $entityName      = $this->parseName($this->argument('name'));
        $pieces          = explode('\\', $entityName);
        $entityShortName = array_pop($pieces);

        $this->appNamespace        = $this->laravel->getNamespace();
        $this->entityNamespace     = implode('\\', $pieces);
        $this->contractNamespace   = $this->appNamespace . 'Contracts\Repository';
        $this->repositoryNamespace = $this->appNamespace . 'Repositories';

        $repoName         = $entityShortName . 'Repository';
        $repoAppEntity    = $this->appNamespace . 'Support\AppEntityRepository';
        $repoContractName = sprintf('%s\%s', $this->contractNamespace, $repoName);
        $repoConcreteName = sprintf('%s\%s', $this->repositoryNamespace, $repoName);

        $traits     = new Collection();
        $interfaces = new Collection();

        $this->buildBehaviourOptions($traits, $interfaces);

        $this->createFile($entityName, $this->entityClassStub($entityShortName, $interfaces, $traits));

        if ($this->option('repository')) {
            $this->createFile($repoAppEntity,    $this->appRepositoryClassStub());
            $this->createFile($repoConcreteName, $this->repositoryClassStub($repoName));
            $this->createFile($repoContractName, $this->repositoryInterfaceStub($repoName));
        }

        return 0;
    }

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

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

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


Question:
Stores the extrinsic state information for the given component.

@param component the component to set the model for.
@param model the model to set.

@Override
	public void setModel(final WebComponent component, final WebModel model) {
		map.put(component, model);
	}

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

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


Question:
Add an iterator in the list of iterators.

@param iterator the iterator.

public void addIterator(SizedIterator<? extends M> iterator) {
		if (this.iterators.add(iterator)) {
			this.total += iterator.totalSize();
			this.update = true;
		}
	}

def view_aterator(connection, callback, view, view_keys=dict(),
                  args=tuple(), kwargs=dict(), per_page=15,
                  consume_errors=True):
    '''

    '''
    skip = 0
    while True:
        keys = dict(view_keys)
        keys.update(dict(skip=skip, limit=per_page))
        records = yield connection.query_view(view, **keys)
        log.debug('view_aterator', "Fetched %d records of the view: %s",
                  len(records), view.name)
        skip += len(records)
        for record in records:
            try:
                yield callback(connection, record, *args, **kwargs)
            except Exception as e:
                error.handle_exception(
                    'view_aterator', e,
                    "Callback %s failed its iteration on a row %r",
                    callback.__name__, record)
                if not consume_errors:
                    raise e

        if not records:
            break

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


Question: // Convert_network_ClusterNetworkEntry_To_v1_ClusterNetworkEntry is an autogenerated conversion function.

func Convert_network_ClusterNetworkEntry_To_v1_ClusterNetworkEntry(in *network.ClusterNetworkEntry, out *v1.ClusterNetworkEntry, s conversion.Scope) error {
	return autoConvert_network_ClusterNetworkEntry_To_v1_ClusterNetworkEntry(in, out, s)
}

def coerce_value(
    value: Any, type_: GraphQLInputType, blame_node: Node = None, path: Path = None
) -> CoercedValue:

    # A value must be provided if the type is non-null.
    if is_non_null_type(type_):
        if value is None or value is INVALID:
            return of_errors(
                [
                    coercion_error(
                        f"Expected non-nullable type {type_} not to be null",
                        blame_node,
                        path,
                    )
                ]
            )
        type_ = cast(GraphQLNonNull, type_)
        return coerce_value(value, type_.of_type, blame_node, path)

    if value is None or value is INVALID:
        # Explicitly return the value null.
        return of_value(None)

    if is_scalar_type(type_):
        # Scalars determine if a value is valid via `parse_value()`, which can throw to
        # indicate failure. If it throws, maintain a reference to the original error.
        type_ = cast(GraphQLScalarType, type_)
        try:
            parse_result = type_.parse_value(value)
            if is_invalid(parse_result):
                return of_errors(
                    [coercion_error(f"Expected type {type_.name}", blame_node, path)]
                )
            return of_value(parse_result)
        except (TypeError, ValueError) as error:
            return of_errors(
                [
                    coercion_error(
                        f"Expected type {type_.name}",
                        blame_node,
                        path,
                        str(error),
                        error,
                    )
                ]
            )

    if is_enum_type(type_):
        type_ = cast(GraphQLEnumType, type_)
        values = type_.values
        if isinstance(value, str):
            enum_value = values.get(value)
            if enum_value:
                return of_value(value if enum_value.value is None else enum_value.value)
        suggestions = suggestion_list(str(value), values)
        did_you_mean = f"did you mean {or_list(suggestions)}?" if suggestions else None
        return of_errors(
            [
                coercion_error(
                    f"Expected type {type_.name}", blame_node, path, did_you_mean
                )
            ]
        )

    if is_list_type(type_):
        type_ = cast(GraphQLList, type_)
        item_type = type_.of_type
        if isinstance(value, Iterable) and not isinstance(value, str):
            errors = None
            coerced_value_list: List[Any] = []
            append_item = coerced_value_list.append
            for index, item_value in enumerate(value):
                coerced_item = coerce_value(
                    item_value, item_type, blame_node, at_path(path, index)
                )
                if coerced_item.errors:
                    errors = add(errors, *coerced_item.errors)
                elif not errors:
                    append_item(coerced_item.value)
            return of_errors(errors) if errors else of_value(coerced_value_list)
        # Lists accept a non-list value as a list of one.
        coerced_item = coerce_value(value, item_type, blame_node)
        return coerced_item if coerced_item.errors else of_value([coerced_item.value])

    if is_input_object_type(type_):
        type_ = cast(GraphQLInputObjectType, type_)
        if not isinstance(value, dict):
            return of_errors(
                [
                    coercion_error(
                        f"Expected type {type_.name} to be a dict", blame_node, path
                    )
                ]
            )
        errors = None
        coerced_value_dict: Dict[str, Any] = {}
        fields = type_.fields

        # Ensure every defined field is valid.
        for field_name, field in fields.items():
            field_value = value.get(field_name, INVALID)
            if is_invalid(field_value):
                if not is_invalid(field.default_value):
                    coerced_value_dict[field_name] = field.default_value
                elif is_non_null_type(field.type):
                    errors = add(
                        errors,
                        coercion_error(
                            f"Field {print_path(at_path(path, field_name))}"
                            f" of required type {field.type} was not provided",
                            blame_node,
                        ),
                    )
            else:
                coerced_field = coerce_value(
                    field_value, field.type, blame_node, at_path(path, field_name)
                )
                if coerced_field.errors:
                    errors = add(errors, *coerced_field.errors)
                else:
                    coerced_value_dict[field_name] = coerced_field.value

        # Ensure every provided field is defined.
        for field_name in value:
            if field_name not in fields:
                suggestions = suggestion_list(field_name, fields)
                did_you_mean = (
                    f"did you mean {or_list(suggestions)}?" if suggestions else None
                )
                errors = add(
                    errors,
                    coercion_error(
                        f"Field '{field_name}' is not defined by type {type_.name}",
                        blame_node,
                        path,
                        did_you_mean,
                    ),
                )

        return of_errors(errors) if errors else of_value(coerced_value_dict)

    # Not reachable. All possible input types have been considered.
    raise TypeError(f"Unexpected input type: '{inspect(type_)}'.")

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


Question: Reads and returns single batch from the datastore.

def read_batch_from_datastore(self, class_batch_id):
    """"""
    client = self._datastore_client
    key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id)
    result = client.get(key)
    if result is not None:
      return dict(result)
    else:
      raise KeyError(
          'Key {0} not found in the datastore'.format(key.flat_path))

func (c *Config) defaults() {
	if c.Client == nil {
		c.Client = k.New(session.New(aws.NewConfig()))
	}

	if c.Logger == nil {
		c.Logger = log.Log
	}

	c.Logger = c.Logger.WithFields(log.Fields{
		"package": "kinesis",
	})

	if c.StreamName == "" {
		c.Logger.Fatal("StreamName required")
	}

	c.Logger = c.Logger.WithFields(log.Fields{
		"stream": c.StreamName,
	})

	if c.BufferSize == 0 {
		c.BufferSize = maxRecordsPerRequest
	}

	if c.BufferSize > maxRecordsPerRequest {
		c.Logger.Fatal("BufferSize exceeds 500")
	}

	if c.BacklogSize == 0 {
		c.BacklogSize = maxRecordsPerRequest
	}

	if c.FlushInterval == 0 {
		c.FlushInterval = time.Second
	}
}

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


Question: // Update document struct from self-contained document link

func (d *Document) Update(ctx context.Context) APIResponse {
	newDoc, resp := d.client.Get(ctx, d.Links.Document, d.Owner)

	if resp.Error != nil {
		return resp
	}

	*d = *newDoc

	return apiResponse("update completed", d.ID, resp.HttpResponse, nil)
}

public function enterNode(Node $node)
    {
        if ($node instanceof Namespace_) {
            $this->resetContext($node->name);
        }

        $this->recordDoc($node->getAttribute('comments', []));

        return $node;
    }

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


Question:
Invalidate all memory cached images for the specified {@code uri}.

@see #invalidate(String)
@see #invalidate(File)

public void invalidate(@Nullable Uri uri) {
    if (uri != null) {
      cache.clearKeyUri(uri.toString());
    }
  }

def _render_filenames(filenames, zip_file, saltenv, template):
    '''

    '''
    if not template:
        return (filenames, zip_file)

    # render the path as a template using path_template_engine as the engine
    if template not in salt.utils.templates.TEMPLATE_REGISTRY:
        raise CommandExecutionError(
            'Attempted to render file paths with unavailable engine '
            '{0}'.format(template)
        )

    kwargs = {}
    kwargs['salt'] = __salt__
    kwargs['pillar'] = __pillar__
    kwargs['grains'] = __grains__
    kwargs['opts'] = __opts__
    kwargs['saltenv'] = saltenv

    def _render(contents):
        '''
        Render :param:`contents` into a literal pathname by writing it to a
        temp file, rendering that file, and returning the result.
        '''
        # write out path to temp file
        tmp_path_fn = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(contents))
        data = salt.utils.templates.TEMPLATE_REGISTRY[template](
            tmp_path_fn,
            to_str=True,
            **kwargs
        )
        salt.utils.files.safe_rm(tmp_path_fn)
        if not data['result']:
            # Failed to render the template
            raise CommandExecutionError(
                'Failed to render file path with error: {0}'.format(
                    data['data']
                )
            )
        else:
            return data['data']

    filenames = _render(filenames)
    zip_file = _render(zip_file)
    return (filenames, zip_file)

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


Question: // DispatchConsensus provides a mock function with given fields: ctx, request

func (_m *Dispatcher) DispatchConsensus(ctx context.Context, request *orderer.ConsensusRequest) error {
	ret := _m.Called(ctx, request)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, *orderer.ConsensusRequest) error); ok {
		r0 = rf(ctx, request)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

func (mc MongoClient) getDeviceProfiles(q bson.M) ([]contract.DeviceProfile, error) {
	s := mc.session.Copy()
	defer s.Close()

	var dps []models.DeviceProfile
	err := s.DB(mc.database.Name).C(db.DeviceProfile).Find(q).Sort("queryts").All(&dps)
	if err != nil {
		return []contract.DeviceProfile{}, errorMap(err)
	}

	cdps := make([]contract.DeviceProfile, 0)
	for _, dp := range dps {
		c, err := dp.ToContract(mc)
		if err != nil {
			return []contract.DeviceProfile{}, err
		}
		cdps = append(cdps, c)
	}
	return cdps, nil
}

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


Question:
Look for source or sources in the model that match the
        given source.  Sources are matched by name and any association
        columns defined in the assoc_xmatch_columns parameter.

def match_source(self, src):

        srcs = []

        names = [src.name]
        for col in self.config['assoc_xmatch_columns']:
            if col in src.assoc and src.assoc[col]:
                names += [src.assoc[col]]

        for name in names:
            name = name.replace(' ', '').lower()
            if name not in self._src_dict:
                continue
            srcs += [s for s in self._src_dict[name] if s not in srcs]

        return srcs

protected function addRefFKInit(&$script, ForeignKey $refFK)
    {
        $relCol = $this->getRefFKPhpNameAffix($refFK, true);
        $collName = $this->getRefFKCollVarName($refFK);

        $script .= "
    /**
     * Initializes the $collName collection.
     *
     * By default this just sets the $collName collection to an empty array (like clear$collName());
     * however, you may wish to override this method in your stub class to provide setting appropriate
     * to your application -- for example, setting the initial array to the values stored in database.
     *
     * @param      boolean \$overrideExisting If set to true, the method call initializes
     *                                        the collection even if it is not empty
     *
     * @return void
     */
    public function init$relCol(\$overrideExisting = true)
    {
        if (null !== \$this->$collName && !\$overrideExisting) {
            return;
        }

        \$collectionClassName = ".$this->getClassNameFromBuilder($this->getNewTableMapBuilder($refFK->getTable()))."::getTableMap()->getCollectionClassName();

        \$this->{$collName} = new \$collectionClassName;
        \$this->{$collName}->setModel('" . $this->getClassNameFromBuilder($this->getNewStubObjectBuilder($refFK->getTable()), true) . "');
    }
";
    }

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


Question: // Info for an organization app.

func (s *Service) OrganizationAppInfo(ctx context.Context, organizationAppIdentity string) (*OrganizationApp, error) {
	var organizationApp OrganizationApp
	return &organizationApp, s.Get(ctx, &organizationApp, fmt.Sprintf("/organizations/apps/%v", organizationAppIdentity), nil, nil)
}

func NewPaperFolderTeamInviteType(Description string) *PaperFolderTeamInviteType {
	s := new(PaperFolderTeamInviteType)
	s.Description = Description
	return s
}

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


Question: Create an instance of {@link JAXBElement }{@code <}{@link QualifiedSpecializationOf }{@code >}}

@XmlElementDecl(namespace = PROV_EXT_NS, name = "specializationOf")
    public JAXBElement<QualifiedSpecializationOf> createQualifiedSpecializationOf(QualifiedSpecializationOf value) {
        return new JAXBElement<QualifiedSpecializationOf>(_QualifiedSpecializationOf_QNAME, QualifiedSpecializationOf.class, null, value);
    }

def proxy_label_for(label: str) -> str:

        label_java = _VertexLabel(label).unwrap()
        proxy_label_java = k.jvm_view().SequenceBuilder.proxyLabelFor(label_java)
        return proxy_label_java.getQualifiedName()

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


Question: TODO should do this at parse time.

private String[] extractHeaderList(String headerList, int prefixLen) {
        // Remove the trailing and leading ')('
        String tmp = headerList.substring(prefixLen + 1, headerList.length() - 1);
        return split(tmp, " ");
    }

def make_ready_all(self):

        T = self.tm.trace
        if T: T.write(self.trace_message('Task.make_ready_all()', self.node))

        self.out_of_date = self.targets[:]
        for t in self.targets:
            t.disambiguate().set_state(NODE_EXECUTING)
            for s in t.side_effects:
                # add disambiguate here to mirror the call on targets above
                s.disambiguate().set_state(NODE_EXECUTING)

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


Question:
Return a collections.Sized collections.Container of paths to be
        excluded for single_version_externally_managed installations.

def get_exclusions(self):

        all_packages = (
            pkg
            for ns_pkg in self._get_SVEM_NSPs()
            for pkg in self._all_packages(ns_pkg)
        )

        excl_specs = product(all_packages, self._gen_exclusion_paths())
        return set(starmap(self._exclude_pkg_path, excl_specs))

public function setupEnvironment($basePath, $application = 'site')
	{
		if ($application != 'site')
		{
			$basePath .= '/' . $application;
		}

		$server  = array(
			'HTTP_HOST'       => 'undefined',
			'HTTP_USER_AGENT' => 'undefined',
			'REQUEST_METHOD'  => 'GET',
		);
		$_SERVER = array_merge($_SERVER, $server);

		define('JPATH_BASE', $basePath);
		define('DS', DIRECTORY_SEPARATOR);

		require_once JPATH_BASE . '/includes/defines.php';
		require_once JPATH_LIBRARIES . '/loader.php';

		spl_autoload_register('__autoload');

		require_once JPATH_BASE . '/includes/framework.php';

		if ($application == 'administrator')
		{
			require_once JPATH_BASE . '/includes/helper.php';
			require_once JPATH_BASE . '/includes/toolbar.php';

			// JUri uses $_SERVER['HTTP_HOST'] without check
			$_SERVER['HTTP_HOST'] = 'CLI';
		}

		jimport('joomla.installer.installer');
		jimport('joomla.installer.helper');

		$mainframe = \JFactory::getApplication($application);
		$mainframe->initialise();
	}

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


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

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

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

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

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

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

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

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

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

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


Question: // SetNextToken sets the NextToken field's value.

func (s *DescribeRepositoriesInput) SetNextToken(v string) *DescribeRepositoriesInput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
:param cinfo: a :class:`openquake.commonlib.source.CompositionInfo`
    :param sm_lt_path: logic tree path tuple used to select a source model
    :param trts: tectonic region types to accept

def get_rlzs_assoc(cinfo, sm_lt_path=None, trts=None):

    assoc = RlzsAssoc(cinfo)
    offset = 0
    trtset = set(cinfo.gsim_lt.values)
    for smodel in cinfo.source_models:
        # discard source models with non-acceptable lt_path
        if sm_lt_path and not accept_path(smodel.path, sm_lt_path):
            continue

        # collect the effective tectonic region types and ruptures
        trts_ = set()
        for sg in smodel.src_groups:
            if sg.eff_ruptures:
                if (trts and sg.trt in trts) or not trts:
                    trts_.add(sg.trt)

        # recompute the GSIM logic tree if needed
        if trts_ != {'*'} and trtset != trts_:
            before = cinfo.gsim_lt.get_num_paths()
            gsim_lt = cinfo.gsim_lt.reduce(trts_)
            after = gsim_lt.get_num_paths()
            if sm_lt_path and before > after:
                # print the warning only when saving the logic tree,
                # i.e. when called with sm_lt_path in store_rlz_info
                logging.warning('Reducing the logic tree of %s from %d to %d '
                                'realizations', smodel.name, before, after)
            gsim_rlzs = list(gsim_lt)
            all_trts = list(gsim_lt.values)
        else:
            gsim_rlzs = list(cinfo.gsim_lt)
            all_trts = list(cinfo.gsim_lt.values)

        rlzs = cinfo._get_rlzs(smodel, gsim_rlzs, cinfo.seed + offset)
        assoc._add_realizations(offset, smodel, all_trts, rlzs)
        offset += len(rlzs)

    if assoc.realizations:
        assoc._init()
    return assoc

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question: // SetForward sets the Forward field's value.

func (s *CookiePreference) SetForward(v string) *CookiePreference {
	s.Forward = &v
	return s
}

def getUpdated(self, sObjectType, startDate, endDate):
    '''

    '''
    self._setHeaders('getUpdated')
    return self._sforce.service.getUpdated(sObjectType, startDate, endDate)

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


Question: Translate string into another language using the (ReporticoApp::get("translations")) array

static function &translate($in_string)
    {
        $out_string = &$in_string;

        $langage = ReporticoApp::getConfig("language");
        $translations = ReporticoApp::get("translations");

        if ($translations) {
            if (array_key_exists($langage, $translations)) {
                $langset = &$translations[$langage];
                if (isset($langset[$in_string])) {
                    $out_string = &$langset[$in_string];
                }

            }
        }

        return $out_string;
    }

public function detranslify($inString)
    {
        $dirtyResult = str_replace(self::$_EN_ALPHABET, self::$_RU_ALPHABET, $inString);
        return preg_replace(self::$_CORRECTION_PATTERN, self::$_CORRECTION_REPLACEMENT, $dirtyResult);
    }

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


Question:
/*
Iterate over the list of components

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

public tbody tbody(int index) {
        while (tbodyList.size() <= index) {
            tbodyList.add(new tbody());
        }
        return tbodyList.get(index);
    }

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


Question:
Get joined settings data by $name or null if $name not exists in joined settings array

@param string $name
@param null|string $key
@return mixed

public function getSettingJoined($name, $key = null)
	{
		if( debug_assert($this->settingExistsJoined($name),'Tried to retrieve not existing joined setting.') )
		{
			if($key)
			{
				if(isset($this->_settingsJoined[$name][$key]))
				{
					return $this->_settingsJoined[$name][$key];
				}
			}
			else
			{
				return $this->_settingsJoined[$name];
			}
		}
		return null;
	}

private void parseSQLConfig(final Node node, final ConfigSettings config)
	{

		String name, value;
		Node nnode;
		NodeList list = node.getChildNodes();

		int length = list.getLength();
		for (int i = 0; i < length; i++) {
			nnode = list.item(i);

			name = nnode.getNodeName().toUpperCase();
			if (name.equals(KEY_HOST)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_HOST, value);

			}
			else if (name.equals(KEY_DATABASE)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_DATABASE, value);

			}
			else if (name.equals(KEY_USER)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_USERNAME, value);

			}
			else if (name.equals(KEY_PASSWORD)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_PASSWORD, value);
			}
		}
	}

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


Question:
Adds the inputed logger to the list of loggers that are being tracked
        with this widget.

        :param      logger | <logging.Logger> || <str>
                    level  | <logging.LEVEL>

def addLogger(self, logger, level=logging.INFO):

        if isinstance(logger, logging.Logger):
            logger = logger.name

        if logger in self._loggers:
            return

        # allow the handler to determine the level for this logger
        if logger == 'root':
            _log = logging.getLogger()
        else:
            _log = logging.getLogger(logger)

        _log.addHandler(self.handler())

        self._loggers.add(logger)
        self.handler().setLoggerLevel(logger, level)

def show_raslog_output_show_all_raslog_raslog_entries_severity(self, **kwargs):

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

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

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


Question:
Generates HTML markup for a single line of code while determining alternating line style.
@param {Integer} lineNumber	Line number.
@param {String} code Line	HTML markup.
@return {String}				Returns HTML markup.

function(lineIndex, lineNumber, code)
        {
            var classes = [
                'line',
                'number' + lineNumber,
                'index' + lineIndex,
                'alt' + (lineNumber % 2 == 0 ? 1 : 2).toString()
            ];

            if (this.isLineHighlighted(lineNumber))
                classes.push('highlighted');

            if (lineNumber == 0)
                classes.push('break');

            return '
' + code + '
';
        }

private void parseTemplate() {
    /*
     * query string and path literals have different reserved characters and different encoding
     * requirements. to ensure compliance with RFC 6570, we'll need to encode query literals
     * differently from path literals. let's look at the template to see if it contains a query
     * string and if so, keep track of where it starts.
     */
    Matcher queryStringMatcher = QUERY_STRING_PATTERN.matcher(this.template);
    if (queryStringMatcher.find()) {
      /*
       * the template contains a query string, split the template into two parts, the path and query
       */
      String path = this.template.substring(0, queryStringMatcher.start());
      String query = this.template.substring(queryStringMatcher.end() - 1);
      this.parseFragment(path, false);
      this.parseFragment(query, true);
    } else {
      /* parse the entire template */
      this.parseFragment(this.template, false);
    }
  }

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


Question:
Populates the entity identifier of an entity.

@param object  $entity
@param mixed[] $id

public function setIdentifier($entity, array $id) : void
    {
        foreach ($id as $idField => $idValue) {
            $property = $this->class->getProperty($idField);

            $property->setValue($entity, $idValue);
        }
    }

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

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

        $generator->startList('Tag');

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

        $generator->endList('Tag');

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

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


Question: Get the snapshot of the configuration from the configuration manager

private void snapshotConfig() {
    maximum = configManager.getPoolGroupMaximum(getName(), getType());
    minimum = configManager.getPoolGroupMinimum(getName(), getType());
  }

private function assertArray($key, $value)
    {
        if (!is_array($value)) {
            throw new InvalidConfigException(sprintf(
                'The config key "%s" must be an array. Got: %s',
                $key,
                is_object($value) ? get_class($value) : gettype($value)
            ));
        }
    }

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


Question:
// ChangeAgentTools does the actual agent upgrade.
// It should be called just before an agent exits, so that
// it will restart running the new tools.

func (e *UpgradeReadyError) ChangeAgentTools() error {
	agentTools, err := tools.ChangeAgentTools(e.DataDir, e.AgentName, e.NewTools)
	if err != nil {
		return err
	}
	logger.Infof("upgraded from %v to %v (%q)", e.OldTools, agentTools.Version, agentTools.URL)
	return nil
}

def _update_service_profile(self, handle, service_profile,
                                vlan_id, ucsm_ip):

        virtio_port_list = (
            CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].ucsm_virtio_eth_ports)

        eth_port_paths = ["%s%s" % (service_profile, ep)
            for ep in virtio_port_list]

        vlan_name = self.make_vlan_name(vlan_id)

        try:
            obj = handle.query_dn(service_profile)

            if not obj:
                LOG.debug('UCS Manager network driver could not find '
                          'Service Profile %s in UCSM %s',
                          service_profile, ucsm_ip)
                return False

            for eth_port_path in eth_port_paths:
                eth = handle.query_dn(eth_port_path)

                if eth:
                    eth_if = self.ucsmsdk.vnicEtherIf(
                        parent_mo_or_dn=eth,
                        name=vlan_name,
                        default_net="no")

                    handle.add_mo(eth_if)

                    if not eth_if:
                        LOG.debug('UCS Manager network driver could not '
                                  'update Service Profile %s with vlan %d',
                                  service_profile, vlan_id)
                        return False
                else:
                    LOG.debug('UCS Manager network driver did not find '
                              'ethernet port at %s', eth_port_path)

            handle.commit()
            return True

        except Exception as e:
            return self._handle_ucsm_exception(e, 'Service Profile',
                                               vlan_name, ucsm_ip)

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


Question:
@param array|string[]|string $command

@return $this

public function addCommand($command)
    {
        if (is_array($command)) {
            foreach ($command as $cmd) {
                $this->addCommand($cmd);
            }
        }

        if (is_string($command)) {
            $command = new Command($command);
            $this->commandsList[] = $command;
        }

        return $this;
    }

private PrepareResult executeBatchStandard(int estimatedParameterCount) throws SQLException {
    int totalExecutionNumber = getTotalExecutionNumber();
    SQLException exception = null;
    BulkStatus status = new BulkStatus();

    ComStmtPrepare comStmtPrepare = null;
    FutureTask<AsyncMultiReadResult> futureReadTask = null;

    int requestNumberByBulk;
    int paramCount = estimatedParameterCount;
    try {
      do {
        status.sendEnded = false;
        status.sendSubCmdCounter = 0;
        requestNumberByBulk = Math.min(totalExecutionNumber - status.sendCmdCounter,
            protocol.getOptions().useBatchMultiSendNumber);
        protocol.changeSocketTcpNoDelay(false); //enable NAGLE algorithm temporary.

        //add prepare sub-command
        if (readPrepareStmtResult && prepareResult == null) {

          comStmtPrepare = new ComStmtPrepare(protocol, sql);
          comStmtPrepare.send(writer);

          //read prepare result
          prepareResult = comStmtPrepare.read(protocol.getReader(), protocol.isEofDeprecated());
          statementId = ((ServerPrepareResult) prepareResult).getStatementId();
          paramCount = getParamCount();
        }

        boolean useCurrentThread = false;

        for (; status.sendSubCmdCounter < requestNumberByBulk; ) {
          sendCmd(writer, results, parametersList, queries, paramCount, status, prepareResult);
          status.sendSubCmdCounter++;
          status.sendCmdCounter++;
          if (useCurrentThread) {
            try {
              protocol.getResult(results);
            } catch (SQLException qex) {
              if (((readPrepareStmtResult && prepareResult == null) || !protocol
                  .getOptions().continueBatchOnError)) {
                throw qex;
              } else {
                exception = qex;
              }
            }
          } else if (futureReadTask == null) {
            try {
              futureReadTask = new FutureTask<>(new AsyncMultiRead(comStmtPrepare, status,
                  protocol, false, this, paramCount,
                  results, parametersList, queries, prepareResult));
              AbstractQueryProtocol.readScheduler.execute(futureReadTask);
            } catch (RejectedExecutionException r) {
              useCurrentThread = true;
              try {
                protocol.getResult(results);
              } catch (SQLException qex) {
                if (((readPrepareStmtResult && prepareResult == null) || !protocol
                    .getOptions().continueBatchOnError)) {
                  throw qex;
                } else {
                  exception = qex;
                }
              }
            }
          }
        }

        status.sendEnded = true;
        if (!useCurrentThread) {
          protocol.changeSocketTcpNoDelay(protocol.getOptions().tcpNoDelay);
          try {
            AsyncMultiReadResult asyncMultiReadResult = futureReadTask.get();

            if (binaryProtocol && prepareResult == null
                && asyncMultiReadResult.getPrepareResult() != null) {
              prepareResult = asyncMultiReadResult.getPrepareResult();
              statementId = ((ServerPrepareResult) prepareResult).getStatementId();
              paramCount = prepareResult.getParamCount();
            }

            if (asyncMultiReadResult.getException() != null) {
              if (((readPrepareStmtResult && prepareResult == null) || !protocol
                  .getOptions().continueBatchOnError)) {
                throw asyncMultiReadResult.getException();
              } else {
                exception = asyncMultiReadResult.getException();
              }
            }
          } catch (ExecutionException executionException) {
            if (executionException.getCause() == null) {
              throw new SQLException("Error reading results " + executionException.getMessage());
            }
            throw new SQLException(
                "Error reading results " + executionException.getCause().getMessage());
          } catch (InterruptedException interruptedException) {
            protocol.setActiveFutureTask(futureReadTask);
            Thread.currentThread().interrupt();
            throw new SQLException("Interrupted awaiting response ",
                INTERRUPTED_EXCEPTION.getSqlState(), interruptedException);
          } finally {
            //bulk can prepare, and so if prepare cache is enable, can replace an already cached prepareStatement
            //this permit to release those old prepared statement without conflict.
            protocol.forceReleaseWaitingPrepareStatement();
          }
        }

        if (protocol.isInterrupted()) {
          //interrupted during read, must throw an exception manually
          futureReadTask.cancel(true);
          throw new SQLTimeoutException("Timeout during batch execution");
        }
        futureReadTask = null;

      } while (status.sendCmdCounter < totalExecutionNumber);

      if (exception != null) {
        throw exception;
      }

      return prepareResult;

    } catch (IOException e) {
      status.sendEnded = true;
      status.sendCmdCounter = 0; //to ensure read doesn't hang
      throw protocol.handleIoException(e);
    }

  }

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


Question:
Unpublish a given server.

        If the server was not published, this method will not do anything.

        :param DAAPServer daap_server: DAAP Server instance to publish.

def unpublish(self, daap_server):

        if daap_server not in self.daap_servers:
            return

        self.zeroconf.unregister_service(self.daap_servers[daap_server])

        del self.daap_servers[daap_server]

def apply_module_defaults(args)
      args[:port] = args[:server].to_s.end_with?(JAMFCLOUD_DOMAIN) ? JAMFCLOUD_PORT : SSL_PORT if args[:no_port_specified]
      args[:timeout] ||= DFT_TIMEOUT
      args[:open_timeout] ||= DFT_OPEN_TIMEOUT
      args[:ssl_version] ||= DFT_SSL_VERSION
      args
    end

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


Question:
Add role
@param string  $role
@return object (self)

public function add($role)
    {
        $this->bucket[$role] = sprintf("%05d", $this->acl->getRoleLevel($role)) .'-'. $role;
        return $this;
    }

private function resolveAndAddType(JobTypeInterface $type)
    {
        $parentType = $type->getParent();

        if ($parentType instanceof JobTypeInterface) {
            $this->resolveAndAddType($parentType);
            $parentType = $parentType->getName();
        }

        $typeExtensions = array();

        foreach ($this->extensions as $extension) {
            /* @var FormExtensionInterface $extension */
            $typeExtensions = array_merge(
                $typeExtensions,
                $extension->getTypeExtensions($type->getName())
            );
        }

        $this->types[$type->getName()] = new ResolvedJob(
            $type,
            $typeExtensions,
            $parentType ? $this->getType($parentType) : null
        );
    }

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


Question:
Run the migrations.

@return void

public function up()
    {
        // only thing to change is the version number

        /** @var \LCI\Blend\Blendable\SystemSetting $systemSetting */
        $systemSetting = $this->blender->getBlendableLoader()->getBlendableSystemSetting('blend.version');
        $systemSetting
            ->setSeedsDir($this->getSeedsDir())
            ->setFieldValue('1.0.0 beta')
            ->setFieldArea('Blend')
            ->blend(true);

        foreach ($this->empty_settings as $key) {

            /** @var \LCI\Blend\Blendable\SystemSetting $systemSetting */
            $systemSetting = $this->blender->getBlendableLoader()->getBlendableSystemSetting($key);
            $systemSetting
                ->setSeedsDir($this->getSeedsDir())
                ->setFieldArea('Blend')
                ->blend(true);
        }

        $this->modx->cacheManager->refresh();
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

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


Question: Signals that a new segment should be activated.

final void signalActivateSegment() throws SQLException {

      /*
         Note that 'offer' does so only if it can be done
         immediately without exceeding the queue capacity.
         The queue capacity is '1', so this means that
         signals may be ignored. Either way, this message
         will never block.
       */

      if(segmentSignalQueue != null) {
         segmentSignalQueue.offer(ACTIVATE_SEGMENT_SIGNAL);
      } else if(activeSegments == 0) { //Single segment, no monitor, started with the one segment deactivated...
         synchronized(this) {
            if(activeSegments == 0) { //... and DCL works here because activeSegments is volatile.
               segments[0].activate();
               activeSegments = 1;
            }
         }
      }
   }

function PiGlow() {
    var that = this;

    this._wire = null;
    this._currentState = null;

    Emitter.call(this);

    this._initialize(function (error) {
        if (error) {
            that.emit('error', error);
        } else {
            that.emit('initialize');
        }
    });
}

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


Question:
format string to display to user. Uses #format_str if present,
 otherwise finds an i18n label from #format. Returns nil if none
 available.

def display_format
      value = self.format_str ||
        I18n.t(self.format, :scope => [:bento_search, :format], :default => self.format.to_s.titleize)

      return value.blank? ? nil : value
    end

def parse(date_time)
      raise(ISO8601::Errors::UnknownPattern, date_time) if date_time.empty?

      date, time = date_time.split('T')

      date_atoms = parse_date(date)
      time_atoms = Array(time && parse_time(time))
      separators = [date_atoms.pop, time_atoms.pop]

      raise(ISO8601::Errors::UnknownPattern, @original) unless valid_representation?(date_atoms, time_atoms)
      raise(ISO8601::Errors::UnknownPattern, @original) unless valid_separators?(separators)

      ::DateTime.new(*(date_atoms + time_atoms).compact)
    end

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


Question:
Update the creation and update timestamps.

@return void

protected function updateTimestamps()
    {
        $time = $this->freshTimestamp();

        if (! is_null($column = $this->getUpdatedAtColumn()) && ! $this->isDirty($column)) {
            $this->setAttribute($column, $time);
        }

        if (! $this->exists && ! is_null($column = $this->getCreatedAtColumn()) && ! $this->isDirty($column)) {
            $this->setAttribute($column, $time);
        }
    }

public function setByPosition($pos, $value)
    {
        switch ($pos) {
            case 0:
                $this->setId($value);
                break;
            case 1:
                $this->setFirstName($value);
                break;
            case 2:
                $this->setLastName($value);
                break;
            case 3:
                $this->setCreatedAt($value);
                break;
            case 4:
                $this->setUpdatedAt($value);
                break;
        } // switch()
    }

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


Question:
converts the given {@link Iterable} to a {@link List}

@param <P> the element type
@param as  the {@link Iterable}
@return the converted {@link List}

public final <P> List<P> convertIterable(Iterable<P> as) {
        List<P> objects = new ArrayList<>();
        for(P mp : as) {
            objects.add(mp);
        }
        return objects;
    }

public void detail(MethodNode methodNode, MethodAttributes attrs, StringBuilder output) {
        Validate.notNull(methodNode);
        Validate.notNull(attrs);
        Validate.notNull(output);

        int methodId = attrs.getSignature().getMethodId();

        output.append("Class Name: ").append(attrs.getSignature().getClassName().replace('/', '.')).append('\n');
        output.append("Method Name: ").append(attrs.getSignature().getMethodName()).append('\n');
        output.append("Method Params: ").append(attrs.getSignature().getMethodDescriptor()).append('\n');
        output.append("Method Return: ").append(attrs.getSignature().getReturnType()).append('\n');
        output.append("Method ID: ").append(methodId).append('\n');
        output.append("------------------------------------\n");

        UnmodifiableList<ContinuationPoint> cps = attrs.getContinuationPoints();
        for (int i = 0; i < cps.size(); i++) {
            ContinuationPoint cp = cps.get(i);

            int line = cp.getLineNumber() == null ? -1 : cp.getLineNumber();
            String header = String.format("Continuation Point ID: %-4d Line: %-4d Type: %s",
                    i,
                    line,
                    cp.getClass().getSimpleName());
            output.append(header).append('\n');

            // Check out PackStateGenerators class for how things are organized. Brief overview follows...
            // container[0] has local variables that are bytes/shorts/ints
            // container[1] has local variables that are floats
            // container[2] has local variables that are longs
            // container[3] has local variables that are doubles
            // container[4] has local variables that are Objects
            // container[5] has operands that are bytes/shorts/ints
            // container[6] has operands that are floats
            // container[7] has operands that are longs
            // container[8] has operands that are doubles
            // container[9] has operands that are Objects
            detailLocals(cp, methodNode, output);
            detailOperands(cp, output);

            output.append('\n');
        }

        output.append('\n');
    }

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


Question:
// HandleListAction handles GET actions to the dryrun clientset this interface supports.
// Currently there are no known LIST calls during kubeadm init this code has to take care of.

func (idr *InitDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error) {
	return false, nil, nil
}

def pop_with_body_instrs(setup_with_instr, queue):

    body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')

    # Last two instructions should always be POP_BLOCK, LOAD_CONST(None).
    # These don't correspond to anything in the AST, so remove them here.
    load_none = body_instrs.pop()
    expect(load_none, instrs.LOAD_CONST, "at end of with-block")
    pop_block = body_instrs.pop()
    expect(pop_block, instrs.POP_BLOCK, "at end of with-block")
    if load_none.arg is not None:
        raise DecompilationError(
            "Expected LOAD_CONST(None), but got "
            "%r instead" % (load_none)
        )

    # Target of the setup_with should be a WITH_CLEANUP instruction followed by
    # an END_FINALLY.  Neither of these correspond to anything in the AST.
    with_cleanup = queue.popleft()
    expect(with_cleanup, instrs.WITH_CLEANUP, "at end of with-block")
    end_finally = queue.popleft()
    expect(end_finally, instrs.END_FINALLY, "at end of with-block")

    return body_instrs

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


public RouterLike CONNECT_FIRST(String path, T target) {
    return patternFirst(CONNECT(), path, target);
  }

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
Run the migrations.

@return void

public function up()
    {
        ///////////////////////////////////////////////////////////////////////
        ////                    Lookup Tables                              ////
        ///////////////////////////////////////////////////////////////////////

        if (!Schema::hasTable('kb_lookup_categories'))
        {
            Schema::create('kb_lookup_categories', function (Blueprint $table)
            {
                $table->engine = 'InnoDB';

                $table->increments('id')->unsigned();

                $table->string('title')->unique();
                $table->string('description');

                $table->boolean('enabled')->default(true);

                $table->timestamp('created_at');
                $table->integer('created_by')->unsigned();
                $table->foreign('created_by')->references('id')->on('users');

                $table->timestamp('updated_at');
                $table->integer('updated_by')->unsigned();
                $table->foreign('updated_by')->references('id')->on('users');

                $table->timestamp('locked_at')->nullable();
                $table->integer('locked_by')->nullable()->unsigned();
                $table->foreign('locked_by')->references('id')->on('users');
            });
        }

        ///////////////////////////////////////////////////////////////////////
        ////                    Main Tables                                ////
        ///////////////////////////////////////////////////////////////////////

        if (!Schema::hasTable('kb_items'))
        {
            Schema::create('kb_items', function (Blueprint $table)
            {
                $table->engine = 'InnoDB';

                $table->increments('id')->unsigned();

                $table->integer('kb_category_id')->unsigned();
                $table->foreign('kb_category_id')->references('id')->on('kb_lookup_categories');

                $table->string('title');
                $table->string('description');
                $table->text('comments');

                $table->text('link');

                $table->timestamp('created_at');
                $table->integer('created_by')->unsigned();
                $table->foreign('created_by')->references('id')->on('users');

                $table->timestamp('updated_at');
                $table->integer('updated_by')->unsigned();
                $table->foreign('updated_by')->references('id')->on('users');

                $table->timestamp('locked_at')->nullable();
                $table->integer('locked_by')->nullable()->unsigned();
                $table->foreign('locked_by')->references('id')->on('users');
            });
        }
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

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


Question:
Clear global class cache and notify namespaces to clear their
class caches.

The listener list is implemented with weak references so that we
will not keep every namespace in existence forever.

@Override
    protected void classLoaderChanged()
    {
        Vector toRemove = new Vector(); // safely remove
        for ( Enumeration e = listeners.elements(); e.hasMoreElements(); )
        {
            WeakReference wr = (WeakReference)e.nextElement();
            Listener l = (Listener)wr.get();
            if ( l == null )  // garbage collected
              toRemove.add( wr );
            else
              l.classLoaderChanged();
        }
        for( Enumeration e = toRemove.elements(); e.hasMoreElements(); )
            listeners.removeElement( e.nextElement() );
    }

public function loadListeners($manager = null, $scope = null) {
		if (!($manager instanceof CakeEventManager)) {
			$scope = $manager;
			$_this = $this;
		} else {
			$_this = $manager;
		}

		empty($_this->loadedListeners['Common'])
		&& $_this->loadedListeners['Common'] = new CommonEventListener();

		(empty($_this->loadedScopes['Common']) || !in_array($scope, (array) $_this->loadedScopes['Common']))
		&& $_this->loadedScopes['Common'][] = $scope
		&& $_this->attachByScope($_this->loadedListeners['Common'], $_this, $scope);

		$_this->implementedEvents['Common'] = array_keys($_this->loadedListeners['Common']->implementedEvents());

		foreach ($_this->listPlugins() as $plugin) {
			if (isset($_this->loadedListeners[$plugin])) {
				if (
					$_this->loadedListeners[$plugin]
					&& !empty($scope)
					&& !in_array($scope, (array) $_this->loadedScopes[$plugin])
				) {
					$_this->loadedScopes[$plugin][] = $scope;
					$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
				}
				continue;
			}

			$class = $plugin . 'EventListener';

			if (ClassRegistry::isKeySet($class)) {
				$_this->loadedListeners[$plugin] = ClassRegistry::getObject($class);
			} else if (file_exists(CakePlugin::path($plugin) . 'Event' . DS . $class . '.php')) {
				App::uses($class, $plugin . '.Event');
				$_this->loadedListeners[$plugin] = new $class();
			} else {
				$_this->loadedListeners[$plugin] = false;
				continue;
			}

			$_this->loadedScopes[$plugin] = array();
			$_this->implementedEvents[$plugin] = array_keys($_this->loadedListeners[$plugin]->implementedEvents());

			if (empty($scope)) {
				$_this->attach($_this->loadedListeners[$plugin]);
			} else if (!in_array($scope, $_this->loadedScopes[$plugin])) {
				$_this->loadedScopes[$plugin][] = $scope;
				$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
			}
		}

		if ((!Reveal::is('Page.test') || empty($_GET['plugin'])) && !isset($_this->loadedListeners['App'])) {
			if (file_exists(APP . 'Event' . DS . 'AppEventListener.php')) {
				App::uses('AppEventListener', 'Event');
				$_this->loadedListeners['App'] = new AppEventListener();
				$_this->loadedScopes['App'] = array();
				$_this->implementedEvents['App'] = array_keys($_this->loadedListeners['App']->implementedEvents());
				if (empty($scope)) {
					$_this->attach($_this->loadedListeners['App']);
				} else if (!in_array($scope, $_this->loadedScopes['App'])) {
					$_this->loadedScopes['App'][] = $scope;
					$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
				}
			}
		} else if (
			isset($_this->loadedListeners['App'])
			&& $_this->loadedListeners['App']
			&& !empty($scope)
			&& !in_array($scope, $_this->loadedScopes['App'])
		) {
			$_this->loadedScopes['App'][] = $scope;
			$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
		}

		return $_this;
	}

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


Question: // Undo reverts the last Limit() call, returning consumed allowance

func (rl *RateLimiter) Undo() {
	current := atomic.AddUint64(&rl.allowance, rl.unit)

	// Ensure our allowance is not over maximum
	if max := atomic.LoadUint64(&rl.max); current > max {
		atomic.AddUint64(&rl.allowance, max-current)
	}
}

public static function resetLimit(AbstractUser $user): bool
    {
        $query = self::find()
            ->where([
                'user_id' => $user->id,
                'is_deleted' => 0,
            ]);
        $sms_codes = $query->all();
        foreach ($sms_codes as $sms_code) {
            /** @var $sms_code AbstractSmsCode */
            $sms_code->deleteModel();
        }
        return true;
    }

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


Question:
Returns a subset from the given array using the given list of ignored keys.

@param array $Source
@param mixed $keys, ...
@return array

public static final function except(array $Source, $keys){
		return array_diff_key($Source,
			array_fill_keys(self::simplify(array_slice(func_get_args(), 1)), -1));
	}

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: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterResourceQuotaSelector.

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

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

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

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

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

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

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

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

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


Question:
Construct a Mono from Iterable by taking the first value from Iterable

@param t Iterable to populate Mono from
@return Mono containing first element from Iterable (or empty Mono)

public static <T> Mono<T> fromIterable(Iterable<T> t) {
        return Mono.from(Flux.fromIterable(t));
    }

def repl_init(self, config):
        """"""
        self.update_server_map(config)
        # init_server - server which can init replica set
        init_server = [member['host'] for member in config['members']
                       if not (member.get('arbiterOnly', False)
                               or member.get('priority', 1) == 0)][0]

        servers = [member['host'] for member in config['members']]
        if not self.wait_while_reachable(servers):
            logger.error("all servers must be reachable")
            self.cleanup()
            return False
        try:
            result = self.connection(init_server).admin.command("replSetInitiate", config)
            logger.debug("replica init result: {result}".format(**locals()))
        except pymongo.errors.PyMongoError:
            raise
        if int(result.get('ok', 0)) == 1:
            # Wait while members come up
            return self.waiting_member_state()
        else:
            self.cleanup()
            return False

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


Question:
Executes queued requests.

See {@link queue} method for more information.

@since 1.3.0

@return void

public function start() {

        // indicate the library that it should execute queued requests
        $this->_queue = false;

        // if we have to pause between batches of requests, process them sequentially, in batches
        if ($this->pause_interval > 0) $this->_process_paused();

        // if we don't have to pause between batches of requests, process them all at once
        else $this->_process();

    }

function addUrl(when, feed) {
  if (!types.check(feed, 'feed') && !types.check(feed, ['feed']))
    throw Error('sandcrawler.spider.url(s): wrong argument.');

  var a = !(feed instanceof Array) ? [feed] : feed,
      c = !this.state.running ? this.initialBuffer.length : this.index,
      job,
      i,
      l;

  for (i = 0, l = a.length; i < l; i++) {
    job = createJob(a[i]);

    // Don't add if already at limit
    if (this.options.limit && c >= this.options.limit)
      break;

    if (!this.state.running) {
      this.initialBuffer[when === 'later' ? 'push' : 'unshift'](job);
    }
    else {
      this.queue[when === 'later' ? 'push' : 'unshift'](job);
      this.emit('job:add', job);
    }
  }

  return this;
}

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


Question: Returns a validator annotation (parameter or property decorator)

function typeAnnotation(type) {
    return (target, key, index) => {
        const classAnnotationsStore = container.get(AnnotationsServiceName.ClassAnnotationsStore);
        const classTypesStore = container.get(TypesServiceName.ClassTypesStore);
        if (index === undefined) {
            // property
            classAnnotationsStore.addPropertyAnnotation(target.constructor, key, Type, { type });
            classTypesStore.setPropertyType(target.constructor, key, type);
        }
        else {
            // method parameter
            classAnnotationsStore.addMethodParameterAnnotation(target.constructor, key, index, Type, { type });
            classTypesStore.setMethodParameterType(target.constructor, key, index, type);
        }
    };
}

public function composeValidationData(&$container, $constraints, $getters)
    {
        if (null == $container) {
            $container = array();
        }
        if ($getters) {
            if (!isset($container['getters'])) {
                $container['getters'] = array();
            }
            $container['getters'] = array_merge($container['getters'], $this->parseGetters($getters));
        }
        if ($constraints) {
            if (!isset($container['constraints'])) {
                $container['constraints'] = array();
            }
            $container['constraints'] = array_merge($container['constraints'], $this->parseConstraints($constraints));
        }
    }

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


Question:
Check if a group with the given groupName exists in the
list or not.
The check will be done case-sensitive.
@param groupName The name we are searching for.
@return true if the group has been found false otherwise.

public boolean hasGroup(String groupName) {
        boolean result = false;
        for (Group item : getGroupsList()) {
            if (item.getName().equals(groupName)) {
                result = true;
            }
        }
        return result;
    }

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

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

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

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

	return mi;
    }

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


Question:
Returns a list with the aspects that the object
        makes to the objects in IDs. It considers only
        conjunctions and other exact/applicative aspects
        if in aspList.

def __aspectLists(self, IDs, aspList):

        res = []

        for otherID in IDs:
            # Ignore same
            if otherID == self.obj.id:
                continue

            # Get aspects to the other object
            otherObj = self.chart.getObject(otherID)
            asp = aspects.getAspect(self.obj, otherObj, aspList)

            if asp.type == const.NO_ASPECT:
                continue
            elif asp.type == const.CONJUNCTION:
                res.append(asp.type)
            else:
                # Only exact or applicative aspects
                movement = asp.movement()
                if movement in [const.EXACT, const.APPLICATIVE]:
                    res.append(asp.type)

        return res

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question:
Connect to the websocket.

        If uuid is None, the connection will be to the controller. Otherwise it
        will be to the model.
        :return: The response field of login response JSON object.

async def _connect_with_login(self, endpoints):

        success = False
        try:
            await self._connect(endpoints)
            # It's possible that we may get several discharge-required errors,
            # corresponding to different levels of authentication, so retry
            # a few times.
            for i in range(0, 2):
                result = (await self.login())['response']
                macaroonJSON = result.get('discharge-required')
                if macaroonJSON is None:
                    self.info = result
                    success = True
                    return result
                macaroon = bakery.Macaroon.from_dict(macaroonJSON)
                self.bakery_client.handle_error(
                    httpbakery.Error(
                        code=httpbakery.ERR_DISCHARGE_REQUIRED,
                        message=result.get('discharge-required-error'),
                        version=macaroon.version,
                        info=httpbakery.ErrorInfo(
                            macaroon=macaroon,
                            macaroon_path=result.get('macaroon-path'),
                        ),
                    ),
                    # note: remove the port number.
                    'https://' + self.endpoint + '/',
                )
            raise errors.JujuAuthError('failed to authenticate '
                                       'after several attempts')
        finally:
            if not success:
                await self.close()

def _adapt_response(self, response):
        """"""
        if response.headers['content-type'] == 'application/json':
            body = response.json()
            status = response.status_code

            if body.get('errors'):
                return self._complex_response_to_error_adapter(body)

            elif body.get('code') and body.get('message'):
                return self._simple_response_to_error_adapter(status, body)

            elif body.get('error'):
                code = response.reason
                return self._message_to_error_adapter(status, code, body)

        raise UnknownHttpError(response)

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


Question:
Deserialize zipcode json data into a ZipCode object

        Args:
            json_data (dict): The json data for this zipcode

        Returns:
            Zip object

def create_from_json(cls, json_data):

        zipcode = ZipCode()
        zipcode.zipcode = json_data["zipcode_info"]["zipcode"]
        zipcode.meta = json_data["meta"] if "meta" in json_data else None

        zipcode.component_results = _create_component_results(json_data, "zipcode_info")

        return zipcode

def dumpable_obj(obj):
    ''' '''

    if isinstance(obj, list):
        _return_list = []
        for item in obj:
            if isinstance(item, list):
                _return_list.append(dumpable_obj(item))
            elif isinstance(item, set):
                _return_list.append(list(item))
            elif isinstance(item, dict):
                _return_list.append(dumpable_obj(item))
            else:
                try:
                    json.dumps(item)
                    _return_list.append(item)
                except:
                    _return_list.append(str(type(item)))
        return _return_list
    elif isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        _return_obj = {}
        for key, item in obj.items():
            if isinstance(item, list):
                _return_obj[key] = dumpable_obj(item)
            elif isinstance(item, set):
                _return_obj[key] = list(item)
            elif isinstance(item, dict):
                _return_obj[key] = dumpable_obj(item)
            else:
                try:
                    json.dumps(item)
                    _return_obj[key] = item
                except:
                    _return_obj[key] = str(type(item))
        return _return_obj
    else:
        try:
            json.dumps(obj)
            return obj
        except:
            return str(type(obj))

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


Question: // SetAmznClientToken sets the AmznClientToken field's value.

func (s *CreateConnectorDefinitionInput) SetAmznClientToken(v string) *CreateConnectorDefinitionInput {
	s.AmznClientToken = &v
	return s
}

def __get_connection_cloudwatch():

    region = get_global_option('region')
    try:
        if (get_global_option('aws_access_key_id') and
                get_global_option('aws_secret_access_key')):
            logger.debug(
                'Authenticating to CloudWatch using '
                'credentials in configuration file')
            connection = cloudwatch.connect_to_region(
                region,
                aws_access_key_id=get_global_option('aws_access_key_id'),
                aws_secret_access_key=get_global_option(
                    'aws_secret_access_key'))
        else:
            logger.debug(
                'Authenticating using boto\'s authentication handler')
            connection = cloudwatch.connect_to_region(region)

    except Exception as err:
        logger.error('Failed connecting to CloudWatch: {0}'.format(err))
        logger.error(
            'Please report an issue at: '
            'https://github.com/sebdah/dynamic-dynamodb/issues')
        raise

    logger.debug('Connected to CloudWatch in {0}'.format(region))
    return connection

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


Question: // SetEC2SecurityGroupName sets the EC2SecurityGroupName field's value.

func (s *EC2SecurityGroup) SetEC2SecurityGroupName(v string) *EC2SecurityGroup {
	s.EC2SecurityGroupName = &v
	return s
}

def read_developer_settings():

    ret = read_cfg("/.rwmeta/developer_settings.json")

    env_developer_settings = os.environ.get('META_SERVICE_ACCOUNT_SECRET', None)
    if not env_developer_settings:
        env_developer_settings = os.environ.get('X-META-Developer-Settings', None)
    if env_developer_settings:
        ret = json.loads(env_developer_settings)

    return ret

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


Question: Ensure a reuse URL is not yet registered

def check_url_does_not_exists(form, field):
    ''''''
    if field.data != field.object_data and Reuse.url_exists(field.data):
        raise validators.ValidationError(_('This URL is already registered'))

public function setPeerURLs(&$var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
        $this->peerURLs = $arr;
    }

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


Question:
%(super)s

        In addition to data, gives an optional keyword argument k_agg0 that
        specifies the initial value of k_agg used in the optimization.

def fit_mle(self, data, k_agg0=0.5):

        mu = np.mean(data)

        def mle(k):

            return -np.sum(np.log(self.pmf(data, mu, k)))

        k = optim.fmin(mle, x0=k_agg0, disp=0)

        return mu, k[0]

public static <MP extends Model.Parameters, C extends HyperSpaceSearchCriteria>
        HyperSpaceWalker<MP, ? extends HyperSpaceSearchCriteria> create(MP params,
                                                                        Map<String, Object[]> hyperParams,
                                                                        ModelParametersBuilderFactory<MP> paramsBuilderFactory,
                                                                        C search_criteria) {
        HyperSpaceSearchCriteria.Strategy strategy = search_criteria.strategy();

        if (strategy == HyperSpaceSearchCriteria.Strategy.Cartesian) {
          return new HyperSpaceWalker.CartesianWalker<>(params, hyperParams, paramsBuilderFactory, (HyperSpaceSearchCriteria.CartesianSearchCriteria) search_criteria);
        } else if (strategy == HyperSpaceSearchCriteria.Strategy.RandomDiscrete ) {
          return new HyperSpaceWalker.RandomDiscreteValueWalker<>(params, hyperParams, paramsBuilderFactory, (HyperSpaceSearchCriteria.RandomDiscreteValueSearchCriteria) search_criteria);
        } else {
          throw new H2OIllegalArgumentException("strategy", "GridSearch", strategy);
        }
      }

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


Question: init various application wide stores for handling history and debug output.

private void initMBeans(Configuration pConfig) {
        int maxEntries = pConfig.getAsInt(HISTORY_MAX_ENTRIES);
        int maxDebugEntries = pConfig.getAsInt(DEBUG_MAX_ENTRIES);

        historyStore = new HistoryStore(maxEntries);
        debugStore = new DebugStore(maxDebugEntries, pConfig.getAsBoolean(DEBUG));

        try {
            localDispatcher.initMBeans(historyStore, debugStore);
        } catch (NotCompliantMBeanException e) {
            intError("Error registering config MBean: " + e, e);
        } catch (MBeanRegistrationException e) {
            intError("Cannot register MBean: " + e, e);
        } catch (MalformedObjectNameException e) {
            intError("Invalid name for config MBean: " + e, e);
        }
    }

def do_shutdown(self, restart):

        print("in shutdown function")
        if self.hist_file:
            with open(self.hist_file, 'wb') as fid:
                data = '\n'.join(self.hist_cache[-self.max_hist_cache:])
                fid.write(data.encode('utf-8'))
        if self.mva:
            self.mva._endsas()
            self.mva = None
        if restart:
            self.Print("Restarting kernel...")
            self.reload_magics()
            self.restart_kernel()
            self.Print("Done!")
        return {'status': 'ok', 'restart': restart}

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


Question:
/*!
Fetches the http post var integer input and stores it in the data instance.

function fetchObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        if ( $http->hasPostVariable( $base . "_data_integer_" . $contentObjectAttribute->attribute( "id" ) ) )
        {
            $data = $http->postVariable( $base . "_data_integer_" . $contentObjectAttribute->attribute( "id" ) );
            $data = trim( $data ) != '' ? $data : null;
            $data = str_replace(" ", "", $data);
            $contentObjectAttribute->setAttribute( "data_int", $data );
            return true;
        }
        return false;
    }

def add(self, child):

        if isinstance(child, Run):
            self.add_run(child)
        elif isinstance(child, Record):
            self.add_record(child)
        elif isinstance(child, EventRecord):
            self.add_event_record(child)
        elif isinstance(child, DataDisplay):
            self.add_data_display(child)
        elif isinstance(child, DataWriter):
            self.add_data_writer(child)
        elif isinstance(child, EventWriter):
            self.add_event_writer(child)
        else:
            raise ModelError('Unsupported child element')

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


Question:
This function creates a new fax client based on the provided configuration.

@param   type
The fax client type (may be null for default type)
@param   configuration
The fax client configuration (may be null)
@return  The fax client instance

private static FaxClient createFaxClientImpl(String type,Properties configuration)
    {
        //create fax client SPI
        FaxClientSpi faxClientSpi=FaxClientSpiFactory.createFaxClientSpi(type,configuration);

        //get fax client class name
        String className=faxClientSpi.getConfigurationValue(FaxClientFactory.FAX_CLIENT_CLASS_NAME_PROPERTY_KEY);
        if((className==null)||(className.length()==0))
        {
            className=FaxClient.class.getName();
        }

        //load class definition
        Class<?> classDefinition=ReflectionHelper.getType(className);

        FaxClient faxClient=null;
        try
        {
            //create fax client
            Constructor<?> constructor=classDefinition.getConstructor(new Class[]{FaxClientSpi.class});
            faxClient=(FaxClient)constructor.newInstance(new Object[]{faxClientSpi});
        }
        catch(Exception exception)
        {
            throw new FaxException("Unable to create a new fax client instance for class name: "+className,exception);
        }

        return faxClient;
    }

@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withDescriptor:")
    public void sendDocument(Peer peer, String fileName, String mimeType, String descriptor) {
        sendDocument(peer, fileName, mimeType, null, descriptor);
    }

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


Question: // WatchUpgradeSeriesNotifications mocks base method

func (m *MockFacade) WatchUpgradeSeriesNotifications() (watcher.NotifyWatcher, error) {
	ret := m.ctrl.Call(m, "WatchUpgradeSeriesNotifications")
	ret0, _ := ret[0].(watcher.NotifyWatcher)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

func (m *SubscriptionManager) Stop() {
	if atomic.AddInt32(&m.stopped, 1) != 1 {
		return
	}

	log.Debug("Stopping block notifications subscription manager")

	close(m.quit)
	m.wg.Wait()

	var wg sync.WaitGroup
	wg.Add(len(m.subscribers))
	for _, subscriber := range m.subscribers {
		go func() {
			defer wg.Done()
			subscriber.cancel()
		}()
	}

	wg.Wait()
}

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


Question: Draw nodes to screen.

def draw_nodes(self):

        node_r = self.node_sizes
        for i, node in enumerate(self.nodes):
            x = self.node_coords["x"][i]
            y = self.node_coords["y"][i]
            color = self.node_colors[i]
            node_patch = patches.Ellipse(
                (x, y), node_r[i], node_r[i], lw=0, color=color, zorder=2
            )
            self.ax.add_patch(node_patch)

def run(self):
    """"""
    self.graphite.start()
    while True:
      log.debug('Graphite pusher is sleeping for %d seconds', self.period)
      time.sleep(self.period)
      log.debug('Pushing stats to Graphite')
      try:
        self.push()
        log.debug('Done pushing stats to Graphite')
      except:
        log.exception('Exception while pushing stats to Graphite')
        raise

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


Question: Async function required for us to use await

async function runExample() {
	try {

		// Put together some options to use in each test
		const options = {
			log: {
				debug: console.log,
				error: console.error,
				info: console.log
			}
		};

		// Run tests against multiple URLs
		const results = await Promise.all([
			pa11y('http://example.com/', options),
			pa11y('http://example.com/otherpage/', options)
		]);

		// Output the raw result objects
		console.log(results[0]); // Results for the first URL
		console.log(results[1]); // Results for the second URL

	} catch (error) {

		// Output an error if it occurred
		console.error(error.message);

	}
}

public CompletableFuture<Tokens> getTokens() {
        return tokenRepo.fetch(INTERNAL_PROJ, Project.REPO_DOGMA, TOKEN_JSON)
                        .thenApply(HolderWithRevision::object);
    }

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


Question: Take values according to indexer and return them as a block.bb

def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None):

        # algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock
        # so need to preserve types
        # sparse is treated like an ndarray, but needs .get_values() shaping

        values = self.values
        if self.is_sparse:
            values = self.get_values()

        if fill_tuple is None:
            fill_value = self.fill_value
            new_values = algos.take_nd(values, indexer, axis=axis,
                                       allow_fill=False, fill_value=fill_value)
        else:
            fill_value = fill_tuple[0]
            new_values = algos.take_nd(values, indexer, axis=axis,
                                       allow_fill=True, fill_value=fill_value)

        if new_mgr_locs is None:
            if axis == 0:
                slc = libinternals.indexer_as_slice(indexer)
                if slc is not None:
                    new_mgr_locs = self.mgr_locs[slc]
                else:
                    new_mgr_locs = self.mgr_locs[indexer]
            else:
                new_mgr_locs = self.mgr_locs

        if not is_dtype_equal(new_values.dtype, self.dtype):
            return self.make_block(new_values, new_mgr_locs)
        else:
            return self.make_block_same_class(new_values, new_mgr_locs)

public void repairIndex() throws IOException {
        byte[] currentLargestKey = new byte[keySize];
        int maxChunk = getChunkIndex(getFilledUpFromContentStart());
        for (int currentChunkId = 0; currentChunkId <= maxChunk; currentChunkId++) {
            long currentOffset = (currentChunkId + 1) * getChunkSize() - elementSize;
            if (currentOffset < getFilledUpFromContentStart()) {
                read(currentOffset, currentLargestKey);
            } else {
                read(getFilledUpFromContentStart() - elementSize, currentLargestKey);
            }
            getIndex().setLargestKey(currentChunkId, currentLargestKey);
        }
    }

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


Question: Export a MultiplyParameters node, identified by PK, to plain text

def export(outfile, pk):
    """"""
    load_dbenv_if_not_loaded(
    )  # Important to load the dbenv in the last moment

    from aiida.orm import load_node
    node = load_node(pk)
    string = str(node)

    if outfile:
        with open(outfile, 'w') as f:
            f.write(string)
    else:
        click.echo(string)

@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case DroolsPackage.META_DATA_TYPE__META_VALUE:
				return getMetaValue();
			case DroolsPackage.META_DATA_TYPE__NAME:
				return getName();
		}
		return super.eGet(featureID, resolve, coreType);
	}

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