Question:
Parse netty cookie to {@link Cookie}.

@param nettyCookie netty raw cookie instance

private void parseCookie(io.netty.handler.codec.http.cookie.Cookie nettyCookie) {
        var cookie = new Cookie();
        cookie.name(nettyCookie.name());
        cookie.value(nettyCookie.value());
        cookie.httpOnly(nettyCookie.isHttpOnly());
        cookie.path(nettyCookie.path());
        cookie.domain(nettyCookie.domain());
        cookie.maxAge(nettyCookie.maxAge());
        this.cookies.put(cookie.name(), cookie);
    }

def alter(self, operation, timeout=None, metadata=None, credentials=None):
        """"""
        new_metadata = self.add_login_metadata(metadata)

        try:
            return self.any_client().alter(operation, timeout=timeout,
                                           metadata=new_metadata,
                                           credentials=credentials)
        except Exception as error:
            if util.is_jwt_expired(error):
                self.retry_login()
                new_metadata = self.add_login_metadata(metadata)
                return self.any_client().alter(operation, timeout=timeout,
                                               metadata=new_metadata,
                                               credentials=credentials)
            else:
                raise error

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


Question:
Registers a resource.

@param  ResourcesResource $resource

@return void

public function registerResource(Resources\Resource $resource)
  {
      $this->resources[strtolower($resource->getName())] = $resource;
  }

func (self *RawDispatcher) AddResourceSeparateUdid(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid) {
	t := self.validateType(wireExample)
	obj := &restObjUdid{
		restShared: restShared{
			typ:   t,
			name:  name,
			index: index,
			post:  post,
		},
		find: find,
		del:  del,
		put:  put,
	}
	node.ResUdid[strings.ToLower(name)] = obj
}

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


Question: Returns true if the relation holds.

private static boolean polygonRelatePoint_(Polygon polygon_a,
			Point point_b, double tolerance, int relation,
			ProgressTracker progress_tracker) {
		switch (relation) {
		case Relation.disjoint:
			return polygonDisjointPoint_(polygon_a, point_b, tolerance,
					progress_tracker);

		case Relation.contains:
			return polygonContainsPoint_(polygon_a, point_b, tolerance,
					progress_tracker);

		case Relation.touches:
			return polygonTouchesPoint_(polygon_a, point_b, tolerance,
					progress_tracker);

		default:
			break; // warning fix
		}

		return false;
	}

public function prevTypeIsAnyOf(array $types): bool
    {
        return isset($this->tokens[$this->position - 2]) && $this->tokens[$this->position - 2]->typeEqualsAnyOf($types);
    }

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


Question:
Creates an issue.

@param string $project_key Project key.
@param string $summary     Summary.
@param string $issue_type  Issue type.
@param array  $options     Options.

@return Result|false

public function createIssue($project_key, $summary, $issue_type, array $options = array())
	{
		$default = array(
			'project' => array(
				'key' => $project_key,
			),
			'summary' => $summary,
			'issuetype' => array(
				'id' => $issue_type,
			),
		);

		$default = array_merge($default, $options);

		return $this->api(self::REQUEST_POST, '/rest/api/2/issue/', array('fields' => $default));
	}

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question:
Do the mapping.
@return A Map.
@throws ControlException on error.

public Object mapRowToReturnType() {
        try {
        return Collections.unmodifiableMap(new ResultSetHashMap(_resultSet, _keys));
        } catch (SQLException e) {
           throw new ControlException("Exception while creating ResultSetHashMap.", e);
        }
    }

public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();

        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }

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


Question:
Build query and passes to `Elasticsearch`, then returns the raw
        format returned.

def raw(self):

        es = self.get_es()

        params = dict(self.query_params)
        mlt_fields = self.mlt_fields or params.pop('mlt_fields', [])

        body = self.s.build_search() if self.s else ''

        hits = es.mlt(
            index=self.index, doc_type=self.doctype, id=self.id,
            mlt_fields=mlt_fields, body=body, **params)

        log.debug(hits)

        return hits

public function render_result(\core_search\document $doc) {
        $docdata = $doc->export_for_template($this);

        // Limit text fields size.
        $docdata['title'] = shorten_text($docdata['title'], static::SEARCH_RESULT_STRING_SIZE, true);
        $docdata['content'] = $docdata['content'] ? shorten_text($docdata['content'], static::SEARCH_RESULT_TEXT_SIZE, true) : '';
        $docdata['description1'] = $docdata['description1'] ? shorten_text($docdata['description1'], static::SEARCH_RESULT_TEXT_SIZE, true) : '';
        $docdata['description2'] = $docdata['description2'] ? shorten_text($docdata['description2'], static::SEARCH_RESULT_TEXT_SIZE, true) : '';

        return $this->output->render_from_template('core_search/result', $docdata);
    }

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


Question: // SetCacheParameterGroupName sets the CacheParameterGroupName field's value.

func (s *ModifyCacheParameterGroupInput) SetCacheParameterGroupName(v string) *ModifyCacheParameterGroupInput {
	s.CacheParameterGroupName = &v
	return s
}

def set_trigger_group_bit_mask(self, trigger_group_bit_mask):
        """"""
        set_cmd = self._create_set_property_msg("_trigger_group_bit_mask",
                                                0x0c, trigger_group_bit_mask)
        self._send_method(set_cmd, self._property_set)

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


Question: Convert key/value to tree

def key_value_to_tree(data):
    '''

    '''
    tree = {}
    for flatkey, value in six.iteritems(data):
        t = tree
        keys = flatkey.split(__opts__['pepa_delimiter'])
        for i, key in enumerate(keys, 1):
            if i == len(keys):
                t[key] = value
            else:
                t = t.setdefault(key, {})
    return tree

func (t *osCinderCSITranslator) TranslateInTreeStorageClassParametersToCSI(scParameters map[string]string) (map[string]string, error) {
	return scParameters, nil
}

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


Question:
Template filter that returns field widget class name (in lower case).
    E.g. if field's widget is TextInput then {{ field|widget_type }} will
    return 'textinput'.

def widget_type(field):

    if hasattr(field, 'field') and hasattr(field.field, 'widget') and field.field.widget:
        return field.field.widget.__class__.__name__.lower()
    return ''

def _get_event_kwargs(view_obj):

    request = view_obj.request

    view_method = getattr(view_obj, request.action)
    do_trigger = not (
        getattr(view_method, '_silent', False) or
        getattr(view_obj, '_silent', False))

    if do_trigger:
        event_kwargs = {
            'view': view_obj,
            'model': view_obj.Model,
            'fields': FieldData.from_dict(
                view_obj._json_params,
                view_obj.Model)
        }
        ctx = view_obj.context
        if hasattr(ctx, 'pk_field') or isinstance(ctx, DataProxy):
            event_kwargs['instance'] = ctx
        return event_kwargs

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


Question:
{@inheritDoc}

@throws OperaRunnerException if launcher is shut down or not running

public void stopOpera() throws OperaRunnerException {
    assertLauncherAlive();

    if (!isOperaRunning()) {
      return;
    }

    try {
      LauncherStopRequest.Builder request = LauncherStopRequest.newBuilder();

      ResponseEncapsulation res = protocol.sendRequest(
          MessageType.MSG_STOP, request.build().toByteArray()
      );

      if (handleStatusMessage(res.getResponse()) == StatusType.RUNNING) {
        throw new IOException("launcher unable to stop binary");
      }
    } catch (IOException e) {
      throw new OperaRunnerException("Could not stop Opera: " + e.getMessage());
    }
  }

public function notify($exception, $options = array()) {
		$this->_checkConfig();

		$config = array_merge($this->_config, $options);

		$sock = fsockopen(
			$this->_buildTcpScheme($config),
			$config['port'],
			$errno, $errstr,
			$config['connect_timeout']
		);

		if ($sock) {
			stream_set_timeout($sock, $config['write_timeout']);
			fwrite($sock, $this->_buildHttpPayload($exception, $config));
			fclose($sock);
		}

		foreach ($this->_observers as $observer) {
			$observer($exception, $config);
		}

		return $this;
	}

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


Question: // LoadTable loads a table's definition from a database.

func LoadTable(db *sql.DB, name string) (*Table, error) {
	t := makeTable(name)
	err := t.loadColumns(db)
	if err != nil {
		return nil, err
	}
	err = t.loadKeys(db)
	if err != nil {
		return nil, err
	}
	return t, nil
}

@Nonnull
	public static <R> LDblFunctionBuilder<R> dblFunction(Consumer<LDblFunction<R>> consumer) {
		return new LDblFunctionBuilder(consumer);
	}

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


Question: Sequence of commands create, simulate and analyse network

def intervalCreateSimulateAnalyze (netParams=None, simConfig=None, output=False, interval=None):
    '''  '''
    import os
    from .. import sim
    (pops, cells, conns, stims, rxd, simData) = sim.create(netParams, simConfig, output=True)
    try:
        if sim.rank==0:
            if os.path.exists('temp'):
                for f in os.listdir('temp'):
                    os.unlink('temp/{}'.format(f))
            else:
                os.mkdir('temp')
        sim.intervalSimulate(interval)
    except Exception as e:
        print(e)
        return
    sim.pc.barrier()
    sim.analyze()
    if output: return (pops, cells, conns, stims, simData)

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

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

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


Question:
// forAllOutboundPeers is a helper function that runs closure on all outbound
// peers known to peerState.

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

