Question: then, try to add smaller coins until we accumulate the target amount

function pickMultipleCoinsAndContinue(){
		conn.query(
			"SELECT unit, message_index, output_index, amount, address, blinding \n\
			FROM outputs \n\
			CROSS JOIN units USING(unit) \n\
			WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\
				AND sequence='good' "+confirmation_condition+"  \n\
			ORDER BY amount DESC LIMIT ?",
			[arrSpendableAddresses, constants.MAX_INPUTS_PER_PAYMENT_MESSAGE-2],
			function(rows){
				async.eachSeries(
					rows,
					function(row, cb){
						var input = row;
						objectHash.cleanNulls(input);
						required_amount += is_base*TRANSFER_INPUT_SIZE;
						addInput(input);
						// if we allow equality, we might get 0 amount for change which is invalid
						var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount);
						bFound ? cb('found') : cb();
					},
					function(err){
						if (err === 'found')
							onDone(arrInputsWithProofs, total_amount);
						else if (asset)
							issueAsset();
						else
							addHeadersCommissionInputs();
					}
				);
			}
		);
	}

def add_layer_item(self, layer):

        if not layer.is_draft_version:
            raise ValueError("Layer isn't a draft version")

        self.items.append(layer.latest_version)

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


Question:
Start commercial on channel.
Authenticated, required scope: channel_commercial

@param      $channel
@param int  $length
@param null $token

public function postCommercial($channel, $length = 30, $token = null)
    {
        $token = $this->getToken($token);

        $channelAPI = new Channels($token);

        return $channelAPI->postCommercial($channel, $length);
    }

protected function _init() {
		parent::_init();
		$this->_rules += [
			'allowAll' => [
				'rule' => function() {
					return true;
				}
			],
			'denyAll' => [
				'rule' => function() {
					return false;
				}
			],
			'allowAnyUser' => [
				'message' => 'You must be logged in.',
				'rule' => function($user) {
					return $user ? true : false;
				}
			],
			'allowIp' => [
				'message' => 'Your IP is not allowed to access this area.',
				'rule' => function($user, $request, $options) {
					$options += ['ip' => false];
					if (is_string($options['ip']) && strpos($options['ip'], '/') === 0) {
						return (boolean) preg_match($options['ip'], $request->env('REMOTE_ADDR'));
					}
					if (is_array($options['ip'])) {
						return in_array($request->env('REMOTE_ADDR'), $options['ip']);
					}
					return $request->env('REMOTE_ADDR') === $options['ip'];
				}
			]
		];
	}

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


Question:
Adds a card
@param mixed Either an array of params as per the generateToken method or simply a token
@param bool $setAsDefault
@return array

public function addCard($params, $setAsDefault = false)
    {
        if (is_array($params)) {
            $result = $this->generateToken($params);

            if ($result['status'] === 'error') {
                return $result;
            }

            $token = $result['token'];
        } else {
            $token = $params;
        }

        if (!$this->stripe_id) {
            $customer = $this->createAsStripeCustomer($token);

            $card = $this->getDefaultCard();

            return [
                'status' => 'success',
                'cardId' => $card['id']
            ];
        }

        $customerId = $this->stripe_id;

        try {
            $stripe = new Stripe(Billable::getStripeKey());

            $card = $stripe->cards()
                ->create($customerId, $token);

            if ($setAsDefault) {
                // lets set this card as the default
                $this->updateDefaultCard($card['id']);
            }

            return [
                'status' => 'success',
                'cardId' => $card['id']
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }

public function register()
    {
        $this->app->singleton('seotools.metatags', function($app) {
            return new SEOMeta(new Config($app['config']->get('seotools.meta', [])));
        });

        $this->app->singleton('seotools.opengraph', function($app) {
            return new OpenGraph($app['config']->get('seotools.opengraph', []));
        });

        $this->app->singleton('seotools.twitter', function($app) {
            return new TwitterCards($app['config']->get('seotools.twitter.defaults', []));
        });

        $this->app->singleton('seotools.json-ld', function($app) {
            return new JsonLd($app['config']->get('seotools.json-ld.defaults', []));
        });

        $this->app->singleton('seotools', function() {
            return new SEOTools();
        });

        $this->app->bind(Contracts\MetaTags::class, 'seotools.metatags');
        $this->app->bind(Contracts\OpenGraph::class, 'seotools.opengraph');
        $this->app->bind(Contracts\TwitterCards::class, 'seotools.twitter');
        $this->app->bind(Contracts\JsonLd::class, 'seotools.json-ld');
        $this->app->bind(Contracts\SEOTools::class, 'seotools');
    }

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


Question: // SetAccessLogSettings sets the AccessLogSettings field's value.

func (s *CreateStageInput) SetAccessLogSettings(v *AccessLogSettings) *CreateStageInput {
	s.AccessLogSettings = v
	return s
}

func (c *Config) OpenConnector(logger log.Logger) (interface {
	connector.Connector
	connector.PasswordConnector
	connector.RefreshConnector
}, error) {
	return c.openConnector(logger)
}

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


Question:
Get list of SDC mapped to a specific volume
        :param volObj: ScaleIO volume object
        :return: List of ScaleIO SDC objects (empty list if no mapping exist)
        :rtype: SDC object

def get_sdc_for_volume(self, volObj):

        sdcList = []
        if volObj.mapped_sdcs is not None:
            for sdc in volObj.mapped_sdcs:
                sdcList.append(sdc)
        if len(sdcList) == 0:
            self.conn.logger.debug("No SDCs mapped to volume: %s-(%s)" % (volObj.name, volObj.id))
            return []
        # returning an empty list is
        # valid for snapshots or volumes.
        return sdcList

func FromServices(services []*v1.Service) []v1.EnvVar {
	var result []v1.EnvVar
	for i := range services {
		service := services[i]

		// ignore services where ClusterIP is "None" or empty
		// the services passed to this method should be pre-filtered
		// only services that have the cluster IP set should be included here
		if !v1helper.IsServiceIPSet(service) {
			continue
		}

		// Host
		name := makeEnvVariableName(service.Name) + "_SERVICE_HOST"
		result = append(result, v1.EnvVar{Name: name, Value: service.Spec.ClusterIP})
		// First port - give it the backwards-compatible name
		name = makeEnvVariableName(service.Name) + "_SERVICE_PORT"
		result = append(result, v1.EnvVar{Name: name, Value: strconv.Itoa(int(service.Spec.Ports[0].Port))})
		// All named ports (only the first may be unnamed, checked in validation)
		for i := range service.Spec.Ports {
			sp := &service.Spec.Ports[i]
			if sp.Name != "" {
				pn := name + "_" + makeEnvVariableName(sp.Name)
				result = append(result, v1.EnvVar{Name: pn, Value: strconv.Itoa(int(sp.Port))})
			}
		}
		// Docker-compatible vars.
		result = append(result, makeLinkVariables(service)...)
	}
	return result
}

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


Question:
Expected number of coefficients in a 2D transformation of a given order.

    Parameters
    ----------
    order : int
        Order of the 2D polynomial transformation.

    Returns
    -------
    ncoef : int
        Expected number of coefficients.

def ncoef_fmap(order):

    ncoef = 0
    for i in range(order + 1):
        for j in range(i + 1):
            ncoef += 1
    return ncoef

def output_format_module(self, packages, esc_path=False):

        def create_ordered_list(packages_):
            """
            Recursive for package.packages
            """
            list_ = []
            for _pkg_name in packages_:
                _pkg = packages_[_pkg_name]
                if _pkg and _pkg.packages:
                    list_.extend(create_ordered_list(_pkg.packages))
                if _pkg:
                    _pkg_params = _pkg.get_params(self._columns, True)
                    _res_item = {}
                    for item in self._output_config['columns']:
                        name = item['name'].format(OutFormat(item['column']))
                        value = _pkg_params.get(item['column'], '')
                        if not isinstance(value, (list, dict, tuple)):
                            try:
                                value = item['value'].format(
                                    OutFormat(value, (item['column'] == 'path') if esc_path else False))
                            except Exception:
                                value = ''
                        # TODO: implement this:
                        # if not value:
                        #     try:
                        #         value = item['value'].format(OutFormat(_pkg.get_params('', True)))
                        #     except Exception as e:
                        #         pass
                        _res_item[name] = value
                    list_.append(_res_item)
            return list_

        result_list = create_ordered_list(packages, )

        if self._output_config['type'] == LIST:
            return result_list

        result = OrderedDict()
        for item in result_list:
            # TODO: Error handling
            name = item[self._output_config['key']]
            if self._output_config['value']:
                value = item[self._output_config['value']]
            else:
                value = OrderedDict([(k, v) for k, v in item.items() if k != self._output_config['key']])

            result[name] = value

        return result

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


Question: // getRepoNames returns the repo names of the referenced deps which can be used to fetch the cahced index file.

func (m *Manager) getRepoNames(deps []*chartutil.Dependency) (map[string]string, error) {
	rf, err := repo.LoadRepositoriesFile(m.HelmHome.RepositoryFile())
	if err != nil {
		return nil, err
	}
	repos := rf.Repositories

	reposMap := make(map[string]string)

	// Verify that all repositories referenced in the deps are actually known
	// by Helm.
	missing := []string{}
	for _, dd := range deps {
		if dd.Repository == "" {
			return nil, fmt.Errorf("no 'repository' field specified for dependency: %q", dd.Name)
		}
		// if dep chart is from local path, verify the path is valid
		if strings.HasPrefix(dd.Repository, "file://") {
			if _, err := resolver.GetLocalPath(dd.Repository, m.ChartPath); err != nil {
				return nil, err
			}

			if m.Debug {
				fmt.Fprintf(m.Out, "Repository from local path: %s\n", dd.Repository)
			}
			reposMap[dd.Name] = dd.Repository
			continue
		}

		found := false

		for _, repo := range repos {
			if (strings.HasPrefix(dd.Repository, "@") && strings.TrimPrefix(dd.Repository, "@") == repo.Name) ||
				(strings.HasPrefix(dd.Repository, "alias:") && strings.TrimPrefix(dd.Repository, "alias:") == repo.Name) {
				found = true
				dd.Repository = repo.URL
				reposMap[dd.Name] = repo.Name
				break
			} else if urlutil.Equal(repo.URL, dd.Repository) {
				found = true
				reposMap[dd.Name] = repo.Name
				break
			}
		}
		if !found {
			missing = append(missing, dd.Repository)
		}
	}
	if len(missing) > 0 {
		if len(missing) > 0 {
			errorMessage := fmt.Sprintf("no repository definition for %s. Please add them via 'helm repo add'", strings.Join(missing, ", "))
			// It is common for people to try to enter "stable" as a repository instead of the actual URL.
			// For this case, let's give them a suggestion.
			containsNonURL := false
			for _, repo := range missing {
				if !strings.Contains(repo, "//") && !strings.HasPrefix(repo, "@") && !strings.HasPrefix(repo, "alias:") {
					containsNonURL = true
				}
			}
			if containsNonURL {
				errorMessage += `
Note that repositories must be URLs or aliases. For example, to refer to the stable
repository, use "https://kubernetes-charts.storage.googleapis.com/" or "@stable" instead of
"stable". Don't forget to add the repo, too ('helm repo add').`
			}
			return nil, errors.New(errorMessage)
		}
	}
	return reposMap, nil
}

def query(self):
        """"""

        self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
        self._head = HeadRevision(self._p4dict)

        self._filename = self.depotFile

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


Question:
Sets the description text of the gauge. This description text will usually
only be visible if it is not empty.

@param DESCRIPTION

public void setDescription(final String DESCRIPTION) {
        if (null == description) {
            _description = DESCRIPTION;
            fireTileEvent(VISIBILITY_EVENT);
            fireTileEvent(REDRAW_EVENT);
        } else {
            description.set(DESCRIPTION);
        }
    }

protected function render() : string
    {
        $styles = $this->styles();
        if (strlen($styles) > 0) {
            $styles = 'style="' . trim($styles) . '"';
        }

        return '

classes() .
            '" role="progressbar" ' . $styles . ' aria-valuenow="' . $this->value .
            '" aria-valuemin="0" aria-valuemax="100">' .
            (($this->label !== null) ? $this->label : null) . '

';
    }

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


Question:
omits externals without a description
@static

function _globals (options) {
  options.hash.scope = 'global'
  return _identifiers(options).filter(function (identifier) {
    if (identifier.kind === 'external') {
      return identifier.description && identifier.description.length > 0
    } else {
      return true
    }
  })
}

public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){

		int numberOfStrikes = strikes.length;
		HashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>();

		LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);
		for(int i = 0; i< numberOfStrikes; i++) {
			descriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i]));
		}

		return descriptors;
	}

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


