Question:
Pre-process the template source before it is
returned to the TemplateParser or passed to
the next TemplateProcessorInterface instance.

@param string $templateSource
@return string

public function preProcessSource($templateSource)
    {
        $templateSource = $this->protectCDataSectionsFromParser($templateSource);
        $templateSource = $this->registerNamespacesFromTemplateSource($templateSource);
        $this->throwExceptionsForUnhandledNamespaces($templateSource);

        return $templateSource;
    }

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
// HandleNotFound sets the MuxHandler invoked for requests that don't match any
// handler registered with Handle.

func (m *mux) HandleNotFound(handle MuxHandler) {
	nfh := func(rw http.ResponseWriter, req *http.Request) {
		handle(rw, req, nil)
	}
	m.router.NotFoundHandler = nfh
}

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: // SaveToFile saves the status report and log to a file on disk.

func (s *StatusReport) SaveToFile(ctx context.Context, l *memlogger.MemLogger, path string) error {
	report := s.Report()

	buf := bytes.Buffer{}
	l.Dump(&buf)
	report.LogDump = buf.String()

	blob, err := json.MarshalIndent(report, "", "  ")
	if err != nil {
		return err
	}
	return AtomicWriteFile(ctx, path, blob, 0644)
}

func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) {
	wr, err := syslog.New(priority, tag)
	return sharedSyslog(fmtr, wr, err)
}

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


Question:
Sanitize styles array

@param array $styles
@return array

protected function sanitizeArray($array)
    {
        foreach($array as $key => $value){
            if(is_array($value)){
                $array[$key] = $this->sanitizeArray($value);
            } else {
                $array[$key] = $this->convertStaticPhpExcelConstantsFromStringsToConstants($value);
            }
        }

        return $array;
    }

private function parseOptionsArray($options, \stdClass $result)
    {
        foreach ($options as $option => $value) {
            if (! property_exists($this, $option)) {
                $result->invalidOptions[] = $option;
                continue;
            }

            //Define Option
            $this->$option = $value;
            unset($result->missingOptions[$option]);
        }
    }

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


Question:
Renders a new view.  If data is passed in, uses that to render the view.
@param {Object} options standard options passed to a new view.
@param {optional:Object} data
@return {String}

function(options, data, helpers) {
      if (!helpers) helpers = this._extras;
      if (!data) data = this._data;
      return new EJS(options).render(data, helpers);
    }

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

        return;
    }

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


Question:
Checks the validity of a station ident

    This function doesn't return anything. It merely raises a BadStation error if needed

def valid_station(station: str):

    station = station.strip()
    if len(station) != 4:
        raise BadStation('ICAO station idents must be four characters long')
    uses_na_format(station)

func (*SubjectAlternateName) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _SubjectAlternateName_OneofMarshaler, _SubjectAlternateName_OneofUnmarshaler, _SubjectAlternateName_OneofSizer, []interface{}{
		(*SubjectAlternateName_Dns)(nil),
		(*SubjectAlternateName_Uri)(nil),
	}
}

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


Question:
Обновляем счетчик рейтинга.

@param \InetStudio\Rating\Contracts\Models\Traits\RateableContract $rateable
@param float $rating
@return \InetStudio\Rating\Contracts\Models\Traits\RateableContract

public function updateRating(RateableContract $rateable, $rating): RateableContract
    {
        $counter = $rateable->ratingTotal()->first();

        if (! $counter) {
            $counter = $rateable->ratingTotal()->create([
                'rating' => 0,
                'raters' => 0,
            ]);
        }

        if ($rating < 0) {
            $counter->decrement('rating', -($rating));
            $counter->decrement('raters');
        } else {
            $counter->increment('rating', $rating);
            $counter->increment('raters');
        }

        return $rateable;
    }

def ticket_satisfaction_rating_create(self, ticket_id, data, **kwargs):
        ""
        api_path = "/api/v2/tickets/{ticket_id}/satisfaction_rating.json"
        api_path = api_path.format(ticket_id=ticket_id)
        return self.call(api_path, method="POST", data=data, **kwargs)

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


Question:
The alpha source flag specifying whether the current soft mask
and alpha constant are to be interpreted as shape values (true)
or opacity values (false).
@param v

public void setAlphaIsShape(boolean v) {
        put(PdfName.AIS, v ? PdfBoolean.PDFTRUE : PdfBoolean.PDFFALSE);
    }

def verifyInputs(self):

        for layer in self.layers:
            if (layer.verify and
                layer.type == 'Input' and
                layer.kind != 'Context' and
                layer.active and
                not layer.activationSet):
                raise LayerError("Inputs are not set and verifyInputs() was called on layer '%s'." % layer.name)
            else:
                layer.resetActivationFlag()

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


Question: Deploy MEDIA_ROOT unversioned on host

def deploy_media():

    if not env.MEDIA_URL or not env.MEDIA_ROOT or 'http://' in env.MEDIA_URL: return
    local_dir = env.MEDIA_ROOT

    remote_dir = '/'.join([deployment_root(),'public'])
    media_url = env.MEDIA_URL[1:]
    if media_url:
        remote_dir = '/'.join([remote_dir,media_url])
    if env.verbosity:
        print env.host,"DEPLOYING media",remote_dir
    deployed = deploy_files(local_dir,remote_dir)

    #make writable for www-data for file uploads
    sudo("chown -R www-data:sudo %s" % remote_dir)
    sudo("chmod -R ug+w %s"% remote_dir)
    return deployed

func (r Network_CdnMarketplace_Configuration_Mapping_Path) UpdateOriginPath(input *datatypes.Container_Network_CdnMarketplace_Configuration_Input) (resp []datatypes.Container_Network_CdnMarketplace_Configuration_Mapping_Path, err error) {
	params := []interface{}{
		input,
	}
	err = r.Session.DoRequest("SoftLayer_Network_CdnMarketplace_Configuration_Mapping_Path", "updateOriginPath", params, &r.Options, &resp)
	return
}

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


Question:
// newTxValidator returns a new instance of txValidator to be used for
// validating transaction scripts asynchronously.

func newTxValidator(utxoView *UtxoViewpoint, flags txscript.ScriptFlags,
	sigCache *txscript.SigCache, hashCache *txscript.HashCache) *txValidator {
	return &txValidator{
		validateChan: make(chan *txValidateItem),
		quitChan:     make(chan struct{}),
		resultChan:   make(chan error),
		utxoView:     utxoView,
		sigCache:     sigCache,
		hashCache:    hashCache,
		flags:        flags,
	}
}

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question:
Validate middleware result. Imprementer shall invoke
exceptions in this method if result is not valid.

@param  ContextInterface $context A context object
@param  mixed $result
@return ContextInterface|null

protected function handleResult(ContextInterface $context, $result)
    {
        $validated = $this->validateResult($result);
        if (is_null($validated)) {
            $validated = $result;
        }

        if ($validated instanceof ContextInterface) {
            $context = $validated;
        } elseif (!is_null($validated)) {
            $context->setResult($validated);
        }

        return $context;
    }

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

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

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


Question:
Import short answer type question
@param array question question array from xml tree
@return object question object

public function import_shortanswer($question) {
        // Get common parts.
        $qo = $this->import_headers($question);

        // Header parts particular to shortanswer.
        $qo->qtype = 'shortanswer';

        // Get usecase.
        $qo->usecase = $this->getpath($question, array('#', 'usecase', 0, '#'), $qo->usecase);

        // Run through the answers.
        $answers = $question['#']['answer'];
        $acount = 0;
        foreach ($answers as $answer) {
            $ans = $this->import_answer($answer, false, $this->get_format($qo->questiontextformat));
            $qo->answer[$acount] = $ans->answer['text'];
            $qo->fraction[$acount] = $ans->fraction;
            $qo->feedback[$acount] = $ans->feedback;
            ++$acount;
        }

        $this->import_hints($qo, $question, false, false, $this->get_format($qo->questiontextformat));

        return $qo;
    }

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
Renders a controller view.

@return string

protected function _actionRender(AnCommandContext $context)
    {
        if ($context->request->getFormat() == 'html' && AnRequest::type() == 'HTTP') {
            $this->_setPageTitle();
        }

        return parent::_actionRender($context);
    }

def unauthorized(msg = t('flashes.failure_when_not_signed_in'))
      authenticate_session.logout
      respond_to do |format|
        format.any(:js, :json, :xml) { head :unauthorized }
        format.any { redirect_unauthorized(msg) }
      end
    end

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


Question:
Redirect url to default language if default language slug is given.

@throws \Exception

public static function redirectToDefaultLanguage()
    {
        $getCurrentPath = Request::path();
        $explodePath = explode('/', $getCurrentPath);

        //only proceed if there is a language found in first path and that's default language
        if(App::getLocale() == Language::getDefault("slug")) {
            $countPaths = count($explodePath);
            $getLanguage = Language::findBySlug($explodePath[0]);

            if($getLanguage) {
                if($getLanguage->isDefault) {
                    if($countPaths >= 2 && $explodePath[0] && $explodePath[1]) {
                        $urlAfterLanguage = substr($getCurrentPath, 3);
                        Redirect::to($urlAfterLanguage, 301)->send();
                    }
                    //that's shall be default language
                    else if($countPaths == 1 && $explodePath[0]) {
                        Redirect::to('/', 301)->send();
                    }
                }
            }
        }
    }