def peek(self, n=1, raw=False):

        def _peek_specific_q(_q, _n):
            has_messages = False
            for m in _q.service.peek_messages(_q.name, num_messages=_n):
                if m is not None:
                    has_messages = True
                    result.append(m if raw else self._deserialize_message(m))

                    # short circut to prevent unneeded work
                    if len(result) == n:
                        return True
            return has_messages

        q_services = self._get_q_services()
        random.shuffle(q_services)

        per_q = int(n / len(q_services)) + 1

        result = []

        non_empty_qs = []

        for q in q_services:
            if _peek_specific_q(q, per_q):
                non_empty_qs.append(q)

            if len(result) == n:
                return result

        # in-case queues aren't balanced, and we didn't get enough messages, iterate again and this time get all that we can
        for q in non_empty_qs:
            _peek_specific_q(q, n)
            if len(result) == n:
                return result

        # because we ask for n / len(qs) + 1, we might get more message then requests
        return result

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


Question:
Get value for a specific option. Attention, option MUST exist in template in order to
be retrievable.

@param string $option

@return mixed

@throws OptionsException

public function define(string $option)
    {
        if (!array_key_exists($option, $this->options)) {
            throw new OptionsException("Undefined relation option '{$option}'");
        }

        return $this->options[$option];
    }

public function setPartials(array $partials = array())
    {
        if (!isset($this->partialsLoader)) {
            $this->partialsLoader = new Mustache_Loader_ArrayLoader();
        }

        if (!$this->partialsLoader instanceof Mustache_Loader_MutableLoader) {
            throw new Mustache_Exception_RuntimeException('Unable to set partials on an immutable Mustache Loader instance');
        }

        $this->partialsLoader->setTemplates($partials);
    }

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


Question: // Shutdown stops the daemon.

func (daemon *Daemon) Shutdown() error {
	daemon.shutdown = true
	// Keep mounts and networking running on daemon shutdown if
	// we are to keep containers running and restore them.

	if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
		// check if there are any running containers, if none we should do some cleanup
		if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
			// metrics plugins still need some cleanup
			daemon.cleanupMetricsPlugins()
			return nil
		}
	}

	if daemon.containers != nil {
		logrus.Debugf("daemon configured with a %d seconds minimum shutdown timeout", daemon.configStore.ShutdownTimeout)
		logrus.Debugf("start clean shutdown of all containers with a %d seconds timeout...", daemon.ShutdownTimeout())
		daemon.containers.ApplyAll(func(c *container.Container) {
			if !c.IsRunning() {
				return
			}
			logrus.Debugf("stopping %s", c.ID)
			if err := daemon.shutdownContainer(c); err != nil {
				logrus.Errorf("Stop container error: %v", err)
				return
			}
			if mountid, err := daemon.imageService.GetLayerMountID(c.ID, c.OS); err == nil {
				daemon.cleanupMountsByID(mountid)
			}
			logrus.Debugf("container stopped %s", c.ID)
		})
	}

	if daemon.volumes != nil {
		if err := daemon.volumes.Shutdown(); err != nil {
			logrus.Errorf("Error shutting down volume store: %v", err)
		}
	}

	if daemon.imageService != nil {
		daemon.imageService.Cleanup()
	}

	// If we are part of a cluster, clean up cluster's stuff
	if daemon.clusterProvider != nil {
		logrus.Debugf("start clean shutdown of cluster resources...")
		daemon.DaemonLeavesCluster()
	}

	daemon.cleanupMetricsPlugins()

	// Shutdown plugins after containers and layerstore. Don't change the order.
	daemon.pluginShutdown()

	// trigger libnetwork Stop only if it's initialized
	if daemon.netController != nil {
		daemon.netController.Stop()
	}

	if daemon.containerdCli != nil {
		daemon.containerdCli.Close()
	}

	return daemon.cleanupMounts()
}

def run(self) -> 'QuantumFlowQVM':
        """"""
        assert self.status in ['loaded']
        self.status = 'running'
        self._ket = self._prog.run()
        # Should set state to 'done' after run complete.
        # Makes no sense to keep status at running. But pyQuil's
        # QuantumComputer calls wait() after run, which expects state to be
        # 'running', and whose only effect to is to set state to 'done'
        return self

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