Question:
Prepare params

@param array $params
@return array

protected function prepareParams(array $params)
    {
        $result = $params;

        foreach ($result as $key => $val) {
            if (is_bool($val)) {
                $result[$key] = $val ? 1 : 0;
            }
        }

        return $result;
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question:
// Updates a comment on a commit
//
// https://developer.github.com/v3/repos/comments/#update-a-commit-comment

func (c *CommitCommentsService) Update(uri *Hyperlink, uriParams M, requestParams interface{}) (comment *CommitComment, result *Result) {
	url, err := ExpandWithDefault(uri, &RepoCommentsURL, uriParams)
	if err != nil {
		return nil, &Result{Err: err}
	}

	result = c.client.patch(url, requestParams, &comment)
	return
}

func (s *Action) History(ctx context.Context, c *cli.Context) error {
	name := c.Args().Get(0)
	showPassword := c.Bool("password")

	if name == "" {
		return ExitError(ctx, ExitUsage, nil, "Usage: %s history <NAME>", s.Name)
	}

	if !s.Store.Exists(ctx, name) {
		return ExitError(ctx, ExitNotFound, nil, "Secret not found")
	}

	revs, err := s.Store.ListRevisions(ctx, name)
	if err != nil {
		return ExitError(ctx, ExitUnknown, err, "Failed to get revisions: %s", err)
	}

	for _, rev := range revs {
		pw := ""
		if showPassword {
			sec, err := s.Store.GetRevision(ctx, name, rev.Hash)
			if err != nil {
				out.Debug(ctx, "Failed to get revision '%s' of '%s': %s", rev.Hash, name, err)
			}
			if err == nil {
				pw = " - " + sec.Password()
			}
		}
		out.Print(ctx, "%s - %s <%s> - %s - %s%s", rev.Hash[:8], rev.AuthorName, rev.AuthorEmail, rev.Date.Format(time.RFC3339), rev.Subject, pw)
	}
	return nil
}

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


Question: 通过Mapper方法名获取sql

public static String getMapperSql(SqlSession session, String fullMapperMethodName, Object... args) {
        if (args == null || args.length == 0) {
            return getNamespaceSql(session, fullMapperMethodName, null);
        }
        String methodName = fullMapperMethodName.substring(fullMapperMethodName.lastIndexOf('.') + 1);
        Class<?> mapperInterface = null;
        try {
            mapperInterface = Class.forName(fullMapperMethodName.substring(0, fullMapperMethodName
                    .lastIndexOf('.')));
            return getMapperSql(session, mapperInterface, methodName, args);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("参数" + fullMapperMethodName + "无效！");
        }
    }

func MysqlPort(tablet *topodatapb.Tablet) int32 {
	if tablet.MysqlHostname == "" {
		return tablet.PortMap["mysql"]
	}
	return tablet.MysqlPort
}

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


Question:
$terminate delivery execution
@param DeliveryExecution $deliveryExecution

protected function terminateExecution(DeliveryExecution $deliveryExecution) {
        if ($this->wetRun === true) {
            $deliveryExecutionStateService = ServiceManager::getServiceManager()->get(DeliveryExecutionStateService::SERVICE_ID);
            $deliveryExecutionStateService->terminateExecution(
                $deliveryExecution,
                [
                    'reasons' => $this->getTerminationReasons(),
                    'comment' => __('The assessment was automatically terminated by the system due to inactivity.'),
                ]
            );
            $this->addReport(Report::TYPE_INFO, "Delivery execution {$deliveryExecution->getIdentifier()} has been terminated.");
        } else {
            $this->addReport(Report::TYPE_INFO, "Delivery execution {$deliveryExecution->getIdentifier()} should be terminated.");
        }
    }

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

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

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


Question: // Logistic returns a random number of logistic distribution

func (lrng LogisticGenerator) Logistic(mu, s float64) float64 {
	if !(s > 0.0) {
		panic(fmt.Sprintf("Invalid parameter s: %.2f", s))
	}
	return lrng.logistic(mu, s)
}

def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_message(self, **kwargs):

        config = ET.Element("config")
        logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
        config = logical_chassis_fwdl_status
        output = ET.SubElement(logical_chassis_fwdl_status, "output")
        cluster_fwdl_entries = ET.SubElement(output, "cluster-fwdl-entries")
        fwdl_entries = ET.SubElement(cluster_fwdl_entries, "fwdl-entries")
        message = ET.SubElement(fwdl_entries, "message")
        message.text = kwargs.pop('message')

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

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


Question:
// QueryTopic allows to set a custom nats topic on which service registries
// query (survey) other services. All registries listen on this topic and
// then respond to the query message.

func QueryTopic(s string) registry.Option {
	return func(o *registry.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, queryTopicKey{}, s)
	}
}

func (a *Agent) UserEvent(dc, token string, params *UserEvent) error {
	// Validate the params
	if err := validateUserEventParams(params); err != nil {
		return err
	}

	// Format message
	var err error
	if params.ID, err = uuid.GenerateUUID(); err != nil {
		return fmt.Errorf("UUID generation failed: %v", err)
	}
	params.Version = userEventMaxVersion
	payload, err := encodeMsgPack(&params)
	if err != nil {
		return fmt.Errorf("UserEvent encoding failed: %v", err)
	}

	// Service the event fire over RPC. This ensures that we authorize
	// the request against the token first.
	args := structs.EventFireRequest{
		Datacenter:   dc,
		Name:         params.Name,
		Payload:      payload,
		QueryOptions: structs.QueryOptions{Token: token},
	}

	// Any server can process in the remote DC, since the
	// gossip will take over anyways
	args.AllowStale = true
	var out structs.EventFireResponse
	return a.RPC("Internal.EventFire", &args, &out)
}

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