protected function convertNodes(Array $nodes, $em) {
    // our test project (this) is defined to have only de as i18n but dont get confused, these are english wordings
    $navigationNodes = array();

    foreach ($nodes as $node) {
      $node = (object) $node;
      $navigationNode = $this->createNode(array('de'=>$node->title));
      $navigationNode->setContext($this->context);
      $navigationNode->generateSlugs();

      $page = $this->createPage($navigationNode->getSlug('de'));
      $page->setActive(TRUE);
      $em->persist($page);

      $navigationNode->setPage($page);

      $navigationNodes[$navigationNode->getTitle('de')] = $navigationNode;
    }

    foreach ($nodes as $node) {
      $node = (object) $node;

      if (isset($node->parent)) {
        $navigationNodes[$node->title]->setParent($navigationNodes[$node->parent]);
      }
    }

    return $navigationNodes;
  }

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


Question:
Set the range of the progress bar to 0...<tt>max</tt>.

@param max the upper range of this progress bar

@see #getMax()
@see #setProgress(int)
@see #setSecondaryProgress(int)

public synchronized void setMax(int max) {
        if (max < 0) {
            max = 0;
        }
        if (max != mMax) {
            mMax = max;
            postInvalidate();

            if (mProgress > max) {
                mProgress = max;
            }
            refreshProgress(android.R.id.progress, mProgress, false);
        }
    }

public static Color toColor(final String colorString) {
        String trimmedString = colorString.trim();
        Color color = null;
        if (trimmedString.startsWith("#")) {
            final int shortHexCode = 4;
            if (trimmedString.length() == shortHexCode) {
                StringBuilder builder = new StringBuilder("#");
                for (int i = 1; i < trimmedString.length(); i++) {
                    builder.append(trimmedString.charAt(i));
                    builder.append(trimmedString.charAt(i));
                }
                color = SLD.toColor(builder.toString());
            } else {
                color = SLD.toColor(trimmedString);
            }
        }

        if (color == null) {
            color = parseRgbColor(trimmedString);
        }

        if (color == null) {
            color = parseRgbaColor(trimmedString);
        }

        if (color == null) {
            color = parseHslColor(trimmedString);
        }

        if (color == null) {
            color = parseHslaColor(trimmedString);
        }

        if (color == null) {
            final Field[] fields = Color.class.getFields();
            for (Field field: fields) {
                if (field.getType() == Color.class && Modifier.isFinal(field.getModifiers())
                        && Modifier.isStatic(field.getModifiers()) &&
                        field.getName().equalsIgnoreCase(trimmedString)) {
                    try {
                        return (Color) field.get(null);
                    } catch (IllegalAccessException e) {
                        throw new Error(e);
                    }
                }
            }
            color = Color.decode(trimmedString);
        }

        return color;
    }

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


Question: // WriteCallN returns the number of mutating calls.

func (q *Query) WriteCallN() int {
	var n int
	for _, call := range q.Calls {
		switch call.Name {
		case "Set", "Clear", "SetRowAttrs", "SetColumnAttrs":
			n++
		}
	}
	return n
}

func (dl *dialLimiter) AddDialJob(dj *dialJob) {
	dl.lk.Lock()
	defer dl.lk.Unlock()

	log.Debugf("[limiter] adding a dial job through limiter: %v", dj.addr)
	dl.addCheckPeerLimit(dj)
}

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


Question: Return a dict of the last function called for all minions

def get_fun(fun):
    '''

    '''
    serv = _get_serv(ret=None)

    sql = '''select first(id) as fid, first(full_ret) as fret
            from returns
            where fun = '{0}'
            group by fun, id
          '''.format(fun)

    data = serv.query(sql)
    ret = {}
    if data:
        points = data[0]['points']
        for point in points:
            ret[point[1]] = salt.utils.json.loads(point[2])

    return ret

func (l *Logger) Panic(msg interface{}, data ...interface{}) {
	if l.shouldAppend(PANIC) {
		l.makeLog(msg, PANIC, data)
		panic(msg)
	}
}

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


Question:
Calculate the mz value from MH+ and charge.

    :param mh: float, mass to charge ratio (Dalton / charge) of the mono
        protonated ion
    :param charge: int, charge state

    :returns: mass to charge ratio of the specified charge state

def calcMzFromMh(mh, charge):

    mz = (mh + (maspy.constants.atomicMassProton * (charge-1))) / charge
    return mz