Question:
/*
Render the list

function() {
            this.$(".hr-list-message").remove();
            if (this.collection.queue.isComplete() == false) {
                $("<div>", {
                    "class": "hr-list-message hr-list-message-loading"
                }).appendTo(this.$el);
            } else {
                if (this.count() == 0 && this.options.displayEmptyList) {
                    var el = this.displayEmptyList();
                    $(el).addClass("hr-list-message hr-list-message-empty").appendTo(this.$el);
                }
                if (this.hasMore() > 0 && this.options.displayHasMore) this.displayHasMore();
            }
            return this.ready();
        }

def ul_dealers(subj)
      res = '-'
      unless subj.dealers.count.zero?
        res = ''
        subj.dealers.each do |dealer|
          e = "
#{dealer.title}
"
          res += e
        end
        res = "
#{res}
".html_safe
      end
      res
    end

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


Question: $ANTLR start "T__94"

public final void mT__94() throws RecognitionException {
		try {
			int _type = T__94;
			int _channel = DEFAULT_TOKEN_CHANNEL;
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:75:7: ( 'long' )
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:75:9: 'long'
			{
			match("long");

			}

			state.type = _type;
			state.channel = _channel;
		}
		finally {
			// do for sure before leaving
		}
	}

public org.teatrove.tea.compiler.Scanner createScanner(SourceReader sr, CompilationUnit unit)
    throws IOException {
        org.teatrove.tea.compiler.Scanner scanner = super.createScanner(sr, unit);
        CompileListener scannerListener = getScannerListener();
        if (scannerListener != null) {
            scanner.addCompileListener(scannerListener);
        }
        return scanner;
    }

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


Question: Delete likes related to the current record

public function removeLikes()
	{
		Like::where('likeable_type', $this->morphClass)->where('likeable_id', $this->id)->delete();

		LikeCounter::where('likeable_type', $this->morphClass)->where('likeable_id', $this->id)->delete();
	}

function(number, params, headers, callback) {
        var url;
        url = this.client.url() + ("posts/" + (number || ''));
        return this.client.del(url, params, headers, callback);
      }

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


Question:
Returns a list of indexes containing only the points that pass the filter.

        Parameters
        ----------
        dataframe : DataFrame

def _identify(self, dataframe):

        ##
        # TODO Fix this implementation. (i.e., why not support just 'left')
        # At the moment this implementation won't work at all.
        # The logic here can be simplified.
        id1 = dataframe[self.channels[0]] >= self.vert[0]
        id2 = dataframe[self.channels[1]] >= self.vert[1]

        if 'left' in self.region: id1 = ~id1
        if 'bottom' in self.region: id2 = ~id2

        idx = id1 & id2

        if 'out' in self.region:
            idx = ~idx

        return idx

def lows(self, *args):

		for t in ifilter(lambda e: e[2] == 'L', self.extrema(*args)):
			yield t

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


Question:
Adds remote connection parameter to link GET query,
if parameter yet not present in this link.
@param link link to add connection parameter
@return link with remote connection GET parameter

public static String makeDeepLink(String link){

        if(link != null
                // If getCurrentRemoteConnectionLink() == null means there is no current remote connection
                && getCurrentRemoteConnectionLink() != null
                // If containsRemoteParameter(link) is true means link already contain remote connection parameter
                && !containsRemoteParameter(link)) {

            link += (link.contains("?") ? "&" : "?") + PARAM_REMOTE_CONNECTION + "=" + getCurrentRemoteConnectionLink();

        }

        return link;

    }

def check_url(url_data, logger):
    """"""
    if url_data.has_result:
        logger.log_url(url_data.to_wire())
    else:
        cache = url_data.aggregate.result_cache
        key = url_data.cache_url
        result = cache.get_result(key)
        if result is None:
            # check
            check_start = time.time()
            try:
                url_data.check()
                do_parse = url_data.check_content()
                url_data.checktime = time.time() - check_start
                # Add result to cache
                result = url_data.to_wire()
                cache.add_result(key, result)
                for alias in url_data.aliases:
                    # redirect aliases
                    cache.add_result(alias, result)
                # parse content recursively
                # XXX this could add new warnings which should be cached.
                if do_parse:
                    parser.parse_url(url_data)
            finally:
                # close/release possible open connection
                url_data.close_connection()
        else:
            # copy data from cache and adjust it
            result = copy.copy(result)
            result.parent_url = url_data.parent_url
            result.base_ref = url_data.base_ref or u""
            result.base_url = url_data.base_url or u""
            result.line = url_data.line
            result.column = url_data.column
            result.level = url_data.recursion_level
            result.name = url_data.name
        logger.log_url(result)

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


Question:
Include other config file

@param array $config
@param string $config_file
@param File $base_dir
@param ConfigReader $reader

@throws IncludeConfigFileNotFoundException
@throws UnsupportedConfigFileFormatException

private static function includeConfigFile(array &$config, $config_file, File $base_dir, ConfigReader $reader)
    {
        // try relative path
        $file = new File($config_file, $base_dir);

        if ( $file->exists() ){
            $included = self::loadConfigFileByFormat( $file, $reader );
            $config = array_merge_recursive($config, $included);
            return;
        }

        // try full path
        $file = new File($config_file);

        if ( $file->exists() ){
            $included = self::loadConfigFileByFormat( $file, $reader );
            $config = array_merge_recursive($config, $included);
            return;
        }

        throw new IncludeConfigFileNotFoundException($config_file);
    }

func (f *FlagSet) ParseFile(path string) error {

	// Extract arguments from file
	fp, err := os.Open(path)
	if err != nil {
		return err
	}
	defer fp.Close()

	scanner := bufio.NewScanner(fp)
	for scanner.Scan() {
		line := scanner.Text()

		// Ignore empty lines
		if len(line) == 0 {
			continue
		}

		// Ignore comments
		if line[:1] == "#" {
			continue
		}

		// Match `key=value` and `key value`
		var name, value string
		hasValue := false
		for i, v := range line {
			if v == '=' || v == ' ' {
				hasValue = true
				name, value = line[:i], line[i+1:]
				break
			}
		}

		if hasValue == false {
			name = line
		}

		// Ignore flag when already set; arguments have precedence over file
		if f.actual[name] != nil {
			continue
		}

		m := f.formal
		flag, alreadythere := m[name]
		if !alreadythere {
			if name == "help" || name == "h" { // special case for nice help message.
				f.usage()
				return ErrHelp
			}
			return f.failf("configuration variable provided but not defined: %s", name)
		}

		if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
			if hasValue {
				if err := fv.Set(value); err != nil {
					return f.failf("invalid boolean value %q for configuration variable %s: %v", value, name, err)
				}
			} else {
				// flag without value is regarded a bool
				fv.Set("true")
			}
		} else {
			if err := flag.Value.Set(value); err != nil {
				return f.failf("invalid value %q for configuration variable %s: %v", value, name, err)
			}
		}

		// update f.actual
		if f.actual == nil {
			f.actual = make(map[string]*Flag)
		}
		f.actual[name] = flag
	}

	if err := scanner.Err(); err != nil {
		return err
	}

	return nil
}

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


Question:
Sets ul attributes [5.0.0]

@param callable $list
@param array    $attributes = []

@return string

public function ul(Callable $list, Array $attributes = [], $type = 'ul') : String
    {
        return $this->_multiElement($type, Buffering\Callback::do($list, [new $this]), $attributes);
    }

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:
Connect to the redis host and return a StrictRedisCluster client object.
    If connection fails then return None.

def _redis_client(opts):
    '''

    '''
    redis_host = opts.get("eauth_redis_host", "localhost")
    redis_port = opts.get("eauth_redis_port", 6379)
    try:
        return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)
    except rediscluster.exceptions.RedisClusterException as err:
        log.warning(
            'Failed to connect to redis at %s:%s - %s',
            redis_host, redis_port, err
        )
        return None

def query(self, query):

        if not isinstance(query, bytes):
            query = query.encode("utf-8")

        retry_num = 0
        retry_exceptions = []
        do_retry = True if self.max_retry_count > 0 else False
        while retry_num <= self.max_retry_count:
            if retry_num > 0:
                time.sleep(self.retry_timeout)
            retry_num += 1
            try:
                f = urlopen(self.url, query)
            except HTTPError as e:
                f = e

            response = f.read(self.read_chunk_size)
            while True:
                data = f.read(self.read_chunk_size)
                if len(data) == 0:
                    break
                response = response + data
            f.close()

            if f.code == 200:
                if PY2:
                    http_info = f.info()
                    content_type = http_info.getheader("content-type")
                else:
                    content_type = f.getheader("Content-Type")

                if content_type == "application/json":
                    return self.parse_json(response)

                if content_type == "application/osm3s+xml":
                    return self.parse_xml(response)

                e = exception.OverpassUnknownContentType(content_type)
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            if f.code == 400:
                msgs = []
                for msg in self._regex_extract_error_msg.finditer(response):
                    tmp = self._regex_remove_tag.sub(b"", msg.group("msg"))
                    try:
                        tmp = tmp.decode("utf-8")
                    except UnicodeDecodeError:
                        tmp = repr(tmp)
                    msgs.append(tmp)

                e = exception.OverpassBadRequest(
                    query,
                    msgs=msgs
                )
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            if f.code == 429:
                e = exception.OverpassTooManyRequests
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            if f.code == 504:
                e = exception.OverpassGatewayTimeout
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            e = exception.OverpassUnknownHTTPStatusCode(f.code)
            if not do_retry:
                raise e
            retry_exceptions.append(e)
            continue

        raise exception.MaxRetriesReached(retry_count=retry_num, exceptions=retry_exceptions)

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


Question: Marshall the given parameter object.

public void marshall(GetTraceGraphRequest getTraceGraphRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getTraceGraphRequest.getTraceIds(), TRACEIDS_BINDING);
            protocolMarshaller.marshall(getTraceGraphRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
Create a instance for send sms.

@param mixed $agentName
@param mixed $tempId

@return Sms

public static function make($agentName = null, $tempId = null)
    {
        $sms = new self();
        $sms->type(self::TYPE_SMS);
        if (is_array($agentName)) {
            $sms->template($agentName);
        } elseif ($agentName && is_string($agentName)) {
            if ($tempId === null) {
                $sms->content($agentName);
            } elseif (is_string($tempId) || is_int($tempId)) {
                $sms->template($agentName, "$tempId");
            }
        }

        return $sms;
    }

func (_class VMClass) SetMemoryLimits(sessionID SessionRef, self VMRef, staticMin int, staticMax int, dynamicMin int, dynamicMax int) (_err error) {
	_method := "VM.set_memory_limits"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVMRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_staticMinArg, _err := convertIntToXen(fmt.Sprintf("%s(%s)", _method, "static_min"), staticMin)
	if _err != nil {
		return
	}
	_staticMaxArg, _err := convertIntToXen(fmt.Sprintf("%s(%s)", _method, "static_max"), staticMax)
	if _err != nil {
		return
	}
	_dynamicMinArg, _err := convertIntToXen(fmt.Sprintf("%s(%s)", _method, "dynamic_min"), dynamicMin)
	if _err != nil {
		return
	}
	_dynamicMaxArg, _err := convertIntToXen(fmt.Sprintf("%s(%s)", _method, "dynamic_max"), dynamicMax)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg, _staticMinArg, _staticMaxArg, _dynamicMinArg, _dynamicMaxArg)
	return
}

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


Question:
// contains returns true and the offset if the block is in the range (and aligned), and false
// and nil otherwise.

func (r *Allocator) contains(block uid.Block) (bool, uint32) {
	return r.r.Offset(block)
}

public static MBlockPos fromLong(long serialized)
	{
		int j = (int) (serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS);
		int k = (int) (serialized << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS);
		int l = (int) (serialized << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS);
		return new MBlockPos(j, k, l);
	}

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


Question:
Get the client's secrets using the client_id

        :param client_id: the client ID, e.g. a service ID
        :returns: list OAuthSecret instances

def client_secrets(cls, client_id):

        secrets = yield cls.view.get(key=client_id, include_docs=True)
        raise Return([cls(**secret['doc']) for secret in secrets['rows']])

def toPostArgs(self):

        args = {}

        # Add namespace definitions to the output
        for ns_uri, alias in self.namespaces.items():
            if self.namespaces.isImplicit(ns_uri):
                continue
            if alias == NULL_NAMESPACE:
                ns_key = 'openid.ns'
            else:
                ns_key = 'openid.ns.' + alias
            args[ns_key] = oidutil.toUnicode(ns_uri)

        for (ns_uri, ns_key), value in self.args.items():
            key = self.getKey(ns_uri, ns_key)
            # Ensure the resulting value is an UTF-8 encoded *bytestring*.
            args[key] = oidutil.toUnicode(value)

        return args

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


Question:
// SetLastSent is a bulk call that sets the log forwarding "last sent"
// record ID for each requested target.

func (api *LogForwardingAPI) SetLastSent(args params.LogForwardingSetLastSentParams) params.ErrorResults {
	results := make([]params.ErrorResult, len(args.Params), len(args.Params))
	for i, arg := range args.Params {
		results[i].Error = api.set(arg)
	}
	return params.ErrorResults{
		Results: results,
	}
}

def _translate_ldm(self, oprnd1, oprnd2, oprnd3):

        assert oprnd1.size and oprnd3.size
        assert oprnd1.size == self._address_size

        op1_var = self._translate_src_oprnd(oprnd1)
        op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)

        exprs = []

        for i in reversed(range(0, oprnd3.size, 8)):
            exprs += [self._mem_curr[op1_var + i // 8] == smtfunction.extract(op3_var, i, 8)]

        return exprs + op3_var_constrs

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


Question: // SetLastUpdatedAt sets the LastUpdatedAt field's value.

func (s *SimulationJobSummary) SetLastUpdatedAt(v time.Time) *SimulationJobSummary {
	s.LastUpdatedAt = &v
	return s
}

public function change()
    {
        $tableName = 'language_translations';
        if (!$this->hasTable($tableName)) {
            $tableName = 'translations';
        }

        $table = $this->table($tableName);
        if ($table->hasColumn('created')) {
            $table->changeColumn('created', 'datetime', [
                'default' => null,
                'null' => true
            ]);
        }
        if ($table->hasColumn('modified')) {
            $table->changeColumn('modified', 'datetime', [
                'default' => null,
                'null' => true
            ]);
        }
        $table->save();
    }

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


Question:
Expire the rememberme cookie, unset $_COOKIE[$this->cookieName] value and
remove current login triplet from storage.
@return boolean

public function clearCookie()
    {

        $triplet = Triplet::fromString($this->cookie->getValue());

        $this->cookie->deleteCookie();

        if (!$triplet->isValid()) {
            return false;
        }

        $this->storage->cleanTriplet($triplet->getCredential(), $triplet->getSaltedPersistentToken($this->salt));

        return true;
    }

public void removeUserFromGroup(String username, String groupname) throws CmsException {

        m_securityManager.removeUserFromGroup(m_context, username, groupname, false);
    }

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


Question:
Stores an attribute in this Simon. Attributes can be used to store any custom objects.

@param name a String specifying the name of the attribute
@param value the Object to be stored
@since 2.3

@Override
	public void setAttribute(String name, Object value) {
		attributesSupport.setAttribute(name, value);
	}

public function getExportStorageService($default = null)
    {
        $storage = array_get($this->manifest, 'storage', $default);

        if (is_array($storage)) {
            $name = array_get($storage, 'name', array_get($storage, 'id', $default));
            if (is_numeric($name)) {
                return ServiceManager::getServiceNameById($name);
            }

            return $name;
        }

        return $storage;
    }

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


Question: Use this API to fetch the statistics of all cachepolicylabel_stats resources that are configured on netscaler.

public static cachepolicylabel_stats[] get(nitro_service service) throws Exception{
		cachepolicylabel_stats obj = new cachepolicylabel_stats();
		cachepolicylabel_stats[] response = (cachepolicylabel_stats[])obj.stat_resources(service);
		return response;
	}

func (d *RoleBindingDescriber) Describe(namespace, name string, settings describe.DescriberSettings) (string, error) {
	c := d.c.RoleBindings(namespace)
	roleBinding, err := c.Get(name, metav1.GetOptions{})
	if err != nil {
		return "", err
	}

	var role *authorizationapi.Role
	if len(roleBinding.RoleRef.Namespace) == 0 {
		var clusterRole *authorizationapi.ClusterRole
		clusterRole, err = d.c.ClusterRoles().Get(roleBinding.RoleRef.Name, metav1.GetOptions{})
		role = authorizationapi.ToRole(clusterRole)
	} else {
		role, err = d.c.Roles(roleBinding.RoleRef.Namespace).Get(roleBinding.RoleRef.Name, metav1.GetOptions{})
	}

	return DescribeRoleBinding(roleBinding, role, err)
}

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


Question:
NOTE: This method is used by hierarchy report template, harmless for others.
Creates the HTML fragments for any features assigned to this suite,
and stores them in `featureMarkup` attribute of the suite so we can render them in index.tmpl

@param suite

function (suite) {
        return _.template(readFileForRespectiveTemplates('features.html'))({
            suite: suite,
            _: _,
            calculateDuration: calculateDuration,
            columnLayoutWidth: getColumnLayoutWidth(),
            decideScenarioTitlePadding: preventOverlappingTheScenarioTitle
        });
    }

private void buildDefinitionTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
        markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
    }

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


Question:
// Export enables an NFS export on the cluster to access the volumes.  Return the path to the export
// so other processes can mount the volume directory

func Export(
	ctx context.Context,
	client api.Client,
	path string) (err error) {
	// PAPI call: POST https://1.2.3.4:8080/platform/1/protocols/nfs/exports/
	//            Content-Type: application/json
	//            {paths: ["/path/to/volume"]}

	if path == "" {
		return errors.New("no path set")
	}

	var data = &ExportPathList{Paths: []string{path}}
	data.MapAll.User = client.User()
	if group := client.Group(); group != "" {
		data.MapAll.Groups = append(data.MapAll.Groups, group)
	}
	var resp *postIsiExportResp

	err = client.Post(ctx, exportsPath, "", nil, nil, data, &resp)

	if err != nil {
		return err
	}

	return nil
}

def _parse_caps_cpu(node):
    '''

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

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

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

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

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

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

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

            result[name] = host_model

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

    return result

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


Question:
// CustomHostname inspects the given custom hostname in the given zone.
//
// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-custom-hostname-configuration-details

func (api *API) CustomHostname(zoneID string, customHostnameID string) (CustomHostname, error) {
	uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID
	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return CustomHostname{}, errors.Wrap(err, errMakeRequestError)
	}

	var response CustomHostnameResponse
	err = json.Unmarshal(res, &response)
	if err != nil {
		return CustomHostname{}, errors.Wrap(err, errUnmarshalError)
	}

	return response.Result, nil
}

def create(self, name, provider='AwsEKS'):

        # ----- Create K8s cluster on provider -------
        # Create cluster object
        Cluster = getattr(providers, provider)
        cluster = Cluster(name=name, ssh_key_name='zsailer')
        cluster.create()

        # -------- Add cluster to kubeconf -----------

        # Add cluster to kubeconf
        self.kubeconf.open()
        self.kubeconf.add_cluster(
            cluster.cluster_name,
            server=cluster.endpoint_url,
            certificate_authority_data=cluster.ca_cert
        )

        # Add a user to kubeconf
        self.kubeconf.add_user(name)

        # Add a user exec call for this provider.
        self.kubeconf.add_to_user(
            name,
            **cluster.kube_user_data
        )

        # Add context mapping user to cluster.
        self.kubeconf.add_context(
            name,
            cluster_name=cluster.cluster_name,
            user_name=cluster.name
        )

        # Switch contexts.
        self.kubeconf.set_current_context(name)

        # Commit changes to file.
        self.kubeconf.close()

        # ------ Setup autorization -------
        kubectl('apply', input=cluster.get_auth_config())

        # -------- Setup Storage ----------
        kubectl('delete', 'storageclass', 'gp2')
        kubectl('apply', input=cluster.get_storage_config())

        # ------- setup helm locally ------
        kubectl(
            '--namespace',
            'kube-system',
            'create',
            'serviceaccount',
            'tiller'
        )

        kubectl(
            'create',
            'clusterrolebinding',
            'tiller',
            '--clusterrole=cluster-admin',
            '--serviceaccount=kube-system:tiller'
        )

        # -------- Initialize Helm -----------
        helm(
            'init',
            '--service-account',
            'tiller'
        )

        # --------- Secure Helm --------------
        kubectl(
            'patch',
            'deployment',
            'tiller-deploy',
            namespace='kube-system',
            type='json',
            patch='[{"op": "add", "path": "/spec/template/spec/containers/0/command", "value": ["/tiller", "--listen=localhost:44134"]}]'
        )

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


Question:
Adds an address to the campaign.

 @param [String] addr
   The address that will be targeted.

 @return [Target]
   The new target of the campaign.

 @raise [RuntimeError]
   The given address could not be found.

 @since 1.0.0

 @api public

def target!(addr)
      unless (address = Address.first(:address => addr))
        raise("unknown address #{addr.dump}")
      end

      return Target.first_or_create(:campaign => self, :address => address)
    end

public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(stack.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(stack.getName(), NAME_BINDING);
            protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING);
            protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING);
            protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING);
            protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING);
            protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING);
            protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING);
            protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING);
            protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param mixed $value

@return $this

@throws \InvalidArgumentException

public function setValue($value)
    {
        if (null !== $value) {
            if (!$this->validateValue($value)) {
                throw new \InvalidArgumentException(\sprintf(
                    'Binding invalid value (type "%s") into filter "%s" (%s)',
                    \is_object($value) ? \get_class($value) : \gettype($value),
                    $this->name,
                    \get_class($this)
                ));
            }

            $this->value = $value;
            $this->updateBound();
        }

        return $this;
    }

function (arg) {
    var self = this;

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

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

    return argCode;
  }

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


Question: Removes all items from dataset.

function(){
      Dataset.flushChanges(this);

      var deleted = this.getItems();
      var listenHandler = this.listen.item;
      var delta;

      if (deleted.length)
      {
        if (listenHandler)
          for (var i = 0; i < deleted.length; i++)
            deleted[i].removeHandler(listenHandler, this);

        this.emit_itemsChanged(delta = {
          deleted: deleted
        });

        this.members_ = {};
      }

      return delta;
    }

func indexDelete(storer Storer, tx *bolt.Tx, key []byte, originalData interface{}) error {
	indexes := storer.Indexes()

	for name, index := range indexes {
		err := indexUpdate(storer.Type(), name, index, tx, key, originalData, true)
		if err != nil {
			return err
		}
	}

	return nil
}

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


Question:
Create mask.

@param $maskPath
@param $width
@param $height

@return ImageInterface

protected function createMask($maskPath, $width, $height)
    {
        $mask = $this->imagine->open($maskPath);
        $mask->resize(
            new Box(
                $width ?: 1,
                $height ?: 1
            )
        );

        return $mask;
    }

public function getAllTransformations() {
		$t = array();
		$bits = $this->bits;
		$t['T0'] = $bits;
		for ($i=1; $i<12; $i++) {
			$bits = \ianring\BitmaskUtils::rotateBitmask($bits, $direction = 1, $amount = 1);
			$t['T' . $i] = $bits;
		}

		$bits = \ianring\BitmaskUtils::reflectBitmask($this->bits);
		$t['T0I'] = $bits;
		for ($i=1; $i<12; $i++) {
			$bits = \ianring\BitmaskUtils::rotateBitmask($bits, $direction = 1, $amount = 1);
			$t['T' . $i . 'I'] = $bits;
		}
		return $t;
	}

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


Question:
// Print Row Information to a writer and merge identical cells.
// Adjust column alignment based on type

func (t *Table) printRowMergeCells(writer io.Writer, columns [][]string, rowIdx int, previousLine []string) ([]string, []bool) {
	// Get Maximum Height
	max := t.rs[rowIdx]
	total := len(columns)

	// Pad Each Height
	pads := []int{}

	// Checking for ANSI escape sequences for columns
	is_esc_seq := false
	if len(t.columnsParams) > 0 {
		is_esc_seq = true
	}
	for i, line := range columns {
		length := len(line)
		pad := max - length
		pads = append(pads, pad)
		for n := 0; n < pad; n++ {
			columns[i] = append(columns[i], "  ")
		}
	}

	var displayCellBorder []bool
	t.fillAlignment(total)
	for x := 0; x < max; x++ {
		for y := 0; y < total; y++ {

			// Check if border is set
			fmt.Fprint(writer, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn))

			fmt.Fprintf(writer, SPACE)

			str := columns[y][x]

			// Embedding escape sequence with column value
			if is_esc_seq {
				str = format(str, t.columnsParams[y])
			}

			if t.autoMergeCells {
				//Store the full line to merge mutli-lines cells
				fullLine := strings.Join(columns[y], " ")
				if len(previousLine) > y && fullLine == previousLine[y] && fullLine != "" {
					// If this cell is identical to the one above but not empty, we don't display the border and keep the cell empty.
					displayCellBorder = append(displayCellBorder, false)
					str = ""
				} else {
					// First line or different content, keep the content and print the cell border
					displayCellBorder = append(displayCellBorder, true)
				}
			}

			// This would print alignment
			// Default alignment  would use multiple configuration
			switch t.columnsAlign[y] {
			case ALIGN_CENTER: //
				fmt.Fprintf(writer, "%s", Pad(str, SPACE, t.cs[y]))
			case ALIGN_RIGHT:
				fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y]))
			case ALIGN_LEFT:
				fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y]))
			default:
				if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) {
					fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y]))
				} else {
					fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y]))
				}
			}
			fmt.Fprintf(writer, SPACE)
		}
		// Check if border is set
		// Replace with space if not set
		fmt.Fprint(writer, ConditionString(t.borders.Left, t.pColumn, SPACE))
		fmt.Fprint(writer, t.newLine)
	}

	//The new previous line is the current one
	previousLine = make([]string, total)
	for y := 0; y < total; y++ {
		previousLine[y] = strings.Join(columns[y], " ") //Store the full line for multi-lines cells
	}
	//Returns the newly added line and wether or not a border should be displayed above.
	return previousLine, displayCellBorder
}

func (t *TabletTracker) TabletsInUse() string {
	t.mu.Lock()
	defer t.mu.Unlock()

	var aliases []string
	for alias := range t.usedTablets {
		aliases = append(aliases, alias)
	}
	sort.Strings(aliases)
	return strings.Join(aliases, " ")
}

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


Question: // SetCreationTime sets the CreationTime field's value.

func (s *Dataset) SetCreationTime(v time.Time) *Dataset {
	s.CreationTime = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
If this key is pressed, {@link #result(Object)} is called with the specified object.
@see Keys

public VisDialog key (final int keycode, final Object object) {
		addListener(new InputListener() {
			@Override
			public boolean keyDown (InputEvent event, int keycode2) {
				if (keycode == keycode2) {
					result(object);
					if (!cancelHide) hide();
					cancelHide = false;
				}
				return false;
			}
		});
		return this;
	}

protected OutputsModel toOutputsModel(Output[] outputs, KnowledgeNamespace knowledgeNamespace) {
        OutputsModel outputsModel = null;
        if (outputs != null) {
            for (Output output : outputs) {
                if (output != null) {
                    OutputModel outputModel = new V1OutputModel(knowledgeNamespace.uri());
                    String from = output.from();
                    if (!UNDEFINED.equals(from)) {
                        outputModel.setFrom(from);
                    }
                    String to = output.to();
                    if (!UNDEFINED.equals(to)) {
                        outputModel.setTo(to);
                    }
                    if (outputsModel == null) {
                        outputsModel = new V1OutputsModel(knowledgeNamespace.uri());
                    }
                    outputsModel.addOutput(outputModel);
                }
            }
        }
        return outputsModel;
    }

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


Question: Heartbeat request to keep session alive.

def heartbeat(self):

        unique_id = self.new_unique_id()
        message = {
            'op': 'heartbeat',
            'id': unique_id,
        }
        self._send(message)
        return unique_id

func NewNode(cfg NodeConfig, conn HAConn, engine Engine) *Node {
	n := &Node{
		NodeConfig:           cfg,
		conn:                 conn,
		engine:               engine,
		lastMasterAdvertTime: time.Now(),
		errChannel:           make(chan error),
		recvChannel:          make(chan *advertisement, 20),
		stopSenderChannel:    make(chan seesaw.HAState),
		shutdownChannel:      make(chan bool),
	}
	n.setState(seesaw.HABackup)
	n.resetMasterDownInterval(cfg.MasterAdvertInterval)
	return n
}

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


Question:
Global achievement unlock percent.

        :rtype: float

def global_unlock_percent(self):

        percent = CRef.cfloat()
        result = self._iface.get_ach_progress(self.name, percent)

        if not result:
            return 0.0

        return float(percent)

def format_bar(self):

        pct = floor(round(self.progress/self.size, 2)*100)
        pr = floor(pct*.33)
        bar = "".join(
            ["‒" for x in range(pr)] + ["↦"] +
            [" " for o in range(self._barsize-pr-1)])
        subprogress = self.format_parent_bar() if self.parent_bar else ""
        message = "Loading{} ={}{} ({}%)".format(subprogress, bar, "☉", pct)
        return message.ljust(len(message)+5)

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


Question:
Create an array of OG tags and their values for a show.

https://developers.facebook.com/docs/sharing/webmasters

@param  object   $show       The show object.
@return array

public static function createOpenGraphTagsForShow($show) {
        return [
            'og:title'               => $show->title,
            'og:type'                => 'website',
            'og:url'                 => Config('app.url') .'/'. $show->slug,
            'og:image'               => Config('app.url') .'/'. Config::get('lasallecastfrontend.images_shows') .'/'. $show->featured_image,
            'og:description'         => $show->meta_description,
            'og:site_name'           => Config::get('lasallecmsfrontend.og_site_name'),

        ];
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('BulkOperationResponse');
        $visitor->setHeader('Content-Type', $generator->getMediaType('BulkOperationResponse'));
        $visitor->setStatus(Response::HTTP_OK);

        $generator->startHashElement('operations');

        foreach ($data->operations as $operationId => $operation) {
            $generator->startObjectElement($operationId, 'OperationResponse');

            $generator->startValueElement('statusCode', $operation->statusCode);
            $generator->endValueElement('statusCode');

            $generator->startHashElement('headers');

            foreach ($operation->headers as $name => $header) {
                $generator->startValueElement($name, $header[0]);
                $generator->endValueElement($name);
            }
            $generator->endHashElement('headers');

            $generator->startValueElement('content', $operation->content);
            $generator->endValueElement('content');

            $generator->endObjectElement($operationId);
        }
        $generator->endHashElement('operations');
        $generator->endObjectElement('BulkOperationResponse');
    }

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


Question:
Return tag, attribs (string or array), or class (string or array)

@param array $parts [description]

@return array|string

private static function classRebuild($parts)
    {
        $parts['attribs']['class'] = \array_unique($parts['attribs']['class']);
        $parts['attribs']['class'] = \array_filter($parts['attribs']['class'], 'strlen');
        \sort($parts['attribs']['class']);
        if (!$parts['classIsArray']) {
            $parts['attribs']['class'] = \implode(' ', $parts['attribs']['class']);
        }
        if ($parts['aosIs'] == 'tag') {
            return self::buildTag($parts['tagname'], $parts['attribs'], $parts['innerhtml']);
        } elseif ($parts['aosIs'] == 'attribs') {
            return $parts['attribsIsArray']
                ? $parts['attribs']
                : self::buildAttribString($parts['attribs']);
        } elseif ($parts['aosIs'] == 'class') {
            return $parts['attribs']['class'];
        }
    }

public static Type getReturnType(final String methodDescriptor) {
    // Skip the first character, which is always a '('.
    int currentOffset = 1;
    // Skip the argument types, one at a each loop iteration.
    while (methodDescriptor.charAt(currentOffset) != ')') {
      while (methodDescriptor.charAt(currentOffset) == '[') {
        currentOffset++;
      }
      if (methodDescriptor.charAt(currentOffset++) == 'L') {
        while (methodDescriptor.charAt(currentOffset++) != ';') {
          // Skip the argument descriptor content.
        }
      }
    }
    return getType(methodDescriptor, currentOffset + 1, methodDescriptor.length());
  }

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


Question:
Given a dict, returns a new dict with all the same key/values except
        for keys that had values of None.

def filter_out_none_valued_keys(self, d):
        # type: (typing.Dict[K, V]) -> typing.Dict[K, V]
        """"""
        new_d = {}
        for k, v in d.items():
            if v is not None:
                new_d[k] = v
        return new_d

def headless(self, value):

        if value is True:
            self._arguments.append('-headless')
        elif '-headless' in self._arguments:
            self._arguments.remove('-headless')

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


Question:
Force initialization of the proxy.

@return bool true if the proxy could be initialized

public function initializeProxy() : bool
    {
        if ($this->isProxyInitialized()) {
            return true;
        }

        $this->items = $this->prependedItems + $this->getRelationshipInstance()
            ->getResults($this->relationshipMethod)->all() + $this->pushedItems;

        $this->relationshipLoaded = true;

        return true;
    }

public function compile($endpoint = DefinitionRegistry::DEFAULT_ENDPOINT): Schema
    {
        if (\is_string($endpoint)) {
            $endpoint = $this->registry->getEndpoint($endpoint);
        }

        TypeRegistry::setUp($this->container, $endpoint);

        //automatically create all interface implementors
        //to avoid empty interfaces
        foreach ($endpoint->allInterfaces() as $type) {
            foreach ($type->getImplementors() as $implementor) {
                if (!TypeRegistry::has($implementor)) {
                    TypeRegistry::create($implementor);
                }
            }
        }

        $config = [
            'types' => TypeRegistry::all(),
            'typeLoader' => function ($name) {
                return TypeRegistry::get($name);
            },
        ];

        if ($endpoint->allQueries()) {
            $config['query'] = TypeRegistry::get('Query');
        } else {
            throw new \RuntimeException('Invalid Schema, at least one query is required.');
        }

        if ($endpoint->allMutations()) {
            $config['mutation'] = TypeRegistry::get('Mutation');
        }

        if ($endpoint->allSubscriptions()) {
            $config['subscription'] = TypeRegistry::get('Subscription');
        }

        if (isset($config['query']) || isset($config['mutation'])) {
            return new Schema($config);
        }

        throw new \RuntimeException('Your GraphQL schema is empty. Create your first object and query and try again');
    }

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


Question:
Get the last acl change set id from database

@return

public Long getLastAclChangeSetID(){

        if(logger.isDebugEnabled()){
            logger.debug("[getLastAclChangeSetID]");
        }

        return (Long) template.selectOne(SELECT_LAST_ACL_CHANGE_SET_ID);
    }

private function queryAddSimpleAccessPolicyCondition($policy_name, $policy, $query, $clause)
	{
		$policy_alias = $clause == 'select' ? ' AS '.$query->quoteIdent('_access_policy_'.$policy_name) : '';
		if ($this->auth->isAllMighty()) {
			$query->$clause('TRUE'.$policy_alias);
		} else {
			$query->$clause('('.$policy['sql_select'].')'.$policy_alias);
		}
	}

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


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

@param poolListOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<CloudPool> object

public Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>> listWithServiceResponseAsync(final PoolListOptions poolListOptions) {
        return listSinglePageAsync(poolListOptions)
            .concatMap(new Func1<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>, Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>>>() {
                @Override
                public Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>> call(ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    PoolListNextOptions poolListNextOptions = null;
                    if (poolListOptions != null) {
                        poolListNextOptions = new PoolListNextOptions();
                        poolListNextOptions.withClientRequestId(poolListOptions.clientRequestId());
                        poolListNextOptions.withReturnClientRequestId(poolListOptions.returnClientRequestId());
                        poolListNextOptions.withOcpDate(poolListOptions.ocpDate());
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink, poolListNextOptions));
                }
            });
    }

public function index($page = null)
    {
        $url = sprintf('buckets/%d/categories.json', $this->bucket);

        $messageTypes = $this->client->get($url, [
            'query' => [
                'page' => $page,
            ],
        ]);

        return $this->indexResponse($messageTypes, MessageType::class);
    }

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


Question:
Gets a OAuth access token.

@return String the access token

public function getAccessToken() {
    $session = $this->getSession();
    // either user session signed, or app signed
    if ($session) {
      return $session['access_token'];
    } else {
      return $this->getAppId() .'|'. $this->getApiSecret();
    }
  }

private function parse($body)
    {
        $result = array();
        $data = json_decode($body);

        $response = is_array($data->response) ? new \stdClass : $data->response;
        if (null == $response) {
            $response = $data;
        }
        $response->errors = $data->errors;
        $response->test = isset($data->test) ? $data->test : $response->test;

        if ($data->successful == true) {
            if ((isset($response->authorized)
                && $response->authorized == true)
                || (isset($response->id)
                && $response->id !== null)
            ) {
                $response->authorization_id = isset($response->id)
                    ? $response->id
                    : $response->token;
            } else {
                $response->authorization_id = null;
            }

            $response->success = true;
        } else {
            $response->success = false;
            $response->authorization_id = null;
        }

        $response->message = isset($response->message) ? $response->message : $data->errors;

        return (array) $response;

    }

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


Question: Enclose a reading within a container, e.g. '[]'.

def _enclose_readings(container, readings):
    """"""
    container_start, container_end = tuple(container)
    enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % {
        'container_start': container_start, 'container_end': container_end,
        'readings': readings}
    return enclosed_readings

def _es_content(settings):

        return {k: settings[k] for k in (ConsoleWidget.SETTING_WIDTH,
                                         ConsoleWidget.SETTING_ALIGN,
                                         ConsoleWidget.SETTING_PADDING,
                                         ConsoleWidget.SETTING_PADDING_LEFT,
                                         ConsoleWidget.SETTING_PADDING_RIGHT,
                                         ConsoleWidget.SETTING_PADDING_CHAR)}

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


Question:
Show the specified group. If the group does not exist, nothing will happen.

@param group
The group object.

public void unhide(Object group) {
		if (isAttached()) {
			Element element = helper.getGroup(group);
			if (element != null) {
				Dom.setElementAttribute(element, "display", "inline");
			}
		}
	}

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

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

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

        return $parameters;
    }

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


Question:
Accessor to get the location of the binary

@param string $program Name of binary
@return string

protected function bin($program = '')
    {
        // Get list of allowed search paths
        if ($location = $this->config()->get('binary_location')) {
            $locations = [$location];
        } else {
            $locations = $this->config()->get('search_binary_locations');
        }

        // Find program in each path
        foreach ($locations as $location) {
            $path = "{$location}/{$program}";
            if (file_exists($path)) {
                return $path;
            }
            if (file_exists($path . '.exe')) {
                return $path . '.exe';
            }
        }

        // Not found
        return null;
    }

protected int decodeMandatoryParameters(ISUPParameterFactory parameterFactory, byte[] b, int index)
            throws ParameterException {
        int localIndex = index;
        index += super.decodeMandatoryParameters(parameterFactory, b, index);
        if (b.length - index > 1) {

            try {
                byte[] informationInd = new byte[2];
                informationInd[0] = b[index++];
                informationInd[1] = b[index++];
                InformationIndicators bci = parameterFactory.createInformationIndicators();
                ((AbstractISUPParameter) bci).decode(informationInd);
                this.setInformationIndicators(bci);
            } catch (Exception e) {
                // AIOOBE or IllegalArg
                throw new ParameterException("Failed to parse BackwardCallIndicators due to: ", e);
            }

            // return 3;
            return index - localIndex;
        } else {
            throw new IllegalArgumentException("byte[] must have atleast 2 octets");
        }
    }

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


Question:
checks if a value is cached for a cache key.

@param string $cacheKey
@return bool|string

public function isCached($cacheKey)
    {
        // TODO: Refactor for strict types!
        $path = $this->resolvePath($cacheKey, false);
        if (file_exists($path)) {
            return $path;
        } else {
            return false;
        }
    }

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

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


Question:
Fetch upcoming entries based on the lifespan or now.
@return CollectionLoader

public function archive()
    {
        $lifespan = $this->lifespan();
        $date = is_string($lifespan) ? new DateTime($lifespan) : new DateTime();

        return $this->to($date);
    }

public function solveFetch(Entity &$entity)
    {
        // We need to find all target entities with the ID defined in the current entity source column
        $column = $this->relation->join->column;

        $value = $entity->{$column};
        $where = array($this->relation->join->targetColumn => $value);

        $query = EntityManager::find($this->relation->targetEntity);
        return $query->where($where)->all();
    }

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


Question:
Checks if a cached file already exist in cache. Namespace is taken into account.

@param string $identifier    The identifier
@param string $fileExtension If not set, a file with no file extension is searched

@throws \Exception

@return bool

public function exist(string $identifier, string $fileExtension = '')
    {
        $fileName = $this->getCacheFileName($identifier);
        $cachePath = $this->cacheFolderWithNamespace.'/'.$fileName;

        if (!empty($fileExtension)) {
            $cachePath .= '.'.$fileExtension;
        }
        $file = new File($cachePath);

        if ($file->exists()) {
            return true;
        }

        return false;
    }

public static function duplicate_template($id) {
        global $PAGE;

        $params = self::validate_parameters(self::duplicate_template_parameters(), array('id' => $id));

        $template = api::read_template($params['id']);
        self::validate_context($template->get_context());
        $output = $PAGE->get_renderer('core');

        $result = api::duplicate_template($params['id']);
        $exporter = new template_exporter($result);
        return $exporter->export($output);
    }

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


Question:
Called by MetricsRecordImpl.update().  Creates or updates a row in
the internal table of metric data.

protected void update(MetricsRecordImpl record) {
    String recordName = record.getRecordName();
    TagMap tagTable = record.getTagTable();
    Map<String,MetricValue> metricUpdates = record.getMetricTable();

    RecordMap recordMap = getRecordMap(recordName);
    synchronized (recordMap) {
      MetricMap metricMap = recordMap.get(tagTable);
      if (metricMap == null) {
        metricMap = new MetricMap();
        TagMap tagMap = new TagMap(tagTable); // clone tags
        recordMap.put(tagMap, metricMap);
      }

      Set<Entry<String, MetricValue>> entrySet = metricUpdates.entrySet();
      for (Entry<String, MetricValue> entry : entrySet) {
        String metricName = entry.getKey ();
        MetricValue updateValue = entry.getValue ();
        Number updateNumber = updateValue.getNumber();
        Number currentNumber = metricMap.get(metricName);
        if (currentNumber == null || updateValue.isAbsolute()) {
          metricMap.put(metricName, updateNumber);
        }
        else {
          Number newNumber = sum(updateNumber, currentNumber);
          metricMap.put(metricName, newNumber);
        }
      }
    }
  }

private LogRecordDO modelToDo(LogRecord entityObj) {

        LogRecordDO logRecordDo = new LogRecordDO();
        try {

            if (entityObj.getPipeline() != null && entityObj.getPipeline().getId() > 0) {
                Channel channel = channelService.findByPipelineId(entityObj.getPipeline().getId());
                logRecordDo.setChannelId(channel.getId());
                logRecordDo.setPipelineId(entityObj.getPipeline().getId());
            } else {
                logRecordDo.setChannelId(-1l);
                logRecordDo.setPipelineId(-1l);
            }

            logRecordDo.setNid(entityObj.getNid());
            logRecordDo.setTitle(entityObj.getTitle());
            String message = entityObj.getMessage();
            if (message != null && message.length() > 65535 / 3) {
                message = message.substring(0, 65535 / 3);
            }
            logRecordDo.setMessage(message);
            logRecordDo.setGmtCreate(entityObj.getGmtCreate());
            logRecordDo.setGmtModified(entityObj.getGmtModified());

        } catch (Exception e) {
            logger.error("ERROR ## has an error where write log to db");
            throw new ManagerException(e);
        }
        return logRecordDo;
    }

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


Question:
@param Node            $node
@param string|string[] $checkedFunctionName If an array as passed, function names should be keys

@return bool

public function isFunctionCallByStaticName(Node $node, $checkedFunctionName)
    {
        $isFunctionCallByStaticName = $node instanceof Node\Expr\FuncCall && $node->name instanceof Node\Name;
        if (!$isFunctionCallByStaticName) {
            return $isFunctionCallByStaticName;
        }

        $calledFunctionName = strtolower($node->name->toString());

        return is_array($checkedFunctionName)
            ? isset($checkedFunctionName[$calledFunctionName])
            : $calledFunctionName === $checkedFunctionName;
    }

func (s *RebootNodeInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RebootNodeInput"}
	if s.ClusterName == nil {
		invalidParams.Add(request.NewErrParamRequired("ClusterName"))
	}
	if s.NodeId == nil {
		invalidParams.Add(request.NewErrParamRequired("NodeId"))
	}

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

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


Question: Creates and populates a (not necessarily power of two) texture for use as our main texture.

protected int createMainTex() {
    // the mipmaps flag is always false here because we only ever generate mipmaps for our
    // power-of-two textures; scaleTexture will use tex to create the POT texture, so tex should
    // not have mipmaps enabled, or it will hose up that process
    int tex = ctx.createTexture(false, false, false);
    updateTexture(tex);
    return tex;
  }

def __taint_load(self, instr):

        # Get memory address.
        op0_val = self.__emu.read_operand(instr.operands[0])

        # Get taint information.
        op0_taint = self.get_memory_taint(op0_val, instr.operands[2].size // 8)

        # Propagate taint.
        self.set_operand_taint(instr.operands[2], op0_taint)

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


Question:
Set the file contents to be sent.

@param string $fileContents
@param string $type
@param string $suggestedFileName
@param string $disposition
@param bool   $ignore_user_abort

@return $this

public function setFileContents($fileContents, $type = self::CONTENT_APP_STREAM, $suggestedFileName = '', $disposition = 'attachment', $ignore_user_abort = false)
    {
        // Set response headers
        $this->setHeaders($type, $suggestedFileName, $disposition, $ignore_user_abort);

        // Set response content
        $this->content = $fileContents;

        return $this;
    }

public function getFile($fax_id, $format = null)
    {
        list($response) = $this->getFileWithHttpInfo($fax_id, $format);
        return $response;
    }

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


Question: // AddRoutes sets up routes for the provided objects.

func AddRoutes(objects Objects) Objects {
	routes := []runtime.Object{}
	for _, o := range objects {
		switch t := o.(type) {
		case *kapi.Service:
			routes = append(routes, &routeapi.Route{
				ObjectMeta: metav1.ObjectMeta{
					Name:   t.Name,
					Labels: t.Labels,
				},
				Spec: routeapi.RouteSpec{
					To: routeapi.RouteTargetReference{
						Name: t.Name,
					},
				},
			})
		}
	}
	return append(objects, routes...)
}

protected function registerSettingsSection($slug,$title,$description)
    {
        $this->settingSections[$slug]=[
            'title'=>$title,
            'description'=>$description,
            'fields'=>[]
        ];

        add_settings_section($slug,$title,[$this,'renderSettingsSection'],$this->options_page);
    }

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


Question:
Load the document with the given id.

@param  int  $documentId  The id of the document to load.
@param  DmsLoaderParams  $params  The configured params to use while loading.
@return  document  Returns the document.

public function loadDocument($documentId, \DmsLoaderParams $params)
  {
    $objDocument = $this->Database->prepare("SELECT d.*, CONCAT(m1.firstname, ' ', m1.lastname) AS upload_member_name, CONCAT(m2.firstname, ' ', m2.lastname) AS lastedit_member_name "
                        . "FROM tl_dms_documents d "
                        . "LEFT JOIN tl_member m1 ON m1.id = d.upload_member "
                        . "LEFT JOIN tl_member m2 ON m2.id = d.lastedit_member "
                        . "WHERE d.id = ?")
                    ->limit(1)
                    ->execute($documentId);

    $document = null;
    if ($objDocument->numRows)
    {
      $document = $this->buildDocument($objDocument);
      if ($params->loadCategory)
      {
        $document->category = $this->loadCategory($document->categoryId, $params);
      }
    }

    return $document;
  }

public function api()
    {
        if (config('swagger-lume.generate_always')) {
            Generator::generateDocs();
        }

        //need the / at the end to avoid CORS errors on Homestead systems.
        $response = new Response(
            view('swagger-lume::index', [
                'secure' => Request::secure(),
                'urlToDocs' => route('swagger-lume.docs'),
                'operationsSorter' => config('swagger-lume.operations_sort'),
                'configUrl' => config('swagger-lume.additional_config_url'),
                'validatorUrl' => config('swagger-lume.validator_url'),
            ]),
            200,
            ['Content-Type' => 'text/html']
        );

        return $response;
    }

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


Question:
Find a template path

@param array  $info      The path information
@return array

public function find(array $info)
    {
        $locator = $this->getObject('manager')->getClassLoader()->getLocator('module');

        //Get the package
        $package = $info['package'];

        //Get the domain
        $domain = $info['domain'];

        //Switch basepath
        if(!$locator->getNamespace(ucfirst($package))) {
            $basepath = $locator->getNamespace('\\');
        } else {
            $basepath = $locator->getNamespace(ucfirst($package));
        }

        $basepath .= '/mod_'.strtolower($package);

        return array('mod_'.$package => $basepath);
    }

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

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


Question: // Create an environment

func (es *EnvironmentsService) Create(ctx context.Context, name string) (e *Environment, resp *APIResponse, err error) {
	_, resp, err = es.client.postAction(ctx, &APIClientRequest{
		Path: "admin/environments/",
		RequestBody: Environment{
			Name: name,
		},
		ResponseBody: &e,
		APIVersion:   apiV2,
	})

	return
}

func Env(key, fallback string) string {
	v := os.Getenv(key)
	if v != "" {
		return v
	}

	return fallback
}

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


Question: // SetCaseId sets the CaseId field's value.

func (s *Communication) SetCaseId(v string) *Communication {
	s.CaseId = &v
	return s
}

def setup(cls, client_id, client_secret):

        cls.client_id = client_id
        cls.client_secret = client_secret

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


Question:
用户退出登录

@param $req
@return \Wei\Response

public function logoutAction($req)
    {
        wei()->curUser->logout();

        $next = $req('next', $this->request->getReferer());

        return $this->response->redirect($next);
    }

func (wc *WebhookContext) Form() uurl.Values {
	//todo: bug, RAW() unavailable after ParseForm()
	wc.gin.Request.ParseForm()
	return wc.gin.Request.PostForm
}

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


Question:
Decrypts PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
    (Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).

def decrypt_PBEWithSHAAndTwofishCBC(encrypted_data, password, salt, iteration_count):

    iv  = derive_key(hashlib.sha1, PURPOSE_IV_MATERIAL,  password, salt, iteration_count, 16)
    key = derive_key(hashlib.sha1, PURPOSE_KEY_MATERIAL, password, salt, iteration_count, 256//8)

    encrypted_data = bytearray(encrypted_data)
    encrypted_data_len = len(encrypted_data)
    if encrypted_data_len % 16 != 0:
        raise BadDataLengthException("encrypted data length is not a multiple of 16 bytes")

    plaintext = bytearray()

    # slow and dirty CBC decrypt
    from twofish import Twofish
    cipher = Twofish(key)

    last_cipher_block = bytearray(iv)
    for block_offset in range(0, encrypted_data_len, 16):
        cipher_block = encrypted_data[block_offset:block_offset+16]
        plaintext_block = xor_bytearrays(bytearray(cipher.decrypt(bytes(cipher_block))), last_cipher_block)
        plaintext.extend(plaintext_block)
        last_cipher_block = cipher_block

    plaintext = strip_pkcs7_padding(plaintext, 16)
    return bytes(plaintext)

public function queryParameter($key)
    {
        $keys = array_pluck($this->queryParameters, 'key');
        $queryParameters = array_combine($keys, $this->queryParameters);

        return $queryParameters[$key];
    }

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


Question:
Entry point to the Callback Filtering Example.

@param args unused

public static void main(String[] args) {
		// manager with two stopwatches is created
		Manager manager = new EnabledManager();
		Stopwatch sw1 = manager.getStopwatch("org.javasimon.examples.stopwatch1");
		Stopwatch sw2 = manager.getStopwatch("other.stopwatch2");

		// simple callback printing actions to the stdout is created and installed
		Callback stdoutCallback = new CallbackSkeleton() {
			@Override
			public void onStopwatchStart(Split split) {
				System.out.println("Starting " + split.getStopwatch().getName());
			}

			@Override
			public void onStopwatchStop(Split split, StopwatchSample sample) {
				System.out.println("Stopped " + split.getStopwatch().getName() + " (" + SimonUtils.presentNanoTime(split.runningFor()) + ")");
			}
		};
		manager.callback().addCallback(stdoutCallback);

		// prints start/stop for both stopwatches
		sw1.start().stop();
		sw2.start().stop();
		System.out.println();

		// we need to remove old callback
		manager.callback().removeCallback(stdoutCallback);
		// alternatively you can call this if you want to remove all callbacks
		SimonManager.callback().removeAllCallbacks();

		// filter callback is created
		CompositeFilterCallback filter = new CompositeFilterCallback();
		// rule to filter out all Simons matching pattern "other.*" is added
		filter.addRule(FilterRule.Type.MUST_NOT, null, "other.*");
		// original callback is added after this callback
		filter.addCallback(stdoutCallback);

		// filter callback is installed to the manager (with printing callback behind)
		manager.callback().addCallback(filter);

		// start/stop is printed only for sw1 because sw2 matches other.* pattern that is excluded (MUST_NOT)
		sw1.start().stop();
		sw2.start().stop();
	}

private static List<ParameterFiller> parseParameters(List<String> parameters) {
    List<ParameterFiller> parameterFillers = new ArrayList<>(parameters.size());
    for (String parameter : parameters) {
      ParameterFiller parameterFiller = parseParameter(parameter);
      if (parameterFiller != null) {
        parameterFillers.add(parameterFiller);
      }
    }
    return parameterFillers;
  }

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


Question:
// Int returns a specific return parameter as an int.
// If a result has not been set, it returns 0.

func (r *MockResult) Int(i int) int {
	if r.Contains(i) {
		return r.Result[i].(int)
	} else {
		return 0
	}
}

public function getMacro($static, $doReturn, $paramCount)
    {
        /*
        $scopes = array('', 'STATIC');
        $modes = array('CALL_INTERNAL_METHOD_P', 'RETURN_CALL_INTERNAL_METHOD_P', 'CALL_INTERNAL_METHOD_NORETURN_P');
        */
        $scope = $static ? 'STATIC' : '';
        $mode = 'CALL_INTERNAL_METHOD_NORETURN_P';
        if ($doReturn) {
            $mode = 'RETURN_CALL_INTERNAL_METHOD_P';
            if (2 === $doReturn) {
                $mode = 'CALL_INTERNAL_METHOD_P';
            }
        }
        $macroName = 'ZEPHIR_'.($scope ? $scope.'_' : '').$mode.$paramCount;
        if (!$this->macroIsRequired($macroName)) {
            $this->requiredMacros[$macroName] = [$scope, $mode, $paramCount];
        }

        return $macroName;
    }

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