Question:
Converts a {@link Participant} from {{@link #getParticipants()} to a
{@link ParticipantIdentity}.

@param participant {@link Participant} from {@link #getParticipants()}
@return {@link ParticipantIdentity} that corresponds to this {@link Participant}

public ParticipantIdentity getParticipantIdentity(Participant participant) {
		if (participantIdentities != null) {
			for (ParticipantIdentity participantIdentity : participantIdentities) {
				if (participant.getParticipantId() == participantIdentity.getParticipantId()) {
					return participantIdentity;
				}
			}
		}

		return null;
	}

def list_migration_issues_courses(self, course_id, content_migration_id):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - content_migration_id
        """ID"""
        path["content_migration_id"] = content_migration_id

        self.logger.debug("GET /api/v1/courses/{course_id}/content_migrations/{content_migration_id}/migration_issues with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/content_migrations/{content_migration_id}/migration_issues".format(**path), data=data, params=params, all_pages=True)

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


Question:
/*
(non-Javadoc)

@see
com.netflix.evcache.operation.EVCacheLatchI#addFuture(net.spy.memcached.internal.ListenableFuture)

public void addFuture(ListenableFuture<Boolean, OperationCompletionListener> future) {
        future.addListener(this);
        if (future.isDone()) countDown();
        this.futures.add(future);
    }

def authorize_cache_security_group_ingress(name, ec2_security_group_name,
                                           ec2_security_group_owner_id,
                                           region=None, key=None, keyid=None,
                                           profile=None):
    '''

    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        added = conn.authorize_cache_security_group_ingress(
            name, ec2_security_group_name, ec2_security_group_owner_id)
        if added:
            msg = 'Added {0} to cache security group {1}.'
            msg = msg.format(name, ec2_security_group_name)
            log.info(msg)
            return True
        else:
            msg = 'Failed to add {0} to cache security group {1}.'
            msg = msg.format(name, ec2_security_group_name)
            log.error(msg)
            return False
    except boto.exception.EC2ResponseError as e:
        log.debug(e)
        msg = 'Failed to add {0} to cache security group {1}.'
        msg = msg.format(name, ec2_security_group_name)
        log.error(msg)
        return False

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


Question:
Handles data write RESTful calls

@param String $path Path
@param Mixed  $data Data
@param String $method Method

@return String Response

protected function _writeData($path, $data, $method = 'PUT')
    {
        $jsonData = json_encode($data);
        $header = array(
            'Content-Type: ' . $this->_contentType,
            'Content-Length: ' . strlen($jsonData)
        );
        $this->_addHeaderAuthentication($header);

        try {
            $ch = $this->_getCurlHandler($path, $method);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            $return = $this->_parseCurlResponse(curl_exec($ch));
            curl_close($ch);
        } catch (\Exception $e) {
            $return = null;
        }
        return $return;
    }

private void addPostParams(final Request request) {
        if (friendlyName != null) {
            request.addPostParam("FriendlyName", friendlyName);
        }

        if (domainName != null) {
            request.addPostParam("DomainName", domainName);
        }

        if (disasterRecoveryUrl != null) {
            request.addPostParam("DisasterRecoveryUrl", disasterRecoveryUrl.toString());
        }

        if (disasterRecoveryMethod != null) {
            request.addPostParam("DisasterRecoveryMethod", disasterRecoveryMethod.toString());
        }

        if (recording != null) {
            request.addPostParam("Recording", recording.toString());
        }

        if (secure != null) {
            request.addPostParam("Secure", secure.toString());
        }

        if (cnamLookupEnabled != null) {
            request.addPostParam("CnamLookupEnabled", cnamLookupEnabled.toString());
        }
    }

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


Question:
Escapes a string when it contains special characters (RFC3501)

@param string  $string       IMAP string
@param boolean $force_quotes Forces string quoting (for atoms)

@return string String atom, quoted-string or string literal
@todo lists

public static function escape($string, $force_quotes=false)
    {
        if ($string === null) {
            return 'NIL';
        }

        if ($string === '') {
            return '""';
        }

        // atom-string (only safe characters)
        if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x25\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
            return $string;
        }

        // quoted-string
        if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
            return '"' . addcslashes($string, '\\"') . '"';
        }

        // literal-string
        return sprintf("{%d}\r\n%s", strlen($string), $string);
    }

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

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

      Aptly::runcmd cmd
    end

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


Question:
Create an `assemble` app. This is the main function exported
by the assemble module.

```js
var assemble = require('assemble');
var app = assemble();
```
@param {Object} `options` Optionally pass default options to use.
@api public

function Assemble(options) {
  if (!(this instanceof Assemble)) {
    return new Assemble(options);
  }
  Core.call(this, options);
  this.is('assemble');
  this.initAssemble();
}

function callee(method, href, params, opt, cb, userData){
		cb = cb || ((err)=>{
			if (err) console.error(method, href, params, opt, userData, err)
		})
		if (!href) return cb('url not defined')
		opt=opt||{}

		const urlobj = url.parse(href)
		let protocol

		switch(urlobj.protocol){
		case 'http:': protocol=http; break
		case 'https:': protocol=https; break
		default:
			if (opt.socketPath){
				protocol=http
				urlobj.protocol = 'http:'
				urlobj.socketPath = opt.socketPath
				break
			}
			fs.readFile(href, 'utf8', (err, data)=>{
				cb(err, 4, data, userData)
			}); return
		}

		const isGet = 'GET' === (urlobj.method = method.toUpperCase())
		let body = Array.isArray(params) ? pObj.extends({}, params, {tidy:1, mergeArr:1}) : params || ''

		if (isGet){
			urlobj.path += body ? '?' + qs.stringify(body) : body
			urlobj.headers = opt.headers||{}
		}else{
			urlobj.headers = Object.assign({
				'Content-Type': 'application/x-www-form-urlencoded'
			},opt.headers||{})
			switch(urlobj.headers['Content-Type']){
			case 'application/json': body = JSON.stringify(body); break
			case 'plain/text': body = body.toString(); break
			default: body = qs.stringify(body); break
			}
		}

		const req = protocol.request(urlobj, res => {
			const st=res.statusCode
			const loc=res.headers.location
			if (st>=300 && st<400 && loc) return callee(method,loc,params,opt,cb,userData)
			res.setEncoding('utf8')
			const err=(300>st || !st) ? null : {error:res.statusMessage,code:st,params:arguments}
			cb(err, 2, null, userData)
			let data = ''
			res.on('data', (chunk)=>{
				data += chunk
				cb(err, 3, data, userData)
			})
			res.on('end', ()=>{
				cb(err, 4, data, userData)
			})
		})

		req.setTimeout(opt.timeout||0, err => {
			cb({error:err.message,code:599,src:err,params:arguments}, 4, null, userData)
		})
		req.on('error', err => {
			cb({error:err.message,code:500,src:err,params:arguments}, 4, null, userData)
		})

		if (isGet) req.end()
		else req.end(body)
		return req
	}

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


Question:
Returns the Terminal's width.

@return int

public static function getWidth()
    {
        $width = getenv('COLUMNS');
        if ($width !== false) {
            return (int) trim($width);
        }

        static::updateDimensions();

        return static::$width;
    }

def quit_alternate_screen(self):

        if self._in_alternate_screen:
            stdout = self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE)
            self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
            self._winapi(windll.kernel32.CloseHandle, self.hconsole)
            self.hconsole = stdout
            self._in_alternate_screen = False

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


Question:
this is where all the magic happens, this will try and find the param and
        put its value in kwargs if it has a default and stuff

def normalize_param(self, slf, args, kwargs):
        """"""
        if self.is_kwarg:
            kwargs = self.normalize_kwarg(slf.request, kwargs)
        else:
            args = self.normalize_arg(slf.request, args)
        return slf, args, kwargs

def kitchen_config(backend, kitchen, add, get, unset, listall):

    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
    if use_kitchen is None:
        raise click.ClickException(err_str)
    check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall))

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


Question:
@param array $field   mappable field with type attribute
@param mixed $context context for mapper to check

@return array

public function map($field, $context = null)
    {
        $field['serializerType'] = $field['type'];
        if (substr($field['type'], -2) == '[]') {
            $field['serializerType'] = sprintf('array<%s>', substr($field['type'], 0, -2));
        }

        // @todo this assumtion is a hack and needs fixing
        if ($field['type'] === 'array') {
            $field['serializerType'] = 'array<string>';
        }

        if ($field['type'] === 'object') {
            $field['serializerType'] = 'array';
        }

        return $field;
    }

@Override
    @Path("/{dataType}")
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
        String dataType = getSegment(path, 1);
        if (dataType == null)
            throw new ServiceException("Missing path segment: {dataType}");
        try {
            BaselineData baselineData = DataAccess.getBaselineData();
            if (dataType.equals("VariableTypes")) {
                List<VariableType> variableTypes = baselineData.getVariableTypes();
                JSONArray jsonArray = new JSONArray();
                for (VariableType variableType : variableTypes)
                    jsonArray.put(variableType.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else if (dataType.equals("TaskCategories")) {
                List<TaskCategory> taskCats = new ArrayList<TaskCategory>();
                taskCats.addAll(baselineData.getTaskCategories().values());
                Collections.sort(taskCats);
                JSONArray jsonArray = new JSONArray();
                for (TaskCategory taskCat : taskCats)
                    jsonArray.put(taskCat.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else {
                throw new ServiceException("Unsupported dataType: " + dataType);
            }
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }

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


Question: // SetFailureReason sets the FailureReason field's value.

func (s *HyperParameterTrainingJobSummary) SetFailureReason(v string) *HyperParameterTrainingJobSummary {
	s.FailureReason = &v
	return s
}

def add_cause(self, error: Exception):
        ''''''
        self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error))

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


Question: Evaluates configuration block within a context of the given module.

def configuration_block_core(conf_module, &block)
      return conf_module unless block_given?
      return conf_module.tap(&block) unless block.arity == 0
      conf_module.module_eval(&block)
      conf_module
    end

def system_monitor_mail_fru_email_list_email(self, **kwargs):

        config = ET.Element("config")
        system_monitor_mail = ET.SubElement(config, "system-monitor-mail", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
        fru = ET.SubElement(system_monitor_mail, "fru")
        email_list = ET.SubElement(fru, "email-list")
        email = ET.SubElement(email_list, "email")
        email.text = kwargs.pop('email')

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

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


Question:
// Get registers and returns a session for the given name and session store.
//
// It returns a new session if there are no sessions registered for the name.

func (s *Registry) Get(store Store, name string) (session *Session, err error) {
	if !isCookieNameValid(name) {
		return nil, fmt.Errorf("sessions: invalid character in cookie name: %s", name)
	}
	if info, ok := s.sessions[name]; ok {
		session, err = info.s, info.e
	} else {
		session, err = store.New(s.request, name)
		session.name = name
		s.sessions[name] = sessionInfo{s: session, e: err}
	}
	session.store = store
	return
}

public function loadUserModes(EventInterface $event, EventQueueInterface $queue)
    {
        $logger = $this->getLogger();

        $connectionMask = $this->getConnectionMask($event->getConnection());
        $params = $event->getParams();
        $channel = $params[1];
        $validPrefixes = implode('', array_keys($this->prefixes));
        $pattern = '/^([' . preg_quote($validPrefixes) . ']+)(.+)$/';
        $logger->debug('Gathering initial user mode data', array(
            'connectionMask' => $connectionMask,
            'channel' => $channel,
        ));

        foreach ($params['iterable'] as $fullNick) {
            if (!preg_match($pattern, $fullNick, $match)) {
                continue;
            }
            $nickPrefixes = str_split($match[1]);
            $nick = $match[2];
            foreach ($nickPrefixes as $prefix) {
                $mode = $this->prefixes[$prefix];
                $logger->debug('Recording user mode', array(
                    'connectionMask' => $connectionMask,
                    'channel' => $channel,
                    'nick' => $nick,
                    'mode' => $mode,
                ));
                $this->modes[$connectionMask][$channel][$nick][$mode] = true;
            }
        }
    }

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


Question:
Close terminal and exit process

@method end
@param {Object} err Error
@param {Boolean} exit Exit process?

function(err, exit) {
    // Close the terminal
    if(terminal) terminal.close()

    // If there was an error throw it before exit
    if(err) throw err

    // process.stdin.resume() prevents node from exiting.
    // process.exit() overrides in more cases than stdin.pause() or stdin.end()
    // it also means we don't need to call process.stdin.setRawMode(false)
    if(exit === undefined || exit) {
      process.exit()
    }
    else {
      process.stdin.setRawMode(false)
      process.stdin.end()
    }
  }

def conditions(self, start, last_attempt):

        if time.time() - start > self.timeout:
            yield WaitCondition.Timedout
            return

        if last_attempt is not None and time.time() - last_attempt < self.wait_between_attempts:
            yield WaitCondition.KeepWaiting
            return

        if self.greps is not NotSpecified:
            for name, val in self.greps.items():
                yield 'grep "{0}" "{1}"'.format(val, name)

        if self.file_value is not NotSpecified:
            for name, val in self.file_value.items():
                command = 'diff <(echo {0}) <(cat {1})'.format(val, name)
                if not self.harpoon.debug:
                    command = "{0} > /dev/null".format(command)
                yield command

        if self.port_open is not NotSpecified:
            for port in self.port_open:
                yield 'nc -z 127.0.0.1 {0}'.format(port)

        if self.curl_result is not NotSpecified:
            for url, content in self.curl_result.items():
                yield 'diff <(curl "{0}") <(echo {1})'.format(url, content)

        if self.file_exists is not NotSpecified:
            for path in self.file_exists:
                yield 'cat {0} > /dev/null'.format(path)

        if self.command not in (None, "", NotSpecified):
            for command in self.command:
                yield command

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


Question: // makeOptions makes an options slice.

func (e *endpoint) makeOptions(sackBlocks []header.SACKBlock) []byte {
	options := getOptions()
	offset := 0

	// N.B. the ordering here matches the ordering used by Linux internally
	// and described in the raw makeOptions function. We don't include
	// unnecessary cases here (post connection.)
	if e.sendTSOk {
		// Embed the timestamp if timestamp has been enabled.
		//
		// We only use the lower 32 bits of the unix time in
		// milliseconds. This is similar to what Linux does where it
		// uses the lower 32 bits of the jiffies value in the tsVal
		// field of the timestamp option.
		//
		// Further, RFC7323 section-5.4 recommends millisecond
		// resolution as the lowest recommended resolution for the
		// timestamp clock.
		//
		// Ref: https://tools.ietf.org/html/rfc7323#section-5.4.
		offset += header.EncodeNOP(options[offset:])
		offset += header.EncodeNOP(options[offset:])
		offset += header.EncodeTSOption(e.timestamp(), uint32(e.recentTS), options[offset:])
	}
	if e.sackPermitted && len(sackBlocks) > 0 {
		offset += header.EncodeNOP(options[offset:])
		offset += header.EncodeNOP(options[offset:])
		offset += header.EncodeSACKBlocks(sackBlocks, options[offset:])
	}

	// We expect the above to produce an aligned offset.
	if delta := header.AddTCPOptionPadding(options, offset); delta != 0 {
		panic("unexpected option encoding")
	}

	return options[:offset]
}

def _get_opts_seaborn(self, opts, style):

        if opts is None:
            if self.chart_opts is None:
                opts = {}
            else:
                opts = self.chart_opts
        if style is None:
            if self.chart_style is None:
                style = self.chart_style
            else:
                style = {}
        return opts, style

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


Question:
Проверка и фильтр логического значения
@param mixed $value Значение для проверки и фильтра
@param null|Error &$error Возвращаемый объект исключения, если значение не соответсвует типу
@param array $args Аргументы фильтра
@return bool

static function bool($value, &$error, $args)
    {
        if ($value===true || $value===false){
            return $value;
        }
        if (is_string($value)){
            return !in_array(mb_strtolower($value), ['false', '', '0']);
        }
        if (is_scalar($value)){
            return (bool)$value;
        }
        $error = new Error('Должно быть логическим (true/false, 1/0)', 'bool');
        return (bool)$value;
    }

function f_rol_sil_tahta(_tahta_id, _rol_id, _arrKul_id) {

        // 1. Tahtanın üye id lerini Array mi diye kontrol et
        // 2. üye id lerinden rolü çıkar
        // 3. tahta id den bu rolü sil
        if (_rol_id) {
            var arrPromises = Array.isArray(_arrKul_id) //1
                ? _arrKul_id.mapX(null, f_rol_sil_kullanici, _tahta_id, _rol_id) // 2
                : [];
            //3

            return arrPromises.concat(_arrKul_id).allX()
                .then(function () {
                    return [
                        result.dbQ.srem(result.kp.tahta.ssetOzelTahtaRolleri(_tahta_id, true), _rol_id),
                        result.dbQ.sadd(result.kp.tahta.ssetOzelTahtaRolleri(_tahta_id, false), _rol_id)
                    ].allX();
                });
        } else {
            console.error("Silinecek aktif bir rol bulunamadı");
            throw "Silinecek aktif bir rol bulunamadı";
        }
    }

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


Question: // Convert a < xlength, xoffset > pair into a match token.

func matchToken(xlength uint32, xoffset uint32) token {
	return token(matchType + xlength<<lengthShift + xoffset)
}

func (c *Client) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {
	if namespace == "" {
		return nil, trace.BadParameter(MissingNamespaceError)
	}
	response, err := c.Get(c.Endpoint("namespaces", namespace, "sessions", string(sid), "stream"), url.Values{
		"offset": []string{strconv.Itoa(offsetBytes)},
		"bytes":  []string{strconv.Itoa(maxBytes)},
	})
	if err != nil {
		log.Error(err)
		return nil, trace.Wrap(err)
	}
	return response.Bytes(), nil
}

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


Question: Write a new Abook file with the given vcards

def abook_file(vcard, bookfile):
        """"""
        book = ConfigParser(default_section='format')

        book['format'] = {}
        book['format']['program'] = 'abook'
        book['format']['version'] = '0.6.1'

        for (i, card) in enumerate(readComponents(vcard.read())):
            Abook.to_abook(card, str(i), book, bookfile)
        with open(bookfile, 'w') as fp:
            book.write(fp, False)

def get_book_metadata(self, asin):

    kbm = self._get_api_call('get_book_metadata', '"%s"' % asin)
    return KindleCloudReaderAPI._kbm_to_book(kbm)

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


Question:
Setting the base uri for the pointer resolution
The base uri is used for xml:base calculations

@param baseURI of the parent xml
@return the XPointerEngine for fluent api usage

public XPointerEngine setBaseURI(final String baseURI)
    {
        if (baseURI == null)
        {
            this.baseURIValue = XdmEmptySequence.getInstance();
        }
        else
        {
            this.baseURIValue = new XdmAtomicValue(baseURI);
        }
        return this;
    }

func All(basedir string, values []byte, namespace string, strict bool) support.Linter {
	// Using abs path to get directory context
	chartDir, _ := filepath.Abs(basedir)

	linter := support.Linter{ChartDir: chartDir}
	rules.Chartfile(&linter)
	rules.Values(&linter)
	rules.Templates(&linter, values, namespace, strict)
	return linter
}

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


Question:
Creates the resource tree for the given root.<p>

@param cms the CMS context
@param root the root resource
@return the resource tree

protected CmsResourceTreeTable createTree(CmsObject cms, CmsResource root) {

        return new CmsResourceTreeTable(cms, root, m_filter);
    }

public function redirectLocation(Request $request)
    {
        if ($request->query->has('id')) {
            $location = $this->locationService->loadLocation($request->query->get('id'));
        } elseif ($request->query->has('remoteId')) {
            $location = $this->locationService->loadLocationByRemoteId($request->query->get('remoteId'));
        } elseif ($request->query->has('urlAlias')) {
            $urlAlias = $this->urlAliasService->lookup($request->query->get('urlAlias'));
            $location = $this->locationService->loadLocation($urlAlias->destination);
        } else {
            throw new BadRequestException("At least one of 'id', 'remoteId' or 'urlAlias' parameters is required.");
        }

        return new Values\TemporaryRedirect(
            $this->router->generate(
                'ezpublish_rest_loadLocation',
                array(
                    'locationPath' => trim($location->pathString, '/'),
                )
            )
        );
    }

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


Question: // AddPayload appends message payload to for given chain

func (g *gossipServiceImpl) AddPayload(chainID string, payload *gproto.Payload) error {
	g.lock.RLock()
	defer g.lock.RUnlock()
	return g.chains[chainID].AddPayload(payload)
}

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

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


Question:
DOM Traversal
@module traverse-dom

Traverses a document in depth-first (AKA "document") order
@param  {any} $node  VNode, Observable or any node constructed within the DOM context
@return {Observable} An Observable stream emitting VNodes

function traverseDOM($node, d = document) {
  $node = _doc.ensureDoc.bind(cx)($node);
  return _rxjs.Observable.create($o => {
    $node.subscribe({
      next(vnode) {
        const t = d.createTreeWalker(vnode.node);
        const closers = new WeakMap();

        const isBranch = n => n.nodeType == 1 || n.nodeType == 9 || n.nodeType == 10 || n.nodeType == 11;

        const emitNode = n => {
          $o.next(new _vnode.VNode(cx, n, n.nodeType, n.nodeName, n.nodeType == 2 ? n.nodeName : null, n.textContent, n.parentNode));
        };

        const close = n => {
          $o.next(new _vnode.Close(n));

          if (closers.has(n)) {
            const parent = closers.get(n);
            closers.delete(n);
            close(parent);
          }
        };

        emitNode(t.currentNode);

        while (t.nextNode()) {
          const n = t.currentNode;
          emitNode(n); // if the node is a leaf or an empty branch, close its parent
          // else the node itself should close first
          // so don't close the parent yet, but move it to the closers map
          // and close it after this node closes

          let parent = n.parentNode;

          if (parent && parent.lastChild == n) {
            if (isBranch(n)) {
              if (!n.childNodes.length) {
                close(n);
                close(parent);
              } else {
                closers.set(n, parent);
              }
            } else {
              close(parent);
            }
          }
        }
      },

      complete() {
        $o.complete();
      },

      error(err) {
        $o.error(err);
      }

    });
  });
}

function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}

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


Question: Provision slave container and wait for it's availability.

private DockerSlave provisionWithWait(DockerSlaveTemplate template, ProvisioningActivity.Id id)
            throws Exception {
        final DockerContainerLifecycle dockerContainerLifecycle = template.getDockerContainerLifecycle();
        final String imageId = dockerContainerLifecycle.getImage();
        final DockerComputerLauncher computerLauncher = template.getLauncher();

        //pull image
        dockerContainerLifecycle.getPullImage().exec(getClient(), imageId, new StreamTaskListener(new NullStream()));

        // set the operating system if it's not already cached
        if (template.getOsType() == null) {
            template.setOsType(determineOsType(imageId));
        }

        LOG.debug("Trying to run container for {}, operating system {}", imageId, template.getOsType());
        final String containerId = runContainer(template);

        InspectContainerResponse ir;
        try {
            ir = getClient().inspectContainerCmd(containerId).exec();
        } catch (ProcessingException ex) {
            LOG.error("Failed to run container for {}, clean-up container", imageId);
            dockerContainerLifecycle.getRemoveContainer().exec(getClient(), containerId);
            throw ex;
        }

        // Build a description up:
        String nodeDescription = "Docker Node [" + imageId + " on ";
        try {
            nodeDescription += getDisplayName();
        } catch (Exception ex) {
            nodeDescription += "???";
        }
        nodeDescription += "]";

        String slaveName = String.format("%s-%s", getDisplayName(), containerId.substring(0, 12));

        if (computerLauncher.waitUp(getDisplayName(), template, ir)) {
            LOG.debug("Container {} is ready for slave connection", containerId);
        } else {
            LOG.error("Container {} is not ready for slave connection.", containerId);
        }

        final DockerComputerLauncher launcher = computerLauncher.getPreparedLauncher(getDisplayName(), template, ir);
        return new DockerSlave(slaveName, nodeDescription, launcher, containerId, template, getDisplayName(), id);
    }

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

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


Question:
Method to create ipv6's

        :param ipv6s: List containing vrf desired to be created on database
        :return: None

def create(self, ipv6s):

        data = {'ips': ipv6s}
        return super(ApiV4IPv6, self).post('api/v4/ipv6/', data)

def _netstat_route_sunos():
    '''

    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    cmd = 'netstat -f inet6 -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    return ret

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


Question:
Creates a function `function name(paramList) { body }`

@param name STRING node - empty string if no name
@param paramList PARAM_LIST node
@param body BLOCK node
@param type type to apply to the function itself

Node createFunction(String name, Node paramList, Node body, JSType type) {
    Node nameNode = createName(name, type);
    Node result = IR.function(nameNode, paramList, body);
    if (isAddingTypes()) {
      checkArgument(type.isFunctionType(), type);
      result.setJSType(type);
    }
    return result;
  }

def _partial_build(self, endpoint, values, method, append_unknown):

        # in case the method is none, try with the default method first
        if method is None:
            rv = self._partial_build(
                endpoint, values, self.default_method, append_unknown
            )
            if rv is not None:
                return rv

        # default method did not match or a specific method is passed,
        # check all and go with first result.
        for rule in self.map._rules_by_endpoint.get(endpoint, ()):
            if rule.suitable_for(values, method):
                rv = rule.build(values, append_unknown)
                if rv is not None:
                    return rv

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


Question:
Returns multidimensional variant structure

@param object $oVariants all article variants
@param string $sParentId parent article id

@return oxMdVariant

public function buildMdVariants($oVariants, $sParentId)
    {
        $oMdVariants = oxNew(\OxidEsales\Eshop\Application\Model\MdVariant::class);
        $oMdVariants->setParentId($sParentId);
        $oMdVariants->setName("_parent_product_");
        foreach ($oVariants as $sKey => $oVariant) {
            $aNames = explode(trim($this->_sMdSeparator), $oVariant->oxarticles__oxvarselect->value);
            foreach ($aNames as $sNameKey => $sName) {
                $aNames[$sNameKey] = trim($sName);
            }
            $oMdVariants->addNames(
                $sKey,
                $aNames,
                (\OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('bl_perfLoadPrice')) ? $oVariant->getPrice()->getPrice() : null,
                $oVariant->getLink()
            );
        }

        return $oMdVariants;
    }

private function parseOptions(array $options): array
    {
        $child = $options['child'] ?? [];

        if (isset($options['header'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['header' => $options['header']]);
        }

        if (isset($options['divider'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['divider' => true]);
        }

        if (isset($options['icon'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['icon' => $options['icon']]);
        }

        if (isset($options['route']) && is_array($options['route'])) {
            $options['routeParameters'] = $options['route']['[parameters'] ?? [];
            $options['route'] = $options['route']['name'];
        }

        foreach ($this->parsers as $parser) {
            if ($result = $parser($options)) {
                $options = $result;
            }
        }

        unset($options['child']);

        return [
            'options' => $options,
            'child' => $child,
        ];
    }

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


Question:
// Implement InstanceGroupInfo.CurrentSize
// The number of instances currently running under control of this group

func (g *awsInstanceGroup) CurrentSize() (int, error) {
	return len(g.group.Instances), nil
}

func ScaleCommand(factory app.ProjectFactory) cli.Command {
	return cli.Command{
		Name:   "scale",
		Usage:  "Scale services",
		Action: app.WithProject(factory, app.ProjectScale),
		Flags: []cli.Flag{
			cli.IntFlag{
				Name:  "timeout,t",
				Usage: "Specify a shutdown timeout in seconds.",
			},
		},
	}
}

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


Question: Reimplement Qt method

def sort(self, column, order=Qt.AscendingOrder):
        """"""
        self.sourceModel().sort(column, order)

def queryBuilderWidget( self ):

        from projexui.widgets.xquerybuilderwidget import XQueryBuilderWidget

        builder = self.parent()
        while ( builder and not isinstance(builder, XQueryBuilderWidget) ):
            builder = builder.parent()

        return builder

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


Question:
Add rubric breadcrumbs element (in most cases - second emelent of breadcrumbs).

@param $id rubric ID
@return bool

public function breadcrumbs_add_rubric($id) {
		bimport('rubrics.general');
		$brubrics = BRubrics::getInstance();
		$rub = $brubrics->getrubric_by_id($id);
		if (empty($rub)) {
			return false;
		}
		$brouter = BRouter::getInstance();
		$url = '//' . $brouter->generateURL('rubric', BLang::$langcode, array('view' => 'rubric', 'id' => $id));
		$name = $rub->getname();
		return $this->breadcrumbs_add($url, $name, true, 'rubric');
	}

public function handle()
    {
        $ds = DIRECTORY_SEPARATOR;
        $resources = $this->argument('resources');
        $resources = !is_array($resources) ? [$resources] : $resources;
        $module = $this->option('module');
        $routesFile = base_path('routes') . $ds . 'web.php';

        if ($module) {
            $module = is_array($module) ? $module[0] : $module;
            $moduleDirectory = config('support.module.directory') . $ds . ucfirst($module);

            $this->namespace = $this->getAppNamespace() . ucfirst($module);
            $routesFile = config('support.module.directory') . $ds . ucfirst($module) . $ds . config('support.module.routes');

            if (!file_exists($moduleDirectory)) {
                $this->error("The requested module '$moduleDirectory' does not exists!");
                return;
            }

            if(config('support.namespace')) {
                $this->namespace = config('support.namespace');
            }
        }

        foreach ($resources as $resource) {
            $stub = file_get_contents(__DIR__ . $ds . '..' . $ds . '..' . $ds . '..' . $ds . '..' . $ds . 'resources' . $ds . 'Stubs' . $ds . (empty($module) ? 'Standard' : 'Modular') . $ds . 'Route.stub');
            $stub = str_replace([
                        '{{resource}}',                    '{{class}}'],
                        [str_plural(strtolower($resource)),  str_plural(ucfirst($resource))],
                        $stub);

            if (!file_exists($routesFile)) {
                $this->error('Could not update routes file \'' . $routesFile . '\' as it does not exist!');
                return;
            }

            $routes = file_get_contents($routesFile);
            $stub = $routes ? $routes . "\n" . $stub : $stub;

            file_put_contents($routesFile, $stub);
            $this->info($routesFile . ' routes updated!');
        }
    }

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


Question:
Get the contents of a channel

Only availabe if no

@param int $channel  1: STDOUT / 2: STDERR

public function getChanContents(int $channel=1) : string
    {
        if ( ! isset ($this->pipes[$channel]))
            throw new \InvalidArgumentException("No channel '$channel' defined.");
        return $this->pipes[$channel];
    }

function bin(argv) {
  // setup config

  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

  var url     = process.argv[2] || 'https://localhost:4000/buffer?type=getLastFragment'
  var cert    = process.argv[3] || process.env['CERT']
  var display = process.argv[4] || process.env['DISP'] || 'display'
  var buffer  = process.argv[5] || 'https://localhost:4000/static/buffer.mp4'

  var options = {
    url: url,
    key: fs.readFileSync(cert),
    cert: fs.readFileSync(cert),
  }

  var config = require('../config/config.js')
  console.log(config);

  request.get(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body) // Show the HTML for the Google homepage.

      var cmd = display + ' ' + buffer
      console.log(cmd)
      child_process.exec(cmd)

    } else {
      console.error(error);
    }

  })
}

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


Question: Copy this object with some parameters changed if needed.

def copy(self, sleep=_unset, stop=_unset, wait=_unset,
             retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
             reraise=_unset):
        """"""
        if before_sleep is _unset:
            before_sleep = self.before_sleep
        return self.__class__(
            sleep=self.sleep if sleep is _unset else sleep,
            stop=self.stop if stop is _unset else stop,
            wait=self.wait if wait is _unset else wait,
            retry=self.retry if retry is _unset else retry,
            before=self.before if before is _unset else before,
            after=self.after if after is _unset else after,
            before_sleep=before_sleep,
            reraise=self.reraise if after is _unset else reraise,
        )

func (s *SnapshotCopyGrant) SetSnapshotCopyGrantName(v string) *SnapshotCopyGrant {
	s.SnapshotCopyGrantName = &v
	return s
}

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


Question:
Construct a conjunction of two expressions

@param lhs
@param rhs
@return

private WyalFile.Stmt and(WyalFile.Stmt lhs, WyalFile.Stmt rhs) {
		if (lhs == null) {
			return rhs;
		} else if (rhs == null) {
			return rhs;
		} else {
			return new WyalFile.Stmt.Block(lhs, rhs);
		}
	}

public function login(Net_SSH2 &$ssh)
    {
        $this->validateAuthParams(
            $this->authParams,
            $acceptableParams = [
                'username' => 'is_string',
                'password' => 'is_string'
            ]
        );

        extract($this->authParams);

        if (!$ssh->login($username, $password)) {
            throw new \Exception(get_class().': Authentication failed');
        }
    }

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


Question:
Deletes a tag value.

@param tagName The name of the tag.
@param tagValue The value of the tag to delete.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

def delete_target(target_id)
      # In order to delete the target, we have to set it to non-active.
      # Therefore,first retrieve target info and act accordingly to target info
      # returned
      target_data = JSON.parse(retrieve_target(target_id)) # have to JSON.parse
      # retrieve_target's results since they're in string format
      target_result_code = target_data["result_code"]
      if target_result_code != "AuthenticationFailure"
        if target_result_code != "UnknownTarget"
          target_active_flag = target_data["target_record"]["active_flag"]
          target_status = target_data["status"]
          if target_result_code == "Success"
            if target_active_flag == true && target_status == "success"
              return {:result_code => "TargetActive"}.to_json
            elsif target_active_flag == false && target_status == "success"
              # if we reached this point, the target is fine, inactive and
              # ready to be deleted
              date_timestamp = Time.now.httpdate
              target_id_url = TARGETS_URL + '/' + target_id
              target_id_suburl = '/targets' + '/' + target_id
              signature = self.build_signature(target_id_suburl, nil, 'DELETE', date_timestamp)
              raise ArgumentError.new('Signature returned nil. Aborting...') if signature == nil
              authorization_header = "VWS " + @accesskey + ":" + signature
                begin
                  RestClient.delete(target_id_url,
                                             :'Date' => date_timestamp,
                                             :'Authorization' => authorization_header)
                rescue => e
                  e.response
                end
            else
              return {:result_code => "#{target_status}"}.to_json
            end
          end
        else
          return {:result_code => "UnknownTarget"}.to_json
        end
      else
        return {:result_code => "AuthenticationFailure"}.to_json
      end
    end

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


Question:
Renderers a key value pair of information for display.

@param string $key
@param string $value
@param string $class
@return string

protected function detail_pair($key, $value, $class ='') {
        $html = html_writer::start_div('detail-pair row yui3-g '.preg_replace('#[^a-zA-Z0-9_\-]#', '-', $class));
        $html .= html_writer::div(html_writer::span($key), 'pair-key col-md-3 yui3-u-1-4 font-weight-bold');
        $html .= html_writer::div(html_writer::span($value), 'pair-value col-md-8 yui3-u-3-4');
        $html .= html_writer::end_div();
        return $html;
    }

protected function getKey($name, $arguments)
    {
        if (empty($arguments)) {
            return null;
        }
        if (is_string($arguments[0])) {
            return $arguments[0];
        } else {
            return null;
        }
    }

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


Question:
Wrap a value in keyword identifiers.

@param  string  $value
@return string

public function wrap($value, $prefixAlias = false)
    {
        // We will only wrap the value unless it has parentheses
        // in it which is the case where we're matching a node by id, or an *
        // and last whether this is a pre-formatted key.
        if (preg_match('/[(|)]/', $value) || $value == '*' || strpos($value, '.') !== false) return $value;

        // In the case where the developer specifies the properties and not returning
        // everything, we need to check whether the primaryKey is meant to be returned
        // since Neo4j's way of evaluating returned properties for the Node id is
        // different: id(n) instead of n.id

        if ($value == 'id')
        {
            return 'id(' . $this->query->modelAsNode() . ')';
        }
        return $this->query->modelAsNode() . '.' . $value;
    }

def hash_to_rets_query_string(hash)
      [].tap do |str|
        hash.each_pair do |k,v|
          val = value_map(v)
          str << "(#{k.to_s.camelize}=#{val})"
        end
      end.join(',')
    end

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


Question: ---------------------------------------------------------------------- 起動時処理実行処理 ----------------------------------------------------------------------

function postload(e){
	if(preinit){
		preinit = false;
		for(var i=0;i<loadfun.length;i++){ loadfun[i]();}
		loadfun = [];
	}
}

def main(args=None):
    """"""

    if args is None:
        parser = get_argument_parser()
        args = parser.parse_args()

    input_file = args.annotation_file
    output_file = args.output_file
    species = args.species
    chrom_pat = args.chromosome_pattern
    field_name = args.field_name

    log_file = args.log_file
    quiet = args.quiet
    verbose = args.verbose

    # configure root logger
    log_stream = sys.stdout
    if output_file == '-':
        # if we print output to stdout, redirect log messages to stderr
        log_stream = sys.stderr

    logger = misc.get_logger(log_stream = log_stream, log_file = log_file,
            quiet = quiet, verbose = verbose)

    if chrom_pat is None:
        chrom_pat = re.compile(ensembl.SPECIES_CHROMPAT[species])
    else:
        chrom_pat = re.compile(chrom_pat)

    logger.info('Regular expression used for filtering chromosome names: "%s"',
            chrom_pat.pattern)

    chromosomes = set()
    excluded_chromosomes = set()
    i = 0
    exons = 0
    logger.info('Parsing data...')
    if input_file == '-':
        input_file = None
    with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh, \
            misc.smart_open_write(output_file) as ofh:
        #if i >= 500000: break
        reader = csv.reader(fh, dialect = 'excel-tab')
        writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep,
                quoting = csv.QUOTE_NONE , quotechar = '|')
        for l in reader:
            i += 1
            #if i % int(1e5) == 0:
            #   print '\r%d...' %(i), ; sys.stdout.flush() # report progress
            if len(l) > 1 and l[2] == field_name:
                attr = parse_attributes(l[8])
                type_ = attr['gene_biotype']
                if type_ in ['protein_coding','polymorphic_pseudogene']:

                    # test whether chromosome is valid
                    chrom = l[0]
                    m = chrom_pat.match(chrom)
                    if m is None:
                        excluded_chromosomes.add(chrom)
                        continue

                    chromosomes.add(chrom)
                    writer.writerow(l)
                    exons += 1

    logger.info('Done! (Parsed %d lines.)', i)

    logger.info('')
    logger.info('Gene chromosomes (%d):', len(chromosomes))
    logger.info('\t' + ', '.join(sorted(chromosomes)))
    logger.info('')
    logger.info('Excluded chromosomes (%d):', len(excluded_chromosomes))
    logger.info('\t' + ', '.join(sorted(excluded_chromosomes)))
    logger.info('')
    logger.info('Total no. of exons: %d' %(exons))

    return 0

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


Question: // AddTxIn adds a transaction input to the message.

func (msg *MsgTx) AddTxIn(ti *TxIn) {
	msg.TxIn = append(msg.TxIn, ti)
}

private static void insertName(String name, int activeLine, WordNet wordNetOptimum, WordNet wordNetAll)
    {
        if (isBadCase(name)) return;
        wordNetOptimum.insert(activeLine, new Vertex(Predefine.TAG_PEOPLE, name, new CoreDictionary.Attribute(Nature.nrj), WORD_ID), wordNetAll);
    }

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


Question: A wrapper of JFS.getObject(), with some tweaks that make sense in a file system.

def _getpath(self, path):
        ""
        if is_blacklisted(path):
            raise JottaFuseError('Blacklisted file, refusing to retrieve it')

        return self.client.getObject(path)

public static List<Win32FindData> listDir(String path) {
    final List<Win32FindData> results = new ArrayList<Win32FindData>();
    listDirectory(path, new INativeWin32APICallback() {
      @Override
      public void handleFile(String name, int attributes, long createTime, long lastAccessTime, long lastModifiedTime, long length) {
        if (!(name.equals(".") || name.equals(".."))) {
          results.add(new Win32FindData(attributes, createTime, lastAccessTime, lastModifiedTime, length, name));
        }
      }
    });
    return results;
  }

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


Question:
Get Label for Artifact Details.

@param caption
as caption of the details
@param name
as name
@return SoftwareModuleName

public static String getSoftwareModuleName(final String caption, final String name) {
        return new StringBuilder()
                .append(DIV_DESCRIPTION_START + caption + " : " + getBoldHTMLText(getFormattedName(name)))
                .append(DIV_DESCRIPTION_END).toString();
    }

public static ElementType[] getTargetType(Class<? extends Annotation> annotationType) {
		final Target target = annotationType.getAnnotation(Target.class);
		if (null == target) {
			return new ElementType[] { ElementType.TYPE, //
					ElementType.FIELD, //
					ElementType.METHOD, //
					ElementType.PARAMETER, //
					ElementType.CONSTRUCTOR, //
					ElementType.LOCAL_VARIABLE, //
					ElementType.ANNOTATION_TYPE, //
					ElementType.PACKAGE//
			};
		}
		return target.value();
	}

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


Question:
Display the staff toolbar
    :param context:
    :type context:
    :return:
    :rtype:

def staff_toolbar(context):

    request = context['request']
    if not request.user.is_staff:
        return u''

    toolbar_html = toolbar_root(request, context)
    return format_html(u'<nav id="django-staff-toolbar">{0}</nav>', toolbar_html)

public function build() {
    $options_data = $this->buildOptionsData();

    $out_text =
      $this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);

    $options_text = '';
    if ($options_data['lines']) {
      foreach($options_data['lines'] as $option_line_data) {
        $options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
      }

      $out_text .=
        "\n".
        ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
        $options_text;
    }

    return $out_text;
  }

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


Question:
Регистрация обработчиков событий

@param string ...  имена событий
@deprecated с 3.01 используйте {@link Eresus_Event_Dispatcher::addEventListener()}

protected function listenEvents()
    {
        $registry = Eresus_Plugin_Registry::getInstance();
        for ($i=0; $i < func_num_args(); $i++)
        {
            $event = func_get_arg($i);
            if (!array_key_exists($event, $registry->events))
            {
                $registry->events[$event] = array();
            }
            $registry->events[$event] []= $this->getName();
        }
    }

private function fallbackFromDatabaseToConnection(array &$config)
    {
        if (isset($config['database'])) {
            // @codingStandardsIgnoreStart
            @\trigger_error(
                'Config key database is deprecated use instead connection. Fallback will be dropped.',
                E_USER_DEPRECATED
            );
            // @codingStandardsIgnoreEnd

            if (!isset($config['connection'])) {
                $config['connection'] = $config['database'];
            }

            unset($config['database']);
        }

        if (isset($config['connection']) && $config['connection'] instanceof Database) {
            // @codingStandardsIgnoreStart
            @\trigger_error(
                '"' . __METHOD__ . '" now accepts doctrine instances - ' .
                'passing Contao database instances is deprecated.',
                E_USER_DEPRECATED
            );
            // @codingStandardsIgnoreEnd
            $reflection = new \ReflectionProperty(Database::class, 'resConnection');
            $reflection->setAccessible(true);

            $config['connection'] = $reflection->getValue($config['connection']);
        }
    }

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


Question:
@param Asker $asker
@param       $modelName
@param       $oldName
@param       $newName
@param Field $fieldObj

@return ConfirmationQuestion

@since  1.1.0

@author Eddilbert Macharia (http://eddmash.com) <edd.cowan@gmail.com>

public static function hasFieldRenamed(Asker $asker, $modelName, $oldName, $newName, Field $fieldObj)
    {
        $msg = 'Did you rename %1$s.%2$s to %1$s.%3$s (a %4$s)? [y/N]';

        $q = new ConfirmationQuestion(sprintf($msg, $modelName, $oldName, $newName, $fieldObj->getShortClassName()));

        return $asker->ask($q);
    }

def signature(self):
        """"""
        if not use_signature:
            raise NotImplementedError("Python 3 only.")

        if self.static:
            parameters = \
                (Parameter(name='cls',
                           kind=Parameter.POSITIONAL_ONLY),)

        else:
            parameters = \
                (Parameter(name='self',
                           kind=Parameter.POSITIONAL_ONLY),)

        if self.input_transform:
            return signature(self.input_transform)

        if self.uses_request:
            fields = get_fields(self.request_type)
            if not self.static:
                if self.field_name not in fields:
                    raise NameError("field '{}' not found in {}".format(
                        self.field_name, self.request_name))
                fields.remove(self.field_name)
            parameters += tuple(
                Parameter(name=name, kind=Parameter.POSITIONAL_OR_KEYWORD,
                          default=None)
                for name in fields)

        return Signature(parameters)

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


Question:
Notify with `notify-send`.

@param string $title
@param string $message
@param string $icon    optional

@return void

protected function notify($title, $message, $icon = null)
    {
        $icon = is_string($icon) ? $icon : $this->icon;

        $this->execute("notify-send -t 2000 -i {$icon} '{$title}' '$message'");
    }

func (s *CreateNotificationSubscriptionInput) SetEndpoint(v string) *CreateNotificationSubscriptionInput {
	s.Endpoint = &v
	return s
}

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


Question: // LessThanOrEqual filter with value.

func (p *UserQueryProperty) LessThanOrEqual(value interface{}) *UserQueryBuilder {
	p.bldr.q = p.bldr.q.Filter(p.name+" <=", value)
	if p.bldr.plugin != nil {
		p.bldr.plugin.Filter(p.name, "<=", value)
	}
	return p.bldr
}

protected function applyFilters(\SelectQuery $select, Query $query)
    {
        if ($query->has('status')) {
            $select->condition('n.status', $query->get('status'));
        }
        if ($query->has('promote')) {
            $select->condition('n.promote', $query->get('promote'));
        }
        if ($query->has('sticky')) {
            $select->condition('n.sticky', $query->get('sticky'));
        }
        if ($query->has('type')) {
            $select->condition('n.type', $query->get('type'));
        }
    }

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


Question:
Returns if a property has been deleted.

@param key
Key for the property to check.

@return If the property is unknown or has been deleted true else false.

public final boolean isRemoved(final String key) {
        final Property prop = find(key);
        if (prop == null) {
            return true;
        }
        return prop.isDeleted();
    }

public static function __supportAutoDestroy($className)
    {
        if (empty(MI::$__reflections[$className])) {
            $reflection  = new \ReflectionClass($className);
            $default     = $reflection->getDefaultProperties();
            $public      = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
            $private     = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
            $protect     = $reflection->getProperties(\ReflectionProperty::IS_PROTECTED);
            $static      = $reflection->getProperties(\ReflectionProperty::IS_STATIC);
            $autoDestroy = [];
            foreach ($public as $val) {
                $autoDestroy[Marco::DS_PUBLIC][$val->getName()] = $default[$val->getName()];
            }

            foreach ($private as $val) {
                $autoDestroy[Marco::DS_PRIVATE][$val->getName()] = $default[$val->getName()];
            }

            foreach ($protect as $val) {
                $autoDestroy[Marco::DS_PROTECTED][$val->getName()] = $default[$val->getName()];
            }

            foreach ($static as $val) {
                if (isset($autoDestroy[Marco::DS_PUBLIC])) {
                    unset($autoDestroy[Marco::DS_PUBLIC][$val->getName()]);
                }

                if (isset($autoDestroy[Marco::DS_PROTECTED])) {
                    unset($autoDestroy[Marco::DS_PROTECTED][$val->getName()]);
                }

                if (isset($autoDestroy[Marco::DS_PRIVATE])) {
                    unset($autoDestroy[Marco::DS_PRIVATE][$val->getName()]);
                }
            }

            unset($autoDestroy[Marco::DS_PUBLIC]['__useCount']);
            unset($autoDestroy[Marco::DS_PUBLIC]['__genTime']);
            unset($autoDestroy[Marco::DS_PUBLIC]['__coreName']);
            unset($autoDestroy[Marco::DS_PUBLIC]['__DSLevel']);
            unset($autoDestroy[Marco::DS_PUBLIC]['__reflections']);
            MI::$__reflections[$className] = $autoDestroy;
            unset($reflection);
            unset($default);
            unset($public);
            unset($private);
            unset($protect);
            unset($static);
        }
    }

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


Question:
Is Error
Checks if value is an error. Allows custom error property
which can be useful in certain scenarios to flag an object
as an error.

@param val the value/object to be inspected.
@param prop a custom property to check if exists indicating is error.

function isError(val, prop) {
    if (!isValue(val) || !isObject(val))
        return false;
    var type = constant_1.toStr.call(val).toLowerCase();
    return type === '[object error]' || type === '[object domexception]' || !isEmpty(val[prop]);
}

func (s *store) UpdateModel(controllerName, modelName string, details ModelDetails) error {
	if err := ValidateControllerName(controllerName); err != nil {
		return errors.Trace(err)
	}
	if err := ValidateModel(modelName, details); err != nil {
		return errors.Trace(err)
	}

	releaser, err := s.acquireLock()
	if err != nil {
		return errors.Annotatef(err,
			"cannot acquire lock file for updating model %s on controller %s", modelName, controllerName,
		)
	}
	defer releaser.Release()

	return errors.Trace(updateModels(
		controllerName,
		func(models *ControllerModels) (bool, error) {
			oldDetails, ok := models.Models[modelName]
			if ok && details == oldDetails {
				return false, nil
			}
			if ok && oldDetails.ModelType == "" && details.ModelType != model.IAAS ||
				oldDetails.ModelType != "" && oldDetails.ModelType != details.ModelType {
				oldModelType := oldDetails.ModelType
				if oldModelType == "" {
					oldModelType = model.IAAS
				}
				return false, errors.Errorf(
					"model type was %q, cannot change to %q", oldModelType, details.ModelType)
			}
			models.Models[modelName] = details
			return true, nil
		},
	))
}

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


Question:
特殊处理，允许通过带参数的constructor创建对象

@param type
@return

public static Object newInstance(Class type) {
        Constructor _constructor = null;
        Object[] _constructorArgs = new Object[0];
        try {
            _constructor = type.getConstructor(new Class[] {});// 先尝试默认的空构造函数
        } catch (NoSuchMethodException e) {
            // ignore
        }

        if (_constructor == null) {// 没有默认的构造函数，尝试别的带参数的函数
            Constructor[] constructors = type.getConstructors();
            if (constructors.length == 0) {
                throw new UnsupportedOperationException("Class[" + type.getName() + "] has no public constructors");
            }
            _constructor = constructors[0];// 默认取第一个参数
            Class[] params = _constructor.getParameterTypes();
            _constructorArgs = new Object[params.length];
            for (int i = 0; i < params.length; i++) {
                _constructorArgs[i] = getDefaultValue(params[i]);
            }
        }

        return ReflectUtils.newInstance(_constructor, _constructorArgs);
    }

protected function handleUnresolvedArgument(\ReflectionParameter $parameter) {
    $class = $parameter->getDeclaringClass();
    $function = $parameter->getDeclaringFunction();
    if ($class && !$function->isClosure()) {
      $function_name = $class->getName() . '::' . $function->getName();
    }
    else {
      $function_name = $function->getName();
    }
    throw new \RuntimeException(sprintf('Callable "%s" requires a value for the "$%s" argument.', $function_name, $parameter->getName()));
  }

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


Question: Render based on interval or automatically

function render (callback) {

    if (effectAttrs.speed !== undefined) {
      setTimeout(function () {
        id = requestAnimationFrame(callback);
      }, effectAttrs.speed);
    } else {
      id = requestAnimationFrame(callback);
    }
  }

private function generateValues($default, $items)
    {
        foreach ($items as $key => $item) {
            /** @type $item CacheItemInterface */
            if (!$item->isHit()) {
                yield $key => $default;
            } else {
                yield $key => $item->get();
            }
        }
    }

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


Question: Marshall the given parameter object.

public void marshall(GetFederationTokenRequest getFederationTokenRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getFederationTokenRequest.getInstanceId(), INSTANCEID_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:
Set errors from response

@param  array  $response
@param  string  $key
@return void

protected function setErrors($response, $key)
    {
        foreach ($response->{$key} as $error) {
            $this->setError($error->code, $error->description);
        }
    }

func (s *Server) handleWriteRequest(r WriteRequest) []byte {
	// Validate the request.
	switch {
	case len(r) < 3:
		return newErrorResponse(r.AttributeOpcode(), 0x0000, ble.ErrInvalidPDU)
	}

	a, ok := s.db.at(r.AttributeHandle())
	if !ok {
		return newErrorResponse(r.AttributeOpcode(), r.AttributeHandle(), ble.ErrInvalidHandle)
	}

	// We don't support write to static value. Pass the request to upper layer.
	if a == nil {
		return newErrorResponse(r.AttributeOpcode(), r.AttributeHandle(), ble.ErrWriteNotPerm)
	}
	if e := handleATT(a, s.conn, r, ble.NewResponseWriter(nil)); e != ble.ErrSuccess {
		return newErrorResponse(r.AttributeOpcode(), r.AttributeHandle(), e)
	}
	return []byte{WriteResponseCode}
}

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


Question: Get metadata of device

def getMetadata(self, remote, address, key):
        """"""
        if self._server is not None:
            # pylint: disable=E1121
            return self._server.getAllMetadata(remote, address, key)

public function withMeta($meta): EncoderInterface
    {
        $this->meta    = $meta;
        $this->hasMeta = true;

        return $this;
    }

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


Question:
Initialize the gaussian components by calculating the means and
variances of k initial cluster centroids generated by the seeder.

@param \Rubix\ML\Datasets\Dataset $dataset
@return array[]

protected function initialize(Dataset $dataset) : array
    {
        $centroids = $this->seeder->seed($dataset, $this->k);

        $kernel = new Euclidean();

        $clusters = array_fill(0, $this->k, []);

        foreach ($dataset as $sample) {
            $bestDistance = INF;
            $bestCluster = -1;

            foreach ($centroids as $cluster => $centroid) {
                $distance = $kernel->compute($sample, $centroid);

                if ($distance < $bestDistance) {
                    $bestDistance = $distance;
                    $bestCluster = $cluster;
                }
            }

            $clusters[$bestCluster][] = $sample;
        }

        $means = $variances = [];

        foreach ($clusters as $cluster => $samples) {
            $mHat = $vHat = [];

            $columns = array_map(null, ...$samples);

            foreach ($columns as $values) {
                [$mean, $variance] = Stats::meanVar($values);

                $mHat[] = $mean;
                $vHat[] = $variance;
            }

            $means[$cluster] = $mHat;
            $variances[$cluster] = $vHat;
        }

        return [$means, $variances];
    }

public static void initClass() {

        // registers a factory for creating new instances of this widget
        CmsWidgetFactoryRegistry.instance().registerFactory(WIDGET_TYPE, new I_CmsFormWidgetFactory() {

            /**
             * @see org.opencms.gwt.client.ui.input.form.I_CmsFormWidgetFactory#createWidget(java.util.Map, com.google.common.base.Optional)
             */
            public I_CmsFormWidget createWidget(Map<String, String> widgetParams, Optional<String> defaultValue) {

                String cfg = widgetParams.get("v");
                if (CmsStringUtil.isEmptyOrWhitespaceOnly(cfg)) {
                    // something went wrong, fall back to text box
                    return new CmsTextBox();
                } else {
                    return new CmsTinyMCEWidget(decode(cfg));
                }
            }

            private String decode(String string) {

                StringBuffer result = new StringBuffer();
                for (String num : string.split(",")) {
                    result.append((char)(Integer.parseInt(num)));
                }
                return result.toString();
            }
        });
    }

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


Question: Check whether ``values`` is a valid argument for ``weighted_choice``.

def _is_valid_options_weights_list(value):
    ''''''
    return ((isinstance(value, list)) and
            len(value) > 1 and
            (all(isinstance(opt, tuple) and
                 len(opt) == 2 and
                 isinstance(opt[1], (int, float))
                 for opt in value)))

def getData(self, pos):

        retval = {}
        if pos >= len(self.inputs):
            raise IndexError('getData() pattern beyond range.', pos)
        if self.verbosity >= 1: print("Getting input", pos, "...")
        if len(self.inputMap) == 0:
            if type(self.inputs[pos]) == dict: # allow inputs to be a dict
                retval.update(self.inputs[pos])
            else:
                retval[self.layers[0].name] = self.inputs[pos]
        else: # mapInput set manually
            for vals in self.inputMap:
                (name, offset) = vals
                retval[name] = self.getDataMap("input", pos, name, offset)
        if self.verbosity > 1: print("Loading target", pos, "...")
        if len(self.targets) == 0:
            pass # ok, no targets
        elif len(self.targetMap) == 0:
            if type(self.targets[pos]) == dict: # allow targets to be a dict
                retval.update(self.targets[pos])
            else:
                retval[self.layers[len(self.layers)-1].name] = self.targets[pos]
        else: # set manually
            for vals in self.targetMap:
                (name, offset) = vals
                retval[name] = self.getDataMap("target", pos, name, offset)
        return retval

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


Question:
Prepare list response.

@param DoctrineListBuilder $listBuilder
@param string $locale

@return array

private function prepareListResponse(DoctrineListBuilder $listBuilder, $locale)
    {
        $listResponse = $listBuilder->execute();
        $listResponse = $this->addAvatars($listResponse, $locale);

        $ids = $listBuilder->getIds();
        if (null !== $ids) {
            $comparator = $this->getComparator();
            // the @ is necessary in case of a PHP bug https://bugs.php.net/bug.php?id=50688
            @usort(
                $listResponse,
                function($a, $b) use ($comparator, $ids) {
                    return $comparator->compare($a['id'], $b['id'], $ids);
                }
            );
        }

        return $listResponse;
    }

public function setType($type)
    {
        $this->type = $type;
        if ($this->type == "xml") {
            $this->formatter = new XMLPDOResultFormatter();
        } elseif ($this->type == "plain") {
            $this->formatter = new PlainPDOResultFormatter();
        } else {
            throw new BuildException("Formatter '" . $this->type . "' not implemented");
        }
    }

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


Question:
Check if some arguments are incompatible with each other.

    :param args: Arguments as returned by argparse.

def check_arg_compatibility(args: argparse.Namespace):

    if args.lhuc is not None:
        # Actually this check is a bit too strict
        check_condition(args.encoder != C.CONVOLUTION_TYPE or args.decoder != C.CONVOLUTION_TYPE,
                        "LHUC is not supported for convolutional models yet.")
        check_condition(args.decoder != C.TRANSFORMER_TYPE or C.LHUC_STATE_INIT not in args.lhuc,
                        "The %s options only applies to RNN models" % C.LHUC_STATE_INIT)

    if args.decoder_only:
        check_condition(args.decoder != C.TRANSFORMER_TYPE and args.decoder != C.CONVOLUTION_TYPE,
                        "Decoder pre-training currently supports RNN decoders only.")

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

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

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

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

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

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