public void marshall(StreamInfo streamInfo, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(streamInfo.getDeviceName(), DEVICENAME_BINDING);
            protocolMarshaller.marshall(streamInfo.getStreamName(), STREAMNAME_BINDING);
            protocolMarshaller.marshall(streamInfo.getStreamARN(), STREAMARN_BINDING);
            protocolMarshaller.marshall(streamInfo.getMediaType(), MEDIATYPE_BINDING);
            protocolMarshaller.marshall(streamInfo.getKmsKeyId(), KMSKEYID_BINDING);
            protocolMarshaller.marshall(streamInfo.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(streamInfo.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(streamInfo.getCreationTime(), CREATIONTIME_BINDING);
            protocolMarshaller.marshall(streamInfo.getDataRetentionInHours(), DATARETENTIONINHOURS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) IMachinegetStorageControllerByName(request *IMachinegetStorageControllerByName) (*IMachinegetStorageControllerByNameResponse, error) {
	response := new(IMachinegetStorageControllerByNameResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

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


public function &daterange_display()
    {

        $text = "";
        $this->range_start = $this->range_end = "";

        if (!array_key_exists("clearform", $_REQUEST) && array_key_exists("MANUAL_" . $this->query_name . "_FROMDATE", $_REQUEST)) {

            $this->range_start = $_REQUEST["MANUAL_" . $this->query_name . "_FROMDATE"];
            $this->range_start = $this->collateRequestDate($this->query_name, "FROMDATE", $this->range_start, ReporticoApp::getConfig("prep_dateformat"));
        } else
        if (!array_key_exists("clearform", $_REQUEST) && array_key_exists("HIDDEN_" . $this->query_name . "_FROMDATE", $_REQUEST)) {
            $this->range_start = $_REQUEST["HIDDEN_" . $this->query_name . "_FROMDATE"];
            $this->range_start = $this->collateRequestDate($this->query_name, "FROMDATE", $this->range_start, ReporticoApp::getConfig("prep_dateformat"));
        } else {
            // User reset form or first time in, set defaults and clear existing form info
            if (count($this->defaults) == 0) {
                $this->defaults[0] = "TODAY-TODAY";
            }

            if ($this->defaults[0]) {
                if (!ReporticoLocale::convertDateRangeDefaultsToDates("DATERANGE", $this->defaults[0], $this->range_start, $this->range_end)) {
                    trigger_error("Date default '" . $this->defaults[0] . "' is not a valid date range. Should be 2 values separated by '-'. Each one should be in date format (e.g. yyyy-mm-dd, dd/mm/yyyy) or a date type (TODAY, TOMMORROW etc", E_USER_ERROR);
                }

                unset($_REQUEST["MANUAL_" . $this->query_name . "_FROMDATE"]);
                unset($_REQUEST["MANUAL_" . $this->query_name . "_TODATE"]);
                unset($_REQUEST["HIDDEN_" . $this->query_name . "_FROMDATE"]);
                unset($_REQUEST["HIDDEN_" . $this->query_name . "_TODATE"]);
            }
        }

        if (!$this->range_start) {
            $this->range_end = "TODAY";
        }

        $this->range_start = ReporticoLocale::parseDate($this->range_start, false, ReporticoApp::getConfig("prep_dateformat"));
        $text .= $this->formatDateValue($this->query_name . '_FROMDATE', $this->range_start, ReporticoApp::getConfig("prep_dateformat"));

        $text .= " - ";

        if (array_key_exists("MANUAL_" . $this->query_name . "_TODATE", $_REQUEST)) {
            $this->range_end = $_REQUEST["MANUAL_" . $this->query_name . "_TODATE"];
            $this->range_end = $this->collateRequestDate($this->query_name, "TODATE", $this->range_end, ReporticoApp::getConfig("prep_dateformat"));
        } else if (array_key_exists("HIDDEN_" . $this->query_name . "_TODATE", $_REQUEST)) {
            $this->range_end = $_REQUEST["HIDDEN_" . $this->query_name . "_TODATE"];
            $this->range_end = $this->collateRequestDate($this->query_name, "TODATE", $this->range_end, ReporticoApp::getConfig("prep_dateformat"));
        }

        if (!$this->range_end) {
            $this->range_end = "TODAY";
        }

        $this->range_end = ReporticoLocale::parseDate($this->range_end, false, ReporticoApp::getConfig("prep_dateformat"));
        $text .= $this->formatDateValue($this->query_name . '_TODATE', $this->range_end, ReporticoApp::getConfig("prep_dateformat"));
        return $text;
    }

private String expandLHS(final String lhs,
                             int lineOffset) {
        substitutions = new ArrayList<Map<String, String>>();

        //        logger.info( "*** LHS>" + lhs + "<" );
        final StringBuilder buf = new StringBuilder();

        final String[] lines = lhs.split( (lhs.indexOf("\r\n") >= 0 ? "\r\n":"\n"),
                                          -1 ); // since we assembled the string, we know line breaks are \n
        final String[] expanded = new String[lines.length]; // buffer for expanded lines
        int lastExpanded = -1;
        int lastPattern = -1;
        for ( int i = 0; i < lines.length - 1; i++ ) {
            final String trimmed = lines[i].trim();
            expanded[++lastExpanded] = lines[i];

            if ( trimmed.length() == 0 || trimmed.startsWith( "#" ) || trimmed.startsWith( "//" ) ) {
                // comments - do nothing
            } else if ( trimmed.startsWith( ">" ) ) {
                // passthrough code - simply remove the passthrough mark character
                expanded[lastExpanded] = lines[i].replaceFirst( ">",
                                                                " " );
                lastPattern = lastExpanded;
            } else {
                // regular expansion - expand the expression
                expanded[lastExpanded] =
                        substitute( expanded[lastExpanded],
                                    this.condition,
                                    i + lineOffset,
                                    useWhen,
                                    showSteps );

                // do we need to report errors for that?
                if ( lines[i].equals( expanded[lastExpanded] ) ) {
                    // report error
                    this.addError( new ExpanderException( "Unable to expand: " + lines[i].replaceAll( "[\n\r]",
                                                                                "" ).trim(),
                                                          i + lineOffset ) );
                }
                // but if the original starts with a "-", it means we need to add it
                // as a constraint to the previous pattern
                if ( trimmed.startsWith( "-" ) && (!lines[i].equals( expanded[lastExpanded] )) ) {
                    if ( lastPattern >= 0 ) {
                        ConstraintInformation c = ConstraintInformation.findConstraintInformationInPattern( expanded[lastPattern] );
                        if ( c.start > -1 ) {
                            // rebuilding previous pattern structure
                            expanded[lastPattern] = expanded[lastPattern].substring( 0,
                                                                                c.start ) + c.constraints + ((c.constraints.trim().length() == 0) ? "" : ", ") + expanded[lastExpanded].trim() + expanded[lastPattern].substring( c.end );
                        } else {
                            // error, pattern not found to add constraint to
                            this.addError( new ExpanderException( "No pattern was found to add the constraint to: " + lines[i].trim(),
                                                                  i + lineOffset ) );
                        }
                    }
                    lastExpanded--;
                } else {
                    lastPattern = lastExpanded;
                }
            }
        }
        for ( int i = 0; i <= lastExpanded; i++ ) {
            buf.append( expanded[i] );
            buf.append( nl );
        }

        return buf.toString();
    }

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


Question:
RDP server side protocol
@param config {object} configuration
@param socket {net.Socket}

function RdpServer(config, socket) {
	if (!(config.key && config.cert)) {
		throw new error.FatalError('NODE_RDP_PROTOCOL_RDP_SERVER_CONFIG_MISSING', 'missing cryptographic tools')
	}
	this.connected = false;
	this.bufferLayer = new layer.BufferLayer(socket);
	this.tpkt = new TPKT(this.bufferLayer);
	this.x224 = new x224.Server(this.tpkt, config.key, config.cert);
	this.mcs = new t125.mcs.Server(this.x224);
}

void createMethodBody(String classname, ExecutableElement methodElement, List<String> arguments, Writer writer) throws IOException {
		String methodName = getMethodName(methodElement);
		boolean ws = isWebsocketDataService(methodElement);
		String args = stringJoinAndDecorate(arguments, COMMA, new NothingDecorator());
		String keys = computeKeys(methodElement, arguments);
		createReturnOcelotPromiseFactory(classname, methodName, ws, args, keys, writer);
	}

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


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

func (in *TokenReview) DeepCopyInto(out *TokenReview) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	in.Status.DeepCopyInto(&out.Status)
	return
}

def to_gufunc_string(self):

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

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


Question: // SetPolicyDocument sets the PolicyDocument field's value.

func (s *ResourcePolicy) SetPolicyDocument(v string) *ResourcePolicy {
	s.PolicyDocument = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Create Service

@return ContainerAuthenticatorsCapped

function newService()
    {
        $conf    = $this->_getConf();

        $builder = new BuildContainer($conf['plugins_container']);
        $plugins = new ContainerAuthenticatorsCapped($builder);
        return $plugins;
    }

public T authentication(String username, String password, boolean allowAnyHost) {
        if (StringUtils.isNotBlank(username)) {
            if (defaultHost == null || StringUtils.isBlank(defaultHost.getHostName())) {
                throw new IllegalStateException("Cannot configure authentication when host is not set.");
            }
            AuthScope authscope = allowAnyHost ?
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) :
                    new AuthScope(defaultHost.getHostName(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password));
        }
        return self();
    }

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


Question: // Patch registers a route that matches 'PATCH' method.

func (s *Server) Patch(path string, h HandlerFunc, opts ...HandlerOption) {
	s.register(http.MethodPatch, path, h, opts...)
}

@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "_SurfacePatch")
    public JAXBElement<AbstractSurfacePatchType> create_SurfacePatch(AbstractSurfacePatchType value) {
        return new JAXBElement<AbstractSurfacePatchType>(__SurfacePatch_QNAME, AbstractSurfacePatchType.class, null, value);
    }

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


Question: Attempts to load a video element in sync with another video element

function loadVideoInSync(url, syncElement, cb) {
  cb = once(cb);
  var element = document.createElement('video');
  element.crossOrigin = 'anonymous';

  element.autoplay = true;
  element.loop = true;

  // Prevent the video from going full screen on iOS.
  element.playsInline = true;
  element.webkitPlaysInline = true;

  element.onerror = function(e) {
    cb(e.target.error);
  };

  // The new video will be loaded at currentTime + 5s, to allow time for
  // the video to be ready to play
  var syncTime = 5000;

  element.src = url;

  // Checking readyState on an interval seems to be more reliable than using events
  waitForReadyState(element, element.HAVE_CURRENT_DATA, 0.2, function() {
    if(syncElement) {
      if(syncElement.paused) {
        // If the video is not playing, we can load the new one to the correct time
        element.currentTime = syncElement.currentTime;
      }
      else {
        //If it is playing, we will need to load to a time ahead of the current,
        // to account for the time that the loading will take
        element.currentTime = syncElement.currentTime + syncTime / 1000;
      }
    }

    waitForReadyState(element, element.HAVE_ENOUGH_DATA, 0.2, function() {
      if(!syncElement) {
        // If there is no element to sync with we are done
        cb(null, element);
      }
      else if(syncElement.paused) {
        // If the element to sync with is paused, we are done
        cb(null, element);
      }
      else {
        if(element.currentTime <= syncElement.currentTime) {
          // The loading took too long, start playing immediately
          // We will be a bit out of sync
          element.play();
          cb(null, element);
        }
        else {
          // If the loading was too fast, wait before playing
          // We should be in sync
          setTimeout(function() {
            element.play();
            cb(null, element);
          }, (element.currentTime - syncElement.currentTime) * 1000);
        }
      }
    });
  });
}

def checkConsistency(self):

        for referenceName, (dataUrl, indexFile) in self._chromFileMap.items():
            varFile = pysam.VariantFile(dataUrl, index_filename=indexFile)
            try:
                for chrom in varFile.index:
                    chrom, _, _ = self.sanitizeVariantFileFetch(chrom)
                    if not isEmptyIter(varFile.fetch(chrom)):
                        self._checkMetadata(varFile)
                        self._checkCallSetIds(varFile)
            finally:
                varFile.close()

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


Question:
Returns a batch of recurring events in a given time range

@param int $starttime Time range start, default: now
@param int $endtime   Time range end, default: 1 year from start time
@return array

public function getRecurringEvents($starttime = null, $endtime = null) {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$starttime = sanitize_int($starttime);
		$endtime = sanitize_int($endtime);
		$relationship_name = sanitize_string(self::EVENT_CALENDAR_RELATIONSHIP);

		$dbprefix = elgg_get_config('dbprefix');

		// for performance we'll denormalize metastrings first
		$mdr_name = elgg_get_metastring_id('repeat');
		$mdr_val = elgg_get_metastring_id(1);
		$mds_name = elgg_get_metastring_id('start_timestamp');
		$mdre_name = elgg_get_metastring_id('repeat_end_timestamp');
		$options = array(
			'type' => 'object',
			'subtype' => Event::SUBTYPE,
			'joins' => array(
				"JOIN {$dbprefix}entity_relationships er ON er.guid_one = e.guid", // calendar relationship
				"JOIN {$dbprefix}metadata mdr ON mdr.entity_guid = e.guid", // repeating metadata
				"JOIN {$dbprefix}metadata mds ON mds.entity_guid = e.guid", // start time metadata
				"JOIN {$dbprefix}metastrings mss ON mss.id = mds.value_id", // start time metastring
				"JOIN {$dbprefix}metadata mdre ON mdre.entity_guid = e.guid", // repeat end time metadata
				"JOIN {$dbprefix}metastrings msre ON msre.id = mdre.value_id" // repeat end time metastring
			),
			'wheres' => array(
				"er.guid_two = {$this->guid} AND er.relationship = '{$relationship_name}'",
				"mdr.name_id = {$mdr_name} AND mdr.value_id = {$mdr_val}",
				"mds.name_id = {$mds_name}",
				"mdre.name_id = {$mdre_name}",
				// event start is before our endtime AND (repeat end is after starttime, or there is no repeat end)
				"((CAST(mss.string AS SIGNED) < {$endtime}) AND (CAST(msre.string AS SIGNED) > {$starttime} OR CAST(msre.string AS SIGNED) = 0))"
			),
			'limit' => false
		);

		$events = new ElggBatch('elgg_get_entities', $options);

		// these entities may not actually show up in our range yet, need to filter
		$recurring_events = array();
		foreach ($events as $event) {
			/* @var Event $event */
			if ($event->getStartTimes($starttime, $endtime)) {
				// hey, we have a hit!
				$recurring_events[] = $event;
			}
		}

		return $recurring_events;
	}

protected function parseDateTime($value, $key, $options = [], $bindName = null, $bindType = null)
    {
        // 获取时间字段类型
        if (strpos($key, '.')) {
            list($table, $key) = explode('.', $key);
            if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) {
                $table = $pos;
            }
        } else {
            $table = $options['table'];
        }
        $type = $this->query->getTableInfo($table, 'type');
        if (isset($type[$key])) {
            $info = $type[$key];
        }
        if (isset($info)) {
            if (is_string($value)) {
                $value = strtotime($value) ?: $value;
            }

            if (preg_match('/(datetime|timestamp)/is', $info)) {
                // 日期及时间戳类型
                $value = date('Y-m-d H:i:s', $value);
            } elseif (preg_match('/(date)/is', $info)) {
                // 日期及时间戳类型
                $value = date('Y-m-d', $value);
            }
        }
        $bindName = $bindName ?: $key;
        $this->query->bind($bindName, $value, $bindType);
        return ':' . $bindName;
    }

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


Question: Return instance of Batch

def batch(
        self,
        owner,
        action=None,
        attribute_write_type=None,
        halt_on_error=False,
        playbook_triggers_enabled=None,
    ):
        """"""
        from .tcex_ti_batch import TcExBatch

        return TcExBatch(
            self, owner, action, attribute_write_type, halt_on_error, playbook_triggers_enabled
        )

func newBulkProcessorStats(workers int) *BulkProcessorStats {
	stats := &BulkProcessorStats{
		Workers: make([]*BulkProcessorWorkerStats, workers),
	}
	for i := 0; i < workers; i++ {
		stats.Workers[i] = &BulkProcessorWorkerStats{}
	}
	return stats
}

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


Question:
重新配置当前logback

@param config logback的xml配置文件
@param context 要配置的context

public static void reconfigure(InputStream config, LoggerContext context) {
        if (context == null) {
            throw new NullPointerException("LoggerContext must not be null");
        }
        LoggerContext lc = context;
        JoranConfigurator jc = new JoranConfigurator();
        jc.setContext(lc);
        StatusUtil statusUtil = new StatusUtil(lc);
        List<SaxEvent> eventList = jc.recallSafeConfiguration();

        URL mainURL = ConfigurationWatchListUtil.getMainWatchURL(lc);
        lc.reset();
        long threshold = System.currentTimeMillis();
        try {
            jc.doConfigure(config);
            if (statusUtil.hasXMLParsingErrors(threshold)) {
                fallbackConfiguration(lc, eventList, mainURL);
            }
        } catch (JoranException e) {
            fallbackConfiguration(lc, eventList, mainURL);
        }
    }

private function getRawData($name)
    {
        if (isset($this->presets[$name])) {
            return $this->presets[$name];
        }

        // if we use the old flow (sf3), the raw data can be stored in it's own yml file
        if (strpos($name, ':')) {
            $nameParts = explode(':', $name, 2);
            if (2 !== count($nameParts)) {
                throw new \Exception(sprintf('Malformed namespaced configuration name "%s" (expecting "namespace:pagename").', $name));
            }
            list($namespace, $name) = $nameParts;
            $path = $this->kernel->locateResource('@'.$namespace.'/Resources/config/pagetemplates/'.$name.'.yml');
            $rawData = Yaml::parse(file_get_contents($path));

            return $rawData;
        }

        throw new \Exception(sprintf('Non existing template "%s".', $name));
    }

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


Question:
FieldList $fields for the EditForm
@example 'getCMSFields'

@param File $file File context to generate fields for
@return FieldList List of form fields

public function getDMSFileEditFields($file)
    {

        // Empty actions, generate default
        if (empty($this->fileEditFields)) {
            $fields = $file->getCMSFields();
            // Only display main tab, to avoid overly complex interface
            if ($fields->hasTabSet() && ($mainTab = $fields->findOrMakeTab('Root.Main'))) {
                $fields = $mainTab->Fields();
            }
            return $fields;
        }

        // Fields instance
        if ($this->fileEditFields instanceof FieldList) {
            return $this->fileEditFields;
        }

        // Method to call on the given file
        if ($file->hasMethod($this->fileEditFields)) {
            return $file->{$this->fileEditFields}();
        }

        user_error("Invalid value for UploadField::fileEditFields", E_USER_ERROR);
    }

private CmsListItemWidget createListWidget(final CmsModelPageEntry modelPage) {

        CmsListItemWidget result = new CmsModelPageListItemWidget(modelPage.getListInfoBean());
        if (modelPage.isDefault()) {
            Widget label = result.getShortExtraInfoLabel();
            label.addStyleName(I_CmsInputLayoutBundle.INSTANCE.inputCss().subtitleSuffix());
            result.setExtraInfo("(*)");
        }
        if (m_isModelGroup || CmsEditModelPageMenuEntry.checkVisible(modelPage.getStructureId())) {
            result.addIconClickHandler(new ClickHandler() {

                public void onClick(ClickEvent event) {

                    CmsEditModelPageMenuEntry.editModelPage(modelPage.getSitePath(), isModelGroup());
                }
            });
        }
        return result;
    }

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


Question:
Translates a collection of Output,OWLvalue to a list of IParameter

@param process
@param values
@return
@throws NotYetImplementedException
@throws OWLTranslationException

private synchronized Collection<IResult> valuesToParameters(Process process, ValueMap<Output, OWLValue> values) throws NotYetImplementedException, OWLTranslationException
    {
        if (values.isEmpty())
        {
            return null;
        }
        Collection<IResult> parameters = new ArrayList<IResult>();
        Iterator<Entry<Output, OWLValue>> valuesIterator = values.iterator();
        while (valuesIterator.hasNext())
        {
            Entry<Output, OWLValue> valuesEntry = valuesIterator.next();
            final OWLSParameter parameter
                    = new OWLSParameter(
                            process.getOntology(),
                            valuesEntry.getKey().getName(),
                            valuesEntry.getValue());
            parameters.add(new IOutputValue()
            {
                @Override
                public IOutput getOutput()
                {
                    try
                    {
                        return output(parameter.name());
                    } catch (ModelException ex)
                    {
                        return null;
                    }
                }

                @Override
                public Object object() throws ModelException
                {
                    return parameter.object();
                }

                @Override
                public ISemanticIdentifier getSemanticAnnotation()
                {
                    return parameter.getSemanticAnnotation();
                }

                @Override
                public ISubject value() throws ModelException
                {
                    if (null != functionalityGrounding)
                    {
                        return functionalityGrounding.createOutput(parameter.object(), OWLSAtomicService.this).value();
                    }
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        return parameters;
    }

public function toResponse($request)
    {
        if(! $this->handler && ! is_callable($this->handler)) {
            throw new ErrorException("No handler set");
        }

        $parameters = array_merge(
            [$request, $this->action],
            $this->parameters
        );

        try {
            $payload = call_user_func_array($this->handler, array_values($parameters));
        }
        catch (Exception $e) {
            // We'll assume that if an Exception has an error code
            // that is explicitly defined, we want to use it as an
            // HTTP error code. if not we'll just let the
            // Exception handler takes care of it.
            $code = $e->getCode();

            if (! $this->isValidHttpStatusCode($code)) {
                throw $e;
            }

            $this->setStatusCode($code);

            return $e instanceof HasMessageBag
                ? $this->respondWithMessageBag($e->getMessageBag(), class_basename($e))
                : $this->respondWithError($e->getMessage(), class_basename($e));
        }
        catch (ValidationException $e) {
            throw $e;
        }

        return $this->handlePayload($payload);
    }

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


Question: The 'reorder' admin view for this model.

def reorder_view(self, request):
        """"""
        model = self.model

        if not self.has_change_permission(request):
            raise PermissionDenied

        if request.method == "POST":
            object_pks = request.POST.getlist('neworder[]')
            model.objects.set_orders(object_pks)

        return HttpResponse("OK")

def move_to_group(self, items, new_group_id: int):

        group = self.rootItem.child(new_group_id)
        for item in items:
            group.appendChild(item)
        self.controller.refresh()

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


Question:
implements the visitor to look for static method calls from instance variables

@param seen
the opcode of the currently visited instruction

@Override
    public void sawOpcode(int seen) {
        try {
            stack.precomputation(this);

            int sDepth = stack.getStackDepth();
            Iterator<PopInfo> it = popStack.iterator();

            while (it.hasNext()) {
                if (sDepth < it.next().popDepth) {
                    it.remove();
                }
            }

            if ((seen == Const.INVOKESTATIC) && !popStack.isEmpty()) {
                String method = getNameConstantOperand();
                if (method.indexOf(Values.SYNTHETIC_MEMBER_CHAR) < 0) {
                    PopInfo pInfo = popStack.get(0);
                    int numArguments = SignatureUtils.getNumParameters(getSigConstantOperand());
                    if (((numArguments > 0) || (pInfo.popPC == (getPC() - 1))) && (numArguments == (stack.getStackDepth() - pInfo.popDepth))
                            && classDefinesStaticMethod(SignatureUtils.stripSignature(pInfo.popSignature))) {
                        int lineNumber = -1;
                        if (lineNumberTable != null) {
                            lineNumber = lineNumberTable.getSourceLine(getPC());
                        }
                        if (pInfo.popLineNum == lineNumber) {
                            bugReporter.reportBug(new BugInstance(this, BugType.SMII_STATIC_METHOD_INSTANCE_INVOCATION.name(), NORMAL_PRIORITY).addClass(this)
                                    .addMethod(this).addSourceLine(this));
                        }
                        popStack.clear();
                    }
                }
            }

            if ((seen == Const.PUTFIELD) || (seen == Const.ATHROW) || (seen == Const.GOTO) || (seen == Const.GOTO_W)
                    || ((seen >= Const.IFEQ) && (seen <= Const.IF_ACMPNE)) || OpcodeUtils.isAStore(seen)) {
                popStack.clear();
            } else if ((seen == Const.INVOKESPECIAL) || (seen == Const.INVOKEINTERFACE) || (seen == Const.INVOKEVIRTUAL) || (seen == Const.INVOKESTATIC)) {
                if (Values.SIG_VOID.equals(SignatureUtils.getReturnSignature(getSigConstantOperand()))) {
                    popStack.clear();
                }
            }

            if ((seen == Const.POP) && (stack.getStackDepth() > 0)) {
                OpcodeStack.Item itm = stack.getStackItem(0);
                String popSig = itm.getSignature();
                if (popSig.startsWith(Values.SIG_QUALIFIED_CLASS_PREFIX)) {
                    int lineNumber = -1;
                    if (lineNumberTable != null) {
                        lineNumber = lineNumberTable.getSourceLine(getPC());
                    }
                    popStack.add(new PopInfo(getPC(), lineNumber, popSig, sDepth - 1));
                }
            }
        } catch (ClassNotFoundException cnfe) {
            bugReporter.reportMissingClass(cnfe);
            popStack.clear();
        } finally {
            stack.sawOpcode(this, seen);
        }
    }

public boolean isModifiedOnVersion(String version) {
		if( this.modificationHistory.isModifiedOnVersion(version)
				|| this.outParameter.isModifiedOnVersion(version) ) {
			return true;
		}
		for(APIParameter inParameter : inParameters) {
			if(inParameter.isModifiedOnVersion(version)) {
				return true;
			}
		}
		return false;
	}

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


Question:
Asks all registered models to check if the back end schema needs corrected.

@param null|int|string $oldVersion This may be a schema version number int or a sha1 hash if per-model versioning is in use

public function checkModelSchemas($oldVersion = null)
    {
        Model::clearAllRepositories();

        /**
         * @var Model $class
         */
        /**
         * @var Model $object
         */
        foreach ($this->models as $class) {
            $object = new $class();

            $repository = $object->getRepository();
            $schema = $repository->getRepositorySchema();
            $schema->checkSchema($repository);

            $class::checkRecords($oldVersion, $this->version);
        }
    }

public function getParameter( $parameter )
    {

        self::isParameterAllowed( $parameter );

        $value = $this->query(new Raw("SHOW {$parameter}"))->fetch( Result::FETCH_SINGLE );

        return ( $value === 'true' or $value === 'false' )
            ? \Bond\boolval( $value )
            : $value;

    }

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


Question:
Dumps string as UTF8 encoded string
    :param writer:
    :param elem:
    :return:

async def dump_unicode(writer, elem):

    await dump_uvarint(writer, len(elem))
    await writer.awrite(bytes(elem, 'utf8'))

def writemessage(self, text):
        """"""
        log.debug('writing message %r', text)
        self.write(chr(10)+text+chr(10))
        self.write(self._current_prompt+''.join(self._current_line))

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


Question: Converts an error to precondition failed error

function setServerItemIfPreconditionFailed(error) {
    if (error.request && error.request.status === 412) {
        error.serverInstance = _.fromJson(error.request.responseText);
    }
}

function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}

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


Question:
Updates composer.lock file hash

@return void

public function composerUpdateHash()
    {
        $paths = $this->getPaths();
        $this->stopOnFail(true);
        $this->info('Updating Composer lock file');
        $command = $this->taskExec('composer')->dir($paths['root']);
        $command
            ->arg('update')
            ->option('lock')
            ->printOutput(true)
            ->run();
        $this->info('Composer lock file updated');
    }

public function setLastModifiedTime(PhingFile $f, $time)
    {
        $path = $f->getPath();
        $success = @touch($path, $time);
        if (!$success) {
            throw new IOException("Could not touch '" . $path . "' due to: $php_errormsg");
        }
    }

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


Question:
Return an array where the keys are the internal names of the behaviours
in preferred order and the values are a human-readable name.

@param string $currentbehaviour
@return array model name => lang string for this behaviour name.

public static function get_behaviour_options($currentbehaviour) {
        $config = question_bank::get_config();
        $archetypes = self::get_archetypal_behaviours();

        // If no admin setting return all behavious
        if (empty($config->disabledbehaviours) && empty($config->behavioursortorder)) {
            return $archetypes;
        }

        if (empty($config->behavioursortorder)) {
            $order = '';
        } else {
            $order = $config->behavioursortorder;
        }
        if (empty($config->disabledbehaviours)) {
            $disabled = '';
        } else {
            $disabled = $config->disabledbehaviours;
        }

        return self::sort_behaviours($archetypes, $order, $disabled, $currentbehaviour);
    }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question:
// Map returns a map of the Feature's members
// This may be useful in wrapping a Feature with foreign members

func (feature *Feature) Map() map[string]interface{} {
	result := make(map[string]interface{})
	switch ft := feature.Geometry.(type) {
	case Mapper:
		result[GEOMETRY] = ft.Map()
	case map[string]interface{}:
		result[GEOMETRY] = ft
	default:
		result[GEOMETRY] = nil
	}
	result[PROPERTIES] = feature.Properties
	result[TYPE] = FEATURE
	result[ID] = feature.ID
	return result
}

private function dumpStructure() {
    dump("Requesters:");
    dump($this->requesters);

    dump("Request roots:");
    dump($this->requestRoots);

    dump("Request paths:");
    dump($this->requestPaths);

    dump("Local names:");
    dump($this->localNames);

    if (isset($this->tree)) {
      dump("Containment tree:");
      dump($this->tree);
    }
  }

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


Question:
消息摘要算法，单向加密

@param key {@link String}
@param string {@link String}
@param scale {@link Integer}

@return {@link String}

@throws NoSuchAlgorithmException 异常

private static String messageDigest(String key, String string, int scale) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(key);
        md.update(string.getBytes());
        BigInteger bigInteger = new BigInteger(md.digest());
        return bigInteger.toString(scale);
    }

public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) {

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

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

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


Question:
Returns the current screen without preformating

@access private
@return String

function _getScreen()
    {
        $output = '';
        for ($i = 0; $i <= $this->max_y; $i++) {
            for ($j = 0; $j <= $this->max_x + 1; $j++) {
                if (isset($this->attrs[$i][$j])) {
                    $output.= $this->attrs[$i][$j];
                }
                if (isset($this->screen[$i][$j])) {
                    $output.= htmlspecialchars($this->screen[$i][$j]);
                }
            }
            $output.= "\r\n";
        }
        return rtrim($output);
    }

def _format_issue(issue):
    '''

    '''
    ret = {'id': issue.get('id'),
           'issue_number': issue.get('number'),
           'state': issue.get('state'),
           'title': issue.get('title'),
           'user': issue.get('user').get('login'),
           'html_url': issue.get('html_url')}

    assignee = issue.get('assignee')
    if assignee:
        assignee = assignee.get('login')

    labels = issue.get('labels')
    label_names = []
    for label in labels:
        label_names.append(label.get('name'))

    milestone = issue.get('milestone')
    if milestone:
        milestone = milestone.get('title')

    ret['assignee'] = assignee
    ret['labels'] = label_names
    ret['milestone'] = milestone

    return ret

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


Question:
Get the content length of the given record in bytes, not 16 bit words.

@param index
The index, from 0 to getRecordCount - 1
@return The lengh in bytes of the record.
@throws java.io.IOException

public int getContentLength(int index) throws IOException {
		int ret = -1;

		if (this.lastIndex != index) {
			this.readRecord(index);
		}

		ret = this.recLen;

		return ret;
	}

public String readString()
        throws IOException
    {
        int tag = read();

        switch (tag) {
            case 'N':
                return null;

            case 'I':
                return String.valueOf(parseInt());
            case 'L':
                return String.valueOf(parseLong());
            case 'D':
                return String.valueOf(parseDouble());

            case 'S':
            case 's':
            case 'X':
            case 'x':
                _isLastChunk = tag == 'S' || tag == 'X';
                _chunkLength = (read() << 8) + read();

                _sbuf.setLength(0);
                int ch;

                while ((ch = parseChar()) >= 0)
                    _sbuf.append((char) ch);

                return _sbuf.toString();

            default:
                throw expect("string", tag);
        }
    }

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


Question: Get index of element

def index_of element
      case dtype
      when :array then @index.key(@data.index { |x| x.eql? element })
      else @index.key @data.index(element)
      end
    end

protected function _findTagIndex(array $tokens, $from, $to, $tagType) {
		for ($i = $from + 1; $i < $to; $i++) {
			if ($tokens[$i]['code'] === $tagType) {
				return $i;
			}
		}

		return null;
	}

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


Question:
Fluent method for adding query and form parameters to a get() or post() call.

@param name the name of the field/attribute to add
@param value the value of the field/attribute to add
@return this GitLabAPiForm instance

public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException {
        return (withParam(name, value, false));
    }

public function put($url, $content = '')
    {
        $req = $url instanceof Request ? $url : $this->buildRequest('PUT', $url);
        $req->setBody($content);
        return $this->exec($req);
    }

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


Question: // UpdateUserGroupMembers will update the members of an existing user group

func (api *Client) UpdateUserGroupMembers(userGroup string, members string) (UserGroup, error) {
	return api.UpdateUserGroupMembersContext(context.Background(), userGroup, members)
}

func (s *CreateClusterInput) SetAllowVersionUpgrade(v bool) *CreateClusterInput {
	s.AllowVersionUpgrade = &v
	return s
}

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


Question:
Choose and load the desired number of questions.
@return array of short answer questions.

public function load_questions() {
        if ($this->choose > count($this->availablequestions)) {
            throw new coding_exception('notenoughtshortanswerquestions');
        }

        $questionids = draw_rand_array($this->availablequestions, $this->choose);
        $questions = array();
        foreach ($questionids as $questionid) {
            $questions[] = question_bank::load_question($questionid);
        }
        return $questions;
    }

def options
      {id: self.survey_id, surveyID: self.survey_id, responseID: self.response_id,
       resultMode: self.result_mode, startDate: self.start_date, userID: self.user_id,
       endDate: self.end_date, startingResponseCounter: self.starting_response_counter,
       emailGroupID: self.email_group_id, templateID: self.template_id}.compact.to_json
    end

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


Question: // SetGlobal sets the git config value for the key in the global config

func (c *Configuration) SetGlobal(key, val string) (string, error) {
	return c.gitConfigWrite("--global", "--replace-all", key, val)
}

func (s *settingsService) GetSettings() Settings {
	s.settingsMutex.Lock()

	settingsCopy := s.settings

	if s.settings.Networks != nil {
		settingsCopy.Networks = make(map[string]Network)
	}

	for networkName, network := range s.settings.Networks {
		settingsCopy.Networks[networkName] = network
	}
	s.settingsMutex.Unlock()

	for networkName, network := range settingsCopy.Networks {
		if !network.IsDHCP() {
			continue
		}

		resolvedNetwork, err := s.resolveNetwork(network)
		if err != nil {
			break
		}

		settingsCopy.Networks[networkName] = resolvedNetwork
	}
	return settingsCopy
}

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


Question: return the CfInfo for the column family

protected CfInfo getCfInfo(Cassandra.Client client)
            throws InvalidRequestException,
                   UnavailableException,
                   TimedOutException,
                   SchemaDisagreementException,
                   TException,
                   NotFoundException,
                   org.apache.cassandra.exceptions.InvalidRequestException,
                   ConfigurationException,
                   IOException
    {
        // get CF meta data
        String query = "SELECT type," +
                       "       comparator," +
                       "       subcomparator," +
                       "       default_validator," +
                       "       key_validator," +
                       "       key_aliases " +
                       "FROM system.schema_columnfamilies " +
                       "WHERE keyspace_name = '%s' " +
                       "  AND columnfamily_name = '%s' ";

        CqlResult result = client.execute_cql3_query(
                                ByteBufferUtil.bytes(String.format(query, keyspace, column_family)),
                                Compression.NONE,
                                ConsistencyLevel.ONE);

        if (result == null || result.rows == null || result.rows.isEmpty())
            return null;

        Iterator<CqlRow> iteraRow = result.rows.iterator();
        CfDef cfDef = new CfDef();
        cfDef.keyspace = keyspace;
        cfDef.name = column_family;
        boolean cql3Table = false;
        if (iteraRow.hasNext())
        {
            CqlRow cqlRow = iteraRow.next();

            cfDef.column_type = ByteBufferUtil.string(cqlRow.columns.get(0).value);
            cfDef.comparator_type = ByteBufferUtil.string(cqlRow.columns.get(1).value);
            ByteBuffer subComparator = cqlRow.columns.get(2).value;
            if (subComparator != null)
                cfDef.subcomparator_type = ByteBufferUtil.string(subComparator);
            cfDef.default_validation_class = ByteBufferUtil.string(cqlRow.columns.get(3).value);
            cfDef.key_validation_class = ByteBufferUtil.string(cqlRow.columns.get(4).value);
            String keyAliases = ByteBufferUtil.string(cqlRow.columns.get(5).value);
            if (FBUtilities.fromJsonList(keyAliases).size() > 0)
                cql3Table = true;
        }
        cfDef.column_metadata = getColumnMetadata(client);
        CfInfo cfInfo = new CfInfo();
        cfInfo.cfDef = cfDef;
        if (cql3Table && !(parseType(cfDef.comparator_type) instanceof AbstractCompositeType))
            cfInfo.compactCqlTable = true;
        if (cql3Table)
            cfInfo.cql3Table = true;;
        return cfInfo;
    }

protected function findFrontendGroups($record, $table)
    {
        if ($this->originalTca[$table]['ctrl']['enablecolumns']['fe_group']) {
            $frontendGroups = $record[$this->originalTca[$table]['ctrl']['enablecolumns']['fe_group']];

            if (empty($frontendGroups)) {
                // default = public access
                $frontendGroups = 0;
            } else {
                if ($this->request->getParameter('loggingEnabled')) {
                    $this->logger->log(
                        SolrLogManager::INFO,
                        'Access restriction found',
                        [
                            'groups' => $frontendGroups,
                            'record' => $record,
                            'record type' => $table,
                        ]
                    );
                }
            }

            $this->frontendGroups[] = $frontendGroups;
        }
    }

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


Question:
/*
// UpdatePrinter updates attributes associated with the printer p.
func (s *Server) UpdatePrinter(p *Printer, info *PrinterInfo) error {
}
*/
// Jobs returns a list of jobs waiting to be printed on the given printer.

func (s *Server) Jobs(p *Printer) ([]*Job, error) {
	var mr multipartRequest
	mr.init()
	mr.WriteField("printerid", p.ID)

	var resp jobsResponse
	err := jsonRPC(&s.auth, "POST", cloudprintURL+"/fetch", &mr, &resp)
	if err != nil {
		return nil, fmt.Errorf("Jobs: %v", err)
	}

	var list []*Job
	for _, desc := range resp.Jobs {
		list = append(list, desc.Job())
	}
	return list, nil
}

def _PrintExtractionStatusUpdateLinear(self, processing_status):

    for worker_status in processing_status.workers_status:
      status_line = (
          '{0:s} (PID: {1:d}) - events produced: {2:d} - file: {3:s} '
          '- running: {4!s}\n').format(
              worker_status.identifier, worker_status.pid,
              worker_status.number_of_produced_events,
              worker_status.display_name,
              worker_status.status not in definitions.ERROR_STATUS_INDICATORS)
      self._output_writer.Write(status_line)

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


Question: // RemoteConnection fields validated separately -- this is for keystone-specific validation

func ValidateKeystoneIdentityProvider(provider *configapi.KeystonePasswordIdentityProvider, identityProvider configapi.IdentityProvider, fldPath *field.Path) common.ValidationResults {
	validationResults := common.ValidationResults{}
	validationResults.AddErrors(ValidateRemoteConnectionInfo(provider.RemoteConnectionInfo, fldPath)...)

	providerURL, err := url.Parse(provider.RemoteConnectionInfo.URL)
	if err == nil {
		if providerURL.Scheme != "https" {
			validationResults.AddWarnings(field.Invalid(field.NewPath("url"), provider.RemoteConnectionInfo.URL, "Auth URL should be secure and start with https"))
		}
	}
	if len(provider.DomainName) == 0 {
		validationResults.AddErrors(field.Required(field.NewPath("domainName"), ""))
	}

	return validationResults
}

def register(self, key, **kwargs):
        """"""
        dimensions = dict((k, str(v)) for k, v in kwargs.items())
        composite_key = self._composite_name(key, dimensions)
        self._metadata[composite_key] = {
            'metric': key,
            'dimensions': dimensions
        }
        return composite_key

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


Question: // IncInt64 increases the value for key k in kv store by step.

func IncInt64(rm RetrieverMutator, k Key, step int64) (int64, error) {
	val, err := rm.Get(k)
	if IsErrNotFound(err) {
		err = rm.Set(k, []byte(strconv.FormatInt(step, 10)))
		if err != nil {
			return 0, err
		}
		return step, nil
	}
	if err != nil {
		return 0, err
	}

	intVal, err := strconv.ParseInt(string(val), 10, 0)
	if err != nil {
		return 0, errors.Trace(err)
	}

	intVal += step
	err = rm.Set(k, []byte(strconv.FormatInt(intVal, 10)))
	if err != nil {
		return 0, err
	}
	return intVal, nil
}

func (that *JSONNode) DebugProspect(indentlevel int, indentchar string) {
	switch that.t {
	case TypeValue:
		that.debugProspectValue(indentlevel, indentchar)
	case TypeMap:
		that.debugProspectMap(indentlevel, indentchar)
	case TypeArray:
		that.debugProspectArray(indentlevel, indentchar)
	case TypeUndefined:
		printfindent(indentlevel, indentchar, "Is of Type: TypeUndefined\n")
	}
}

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


Question: // LineWidth returns the max width of all the lines in a cell

func (c *Cell) LineWidth() uint {
	width := 0
	for _, s := range strings.Split(c.String(), "\n") {
		w := runewidth.StringWidth(s)
		if w > width {
			width = w
		}
	}
	return uint(width)
}

func (writer *baseFileWriter) SetRotateLines(rotateLines int) {
	writer.lock.Lock()
	defer writer.lock.Unlock()
	if rotateLines > 0 {
		writer.lineRotated = true
		writer.rotateLines = rotateLines
	} else {
		writer.lineRotated = false
	}
}

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


Question:
Initializes the current controls layout rect.
This will be executed by the layout managers to determine the
default minWidth/minHeight etc.

@method initLayoutRect
@return {Object} Layout rect instance.

function () {
        var self = this, settings = self.settings, borderBox, layoutRect;
        var elm = self.getEl(), width, height, minWidth, minHeight, autoResize;
        var startMinWidth, startMinHeight, initialSize;

        // Measure the current element
        borderBox = self.borderBox = self.borderBox || BoxUtils.measureBox(elm, 'border');
        self.paddingBox = self.paddingBox || BoxUtils.measureBox(elm, 'padding');
        self.marginBox = self.marginBox || BoxUtils.measureBox(elm, 'margin');
        initialSize = DomUtils.getSize(elm);

        // Setup minWidth/minHeight and width/height
        startMinWidth = settings.minWidth;
        startMinHeight = settings.minHeight;
        minWidth = startMinWidth || initialSize.width;
        minHeight = startMinHeight || initialSize.height;
        width = settings.width;
        height = settings.height;
        autoResize = settings.autoResize;
        autoResize = typeof autoResize != "undefined" ? autoResize : !width && !height;

        width = width || minWidth;
        height = height || minHeight;

        var deltaW = borderBox.left + borderBox.right;
        var deltaH = borderBox.top + borderBox.bottom;

        var maxW = settings.maxWidth || 0xFFFF;
        var maxH = settings.maxHeight || 0xFFFF;

        // Setup initial layout rect
        self._layoutRect = layoutRect = {
          x: settings.x || 0,
          y: settings.y || 0,
          w: width,
          h: height,
          deltaW: deltaW,
          deltaH: deltaH,
          contentW: width - deltaW,
          contentH: height - deltaH,
          innerW: width - deltaW,
          innerH: height - deltaH,
          startMinWidth: startMinWidth || 0,
          startMinHeight: startMinHeight || 0,
          minW: Math.min(minWidth, maxW),
          minH: Math.min(minHeight, maxH),
          maxW: maxW,
          maxH: maxH,
          autoResize: autoResize,
          scrollW: 0
        };

        self._lastLayoutRect = {};

        return layoutRect;
      }

def _create_image(self, matrix, width, height, pad):

        image = Image.new("RGB", (width + (pad * 2),
                                  height + (pad * 2)), self.bg_colour)
        image_draw = ImageDraw.Draw(image)

        # Calculate the block width and height.
        block_width = float(width) / self.cols
        block_height = float(height) / self.rows

        # Loop through blocks in matrix, draw rectangles.
        for row, cols in enumerate(matrix):
            for col, cell in enumerate(cols):
                if cell:
                    image_draw.rectangle((
                        pad + col * block_width,  # x1
                        pad + row * block_height,  # y1
                        pad + (col + 1) * block_width - 1,  # x2
                        pad + (row + 1) * block_height - 1  # y2
                    ), fill=self.fg_colour)

        stream = BytesIO()
        image.save(stream, format="png", optimize=True)
        # return the image byte data
        return stream.getvalue()

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


Question:
Execute the console command.

@return mixed

public function fire()
    {
        try {

            // Potion config
            if ($this->config === false) {
                throw new \Exception('Invalid potion config, please run "artisan vendor:publish" in your project root to public the potion config file.');
            }

            // Clean up paths
            $this->config['assets_path'] = rtrim($this->config['assets_path'], '/');
            $this->config['assets_path'] = rtrim($this->config['assets_path'], '\\');

            // Make sure assets direction exists
            if (!is_dir($this->config['assets_path'])) {
                throw new \Exception("Invalid assets folder: {$this->config['assets_path']}");
            }

            // Confirm that the user wants to clear
            $force = $this->input->getOption('force');
            if (empty($force)) {
                $this->info("This will clear all assets in: {$this->config['assets_path']}");
                $confirmed = $this->confirm('Do you really wish to run this command? [y/N]');
                if (!$confirmed) {
                    $this->comment('Command Cancelled!');
                    return false;
                }
            }

            // Delete all files, do not delete recursively as that is dangerous
            $files = glob($this->config['assets_path'] . DIRECTORY_SEPARATOR . '*');
            foreach ($files as $file) {

                // -- Sanity check
                if (is_file($file)) {

                    // -- -- Echo
                    $this->info("Deleting assets: {$file}");

                    // -- -- Delete
                    unlink($file);
                }
            }

            // Clear cache
            Cache::forget('potion_assets');

        }
        catch (\Exception $e) {

            // Echo
            $this->error($e->getMessage());

        }
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question:
Internal update mechanism of Skills on Group

@param Group $model
@param mixed $data

protected function doUpdateSkills(Group $model, $data) {
		// remove all relationships before
		SkillGroupQuery::create()->filterByGroup($model)->delete();

		// add them
		$errors = [];
		foreach ($data as $entry) {
			if (!isset($entry['id'])) {
				$errors[] = 'Missing id for Skill';
			} else {
				$related = SkillQuery::create()->findOneById($entry['id']);
				$model->addSkill($related);
			}
		}

		if (count($errors) > 0) {
			throw new ErrorsException($errors);
		}
	}

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

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

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


Question:
Get the raw email data sent by this object.

@param  boolean $stream  If true, return a stream resource, otherwise
a string is returned.

@return stream|string  The raw email data.
@since 2.4.0

public function getRaw($stream = true)
    {
        if ($stream) {
            $hdr = new Horde_Stream();
            $hdr->add($this->_headers->toString(), true);
            return Horde_Stream_Wrapper_Combine::getStream(
                array($hdr->stream,
                      $this->getBasePart()->toString(
                        array('stream' => true, 'encode' => Horde_Mime_Part::ENCODE_7BIT | Horde_Mime_Part::ENCODE_8BIT | Horde_Mime_Part::ENCODE_BINARY))
                )
            );
        }

        return $this->_headers->toString() . $this->getBasePart()->toString();
    }

public Observable<ServiceResponse<InputStream>> downloadQueryLogsWithServiceResponseAsync(UUID appId) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.downloadQueryLogs(appId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<InputStream>>>() {
                @Override
                public Observable<ServiceResponse<InputStream>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<InputStream> clientResponse = downloadQueryLogsDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
Indica si no se trata de un segmento vacio
Consideramos segmentos vacios a tambien al directorio actual (.)

@param string $piece

@return bool

private function isNotEmpty(string $piece): bool
    {

        $isEmpty = is_blank($piece);
        $isDot = ('.' === $piece);

        return !($isEmpty || $isDot);
    }

private static function parseRegion($code)
    {
        $lang = substr($code, 0, 2);
        $reg =  strtoupper(substr($code, 3, 2));
        $needle = "{$lang}-{$reg}";
        foreach (self::codes() as $code) {
            if ($code['code'] == $needle) {
                return [$reg, $code['description']];
            }
        }

        throw new UnknownLanguageCodeException(
            "The region code '{$code}'' is unknown."
        );
    }

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


Question:
Returns a printable name for this anonymous instance.

@param string $instanceName
@return string

private function getAnonymousInstanceName($instanceName) {
        // Let's find a name for this anonymous instance
        $anonInstanceName = $instanceName;
        // Let's find where the anonymous instance is used.
        do {
            $parents = $this->moufManager->getOwnerComponents($anonInstanceName);
            // There should be only one parent, since this is an anonymous instance
            $anonInstanceName = current($parents);
        } while ($this->moufManager->getInstanceDescriptor($anonInstanceName)->isAnonymous());

        return "Anonymous (parent: ".$anonInstanceName.")";
    }

func (_class ClusterClass) GetNetwork(sessionID SessionRef, self ClusterRef) (_retval NetworkRef, _err error) {
	_method := "Cluster.get_network"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertClusterRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertNetworkRefToGo(_method + " -> ", _result.Value)
	return
}

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


Question:
Tests if an endpoint name (not path) belongs to this Api.  Takes
        in to account the Blueprint name part of the endpoint name.

        :param endpoint: The name of the endpoint being checked
        :return: bool

def owns_endpoint(self, endpoint):

        if self.blueprint:
            if endpoint.startswith(self.blueprint.name):
                endpoint = endpoint.split(self.blueprint.name + '.', 1)[-1]
            else:
                return False
        return endpoint in self.endpoints

func (g *Gnostic) readOpenAPIBinary(data []byte) (message proto.Message, err error) {
	// try to read an OpenAPI v3 document
	documentV3 := &openapi_v3.Document{}
	err = proto.Unmarshal(data, documentV3)
	if err == nil && strings.HasPrefix(documentV3.Openapi, "3.0") {
		g.sourceFormat = SourceFormatOpenAPI3
		return documentV3, nil
	}
	// if that failed, try to read an OpenAPI v2 document
	documentV2 := &openapi_v2.Document{}
	err = proto.Unmarshal(data, documentV2)
	if err == nil && strings.HasPrefix(documentV2.Swagger, "2.0") {
		g.sourceFormat = SourceFormatOpenAPI2
		return documentV2, nil
	}
	// if that failed, try to read a Discovery Format document
	discoveryDocument := &discovery_v1.Document{}
	err = proto.Unmarshal(data, discoveryDocument)
	if err == nil { // && strings.HasPrefix(documentV2.Swagger, "2.0") {
		g.sourceFormat = SourceFormatDiscovery
		return discoveryDocument, nil
	}
	return nil, err
}

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


Question:
Causes the current thread to block for the specified number of
milliseconds. This exists primarily to work around the fact that on
Linux, {@link Thread#sleep(long)} is only accurate to around 12ms which
is wholly unacceptable.

public static void sleep (int millis)
    {
        if (RunAnywhere.isLinux() && isLoaded()) {
            nativeSleep(millis);
        } else {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ie) {
                log.info("Thread.sleep(" + millis + ") interrupted.");
            }
        }
    }

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,
        )

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


Question:
Convert string data into the database format.

@param mixed $value The value to convert.
@param \Cake\Database\Driver $driver The driver instance to convert with.
@return string|null

public function toDatabase($value, Driver $driver)
    {
        if ($value === null || is_string($value)) {
            return $value;
        }

        if (is_object($value) && method_exists($value, '__toString')) {
            return $value->__toString();
        }

        if (is_scalar($value)) {
            return (string)$value;
        }

        throw new InvalidArgumentException(sprintf(
            'Cannot convert value of type `%s` to string',
            getTypeName($value)
        ));
    }

func builtinChar(args []types.Datum, ctx context.Context) (d types.Datum, err error) {
	// The kinds of args are int or string, and the last one represents charset.
	var resultStr string
	var intSlice = make([]int64, 0, len(args)-1)

	for _, datum := range args[:len(args)-1] {
		switch datum.Kind() {
		case types.KindNull:
			continue
		case types.KindString:
			i, err := datum.ToInt64(ctx.GetSessionVars().StmtCtx)
			if err != nil {
				d.SetString(resultStr)
				return d, nil
			}
			intSlice = append(intSlice, i)
		case types.KindInt64, types.KindUint64, types.KindMysqlHex, types.KindFloat32, types.KindFloat64, types.KindMysqlDecimal:
			x, err := datum.Cast(ctx.GetSessionVars().StmtCtx, types.NewFieldType(mysql.TypeLonglong))
			if err != nil {
				return d, errors.Trace(err)
			}
			intSlice = append(intSlice, x.GetInt64())
		default:
			return d, errors.Errorf("Char invalid args, need int or string but get %T", args[0].GetValue())
		}
	}

	resultStr = string(convertInt64ToBytes(intSlice))

	// The last argument represents the charset name after "using".
	// If it is nil, the default charset utf8 is used.
	argCharset := args[len(args)-1]
	if !argCharset.IsNull() {
		char, err := argCharset.ToString()
		if err != nil {
			return d, errors.Trace(err)
		}

		if strings.ToLower(char) == "ascii" || strings.HasPrefix(strings.ToLower(char), "utf8") {
			d.SetString(resultStr)
			return d, nil
		}

		encoding, _ := charset.Lookup(char)
		if encoding == nil {
			return d, errors.Errorf("unknown encoding: %s", char)
		}

		resultStr, _, err = transform.String(encoding.NewDecoder(), resultStr)
		if err != nil {
			log.Printf("Convert %s to %s with error: %v", resultStr, char, err)
			return d, errors.Trace(err)
		}
	}
	d.SetString(resultStr)
	return d, nil
}

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


Question: Find an image, tolerant of different file extensions.

def _find_image_ext(path, number=None):
    """"""
    if number is not None:
        path = path.format(number)
    path = os.path.splitext(path)[0]
    for ext in _KNOWN_IMG_EXTS:
        this_path = '%s.%s' % (path, ext)
        if os.path.isfile(this_path):
            break
    else:
        ext = 'png'
    return ('%s.%s' % (path, ext), ext)

public static function getExtension($mimeType)
    {
        if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes, true)) {
            $data = Arrays::setKeysAsValues(self::$mimeTypes, false);

            return $data[$mimeType];
        }

        return '';
    }

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


Question:
判断所引类型是否存在
@param indiceName
@param type
@return
@throws ElasticSearchException

public boolean existIndiceType(String indiceName,String type) throws ElasticSearchException{
		try {
			executeHttp(new StringBuilder(indiceName).append("/_mapping/").append(type).toString(), ClientInterface.HTTP_HEAD);
			return true;
		}
		catch(ElasticSearchException e){
			return ResultUtil.hand404HttpRuntimeException(e,boolean.class,ResultUtil.OPERTYPE_existIndiceType);
		}
	}

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
Override a class namespace
@param string $class
@return string

protected static function override(&$class)
    {
        $map = gplcart_config_get(GC_FILE_CONFIG_COMPILED_OVERRIDE);

        if (isset($map[$class])) {
            $override = end($map[$class]);
            $class = $override;
        }

        return $class;
    }

public function setReplacements($replacements)
    {
        if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) {
            $this->replacements = (array) $replacements;
        } else {
            $this->replacements = $replacements;
        }
    }

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


Question: // Ubiquitous chains are the chains with highest platform coverage and break ties with the optimal strategy.

func ubiquitousChains(chains [][]*x509.Certificate) [][]*x509.Certificate {
	// Filter out chains with highest cross platform ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.ComparePlatformUbiquity)
	// Prefer that all intermediates are SHA-2 certs if the leaf is a SHA-2 cert, in order to improve ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.CompareSHA2Homogeneity)
	// Filter shortest chains
	chains = ubiquity.Filter(chains, ubiquity.CompareChainLength)
	// Filter chains with highest signature hash ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.CompareChainHashUbiquity)
	// Filter chains with highest keyAlgo ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.CompareChainKeyAlgoUbiquity)
	// Filter chains with intermediates that last longer.
	chains = ubiquity.Filter(chains, ubiquity.CompareExpiryUbiquity)
	// Use the optimal strategy as final tie breaker.
	return optimalChains(chains)
}

@Pure
	public BusLine getBusLine(String name, Comparator<String> nameComparator) {
		if (name == null) {
			return null;
		}
		final Comparator<String> cmp = nameComparator == null ? BusNetworkUtilities.NAME_COMPARATOR : nameComparator;
		for (final BusLine busLine : this.busLines) {
			if (cmp.compare(name, busLine.getName()) == 0) {
				return busLine;
			}
		}
		return null;
	}

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


Question:
// mustBe checks a value against a kind, panicing with a reflect.ValueError
// if the kind isn't that which is required.

func mustBe(v kinder, expected reflect.Kind) {
	if k := v.Kind(); k != expected {
		panic(&reflect.ValueError{Method: methodName(), Kind: k})
	}
}

def create(self, comment, mentions=()):

        data = {
            "app": self.app_id,
            "record": self.record_id,
            "comment": {
                "text": comment,
            }
        }

        if len(mentions) > 0:
            _mentions = []
            for m in mentions:
                if isinstance(m, (list, tuple)):
                    if len(m) == 2:
                        _mentions.append({
                            "code": m[0],
                            "type": m[1]
                        })
                    else:
                        raise Exception("mention have to have code and target type. ex.[('user_1', 'USER')]")
                elif isinstance(m, Mention):
                    _mentions.append(m.serialize())

            data["comment"]["mentions"] = _mentions

        resp = self._request("POST", self._url, data)
        r = cr.CreateCommentResult(resp)
        return r

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