Question: Reset the particle system.

function() {
        // Put all the particles back
        for (var i = 0; i < this._particles.length; i++) {
            var p = this._particles[i];
            p.emitter.kill(p);
        }
        this._particles.length = 0;
        this._elapsedTime = 0;
        this._emitting = true;
    }

func (d *Detector) clearRegions(detectedRegions Regions) {
	for _, region := range detectedRegions {
		if len(region) > 30 {
			d.SkinRegions = append(d.SkinRegions, region)
		}
	}
}

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


Question:
Get the circuit, supporting over existing transition.

@param circuit The initial circuit.
@param neighbor The neighbor tile which can be a transition.
@return The new circuit or original one.

private Circuit getCircuitOverTransition(Circuit circuit, Tile neighbor)
    {
        final String group = getTransitiveGroup(circuit, neighbor);
        final Circuit newCircuit;
        if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getIn()))
        {
            newCircuit = new Circuit(circuit.getType(), group, circuit.getOut());
        }
        else if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getOut()))
        {
            newCircuit = new Circuit(circuit.getType(), circuit.getIn(), group);
        }
        else
        {
            newCircuit = circuit;
        }
        return newCircuit;
    }

func (info DefaultNodeInfo) CompatibleWith(other_ NodeInfo) error {
	other, ok := other_.(DefaultNodeInfo)
	if !ok {
		return fmt.Errorf("wrong NodeInfo type. Expected DefaultNodeInfo, got %v", reflect.TypeOf(other_))
	}

	if info.ProtocolVersion.Block != other.ProtocolVersion.Block {
		return fmt.Errorf("Peer is on a different Block version. Got %v, expected %v",
			other.ProtocolVersion.Block, info.ProtocolVersion.Block)
	}

	// nodes must be on the same network
	if info.Network != other.Network {
		return fmt.Errorf("Peer is on a different network. Got %v, expected %v", other.Network, info.Network)
	}

	// if we have no channels, we're just testing
	if len(info.Channels) == 0 {
		return nil
	}

	// for each of our channels, check if they have it
	found := false
OUTER_LOOP:
	for _, ch1 := range info.Channels {
		for _, ch2 := range other.Channels {
			if ch1 == ch2 {
				found = true
				break OUTER_LOOP // only need one
			}
		}
	}
	if !found {
		return fmt.Errorf("Peer has no common channels. Our channels: %v ; Peer channels: %v", info.Channels, other.Channels)
	}
	return nil
}

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


Question:
Generic way to get count via UserModel->ProfileCount().

@since 2.0.?
@access public
@param string $Column Name of column to count for this user.
@param int $UserID Defaults to current session.

public function Count($Column, $UserID = FALSE) {
      $Column = 'Count'.ucfirst($Column);
      if (!$UserID)
         $UserID = Gdn::Session()->UserID;

      $Count = $this->UserModel->ProfileCount($UserID, $Column);
      $this->SetData($Column, $Count);
      $this->SetData('_Value', $Count);
      $this->SetData('_CssClass', 'Count');
      $this->Render('Value', 'Utility');
   }

public function listTables($limit = null, $exclusiveStartTableName = null)
    {
        if (null !== $this->logger) {
            $this->log('List tables');
        }

        $parameters = array();
        if (null !== $limit) {
            $parameters['Limit'] = $limit;
        }
        if (null !== $exclusiveStartTableName) {
            $parameters['ExclusiveStartTableName'] = $exclusiveStartTableName;
        }

        if (null !== $this->logger) {
            $this->log('ListTable request paramaters : '.print_r($parameters, true), Logger::DEBUG);
        }

        $response = $this->connector->listTables($parameters);

        if (null !== $this->logger) {
            $this->log('ListTable request response : '.print_r($response, true), Logger::DEBUG);
        }

        $tables = new Table\TableCollection((isset($response['LastEvaluatedTableName'])?$response['LastEvaluatedTableName']:null));
        if (!empty($response['TableNames'])) {
            foreach ($response['TableNames'] as $table) {
                $tables->add($table);
            }
        }
        return $tables;
    }

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


Question: // EncodeNameString converts org/bucket pairs to the tsdb internal serialization

func EncodeNameString(org, bucket platform.ID) string {
	name := EncodeName(org, bucket)
	return string(name[:])
}

def read_lines_from_file(cls_name, filename):
  """"""
  with tf.io.gfile.GFile(filename, "rb") as f:
    lines = [tf.compat.as_text(line)[:-1] for line in f]
  header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
  if lines[0] != header_line:
    raise ValueError("File {fname} does not seem to have been created from "
                     "{name}.save_to_file.".format(
                         fname=filename, name=cls_name))
  metadata_dict = json.loads(lines[1][len(_METADATA_PREFIX):])
  return lines[2:], metadata_dict

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


Question:
// QueryAll will query the statement and populate the given interface with all
// results.

func (db *DB) QueryAll(stmt Executable, i interface{}) error {
	result, err := db.Query(stmt)
	if err != nil {
		return err
	}
	return result.All(i)
}

protected function _parseQuota(
        Horde_Imap_Client_Interaction_Pipeline $pipeline,
        Horde_Imap_Client_Tokenize $data
    )
    {
        $c = &$pipeline->data['quotaresp'];

        $root = $data->next();
        $c[$root] = array();

        $data->next();

        while (($curr = $data->next()) !== false) {
            $c[$root][Horde_String::lower($curr)] = array(
                'usage' => $data->next(),
                'limit' => $data->next()
            );
        }
    }

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