Question:
/**
 * install collector
 *
 *
 * @param collectorId
 * @param osAndArch
 * @param collectorVersion
 * @param token
 * @param monitorOthers
 * @param collectorSize
 * @param useEA
 * @return **os.File
 */

func (a DefaultApi) InstallCollector(collectorId int32, osAndArch string, collectorVersion int32, token string, monitorOthers bool, collectorSize string, useEA bool) (**os.File, *APIResponse, error) {

	var localVarHttpMethod = strings.ToUpper("Get")
	// create path and map variables
	localVarPath := a.Configuration.BasePath + "/setting/collectors/{collectorId}/installers/{osAndArch}"
	localVarPath = strings.Replace(localVarPath, "{"+"collectorId"+"}", fmt.Sprintf("%v", collectorId), -1)
	localVarPath = strings.Replace(localVarPath, "{"+"osAndArch"+"}", fmt.Sprintf("%v", osAndArch), -1)
	localResourcePath := "/setting/collectors/{collectorId}/installers/{osAndArch}"
	localResourcePath = strings.Replace("/setting/collectors/{collectorId}/installers/{osAndArch}", "{"+"collectorId"+"}", fmt.Sprintf("%v", collectorId), -1)
	localResourcePath = strings.Replace("/setting/collectors/{collectorId}/installers/{osAndArch}", "{"+"osAndArch"+"}", fmt.Sprintf("%v", osAndArch), -1)

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := make(map[string]string)
	var localVarPostBody interface{}
	var localVarFileName string
	var localVarFileBytes []byte
	// add default headers if any
	for key := range a.Configuration.DefaultHeader {
		localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
	}
	localVarQueryParams.Add("collectorVersion", a.Configuration.APIClient.ParameterToString(collectorVersion, ""))
	localVarQueryParams.Add("token", a.Configuration.APIClient.ParameterToString(token, ""))
	localVarQueryParams.Add("monitorOthers", a.Configuration.APIClient.ParameterToString(monitorOthers, ""))
	localVarQueryParams.Add("collectorSize", a.Configuration.APIClient.ParameterToString(collectorSize, ""))
	localVarQueryParams.Add("useEA", a.Configuration.APIClient.ParameterToString(useEA, ""))

	// to determine the Content-Type header
	localVarHttpContentTypes := []string{}

	// set Content-Type header
	localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
	if localVarHttpContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHttpContentType
	}
	// to determine the Accept header
	localVarHttpHeaderAccepts := []string{
		"application/json",
	}

	// set Accept header
	localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
	if localVarHttpHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
	}
	// authentication '(LMv1)' required
	// set key with prefix in header
	localVarHeaderParams["Authorization"] = a.Configuration.GetAPIKeyWithPrefix("Authorization", localResourcePath, "Get", localVarPostBody)
	var successPayload = new(*os.File)
	localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)

	var localVarURL, _ = url.Parse(localVarPath)
	localVarURL.RawQuery = localVarQueryParams.Encode()
	var localVarAPIResponse = &APIResponse{Operation: "InstallCollector", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
	if localVarHttpResponse != nil {
		localVarAPIResponse.Response = localVarHttpResponse.RawResponse
		localVarAPIResponse.Payload = localVarHttpResponse.Body()
	}

	if err != nil {
		return successPayload, localVarAPIResponse, err
	}
	err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
	return successPayload, localVarAPIResponse, err
}

public Metadata readNextMetadata() throws IOException {
        Metadata metadata = null;

        boolean isLast = (bitStream.readRawUInt(Metadata.STREAM_METADATA_IS_LAST_LEN) != 0);
        int type = bitStream.readRawUInt(Metadata.STREAM_METADATA_TYPE_LEN);
        int length = bitStream.readRawUInt(Metadata.STREAM_METADATA_LENGTH_LEN);

        if (type == Metadata.METADATA_TYPE_STREAMINFO) {
        	metadata = streamInfo = new StreamInfo(bitStream, length, isLast);
            pcmProcessors.processStreamInfo((StreamInfo)metadata);
        } else if (type == Metadata.METADATA_TYPE_SEEKTABLE) {
        	metadata = seekTable = new SeekTable(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_APPLICATION) {
            metadata = new Application(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_PADDING) {
            metadata = new Padding(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_VORBIS_COMMENT) {
            metadata = vorbisComment = new VorbisComment(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_CUESHEET) {
	    metadata = new CueSheet(bitStream, length, isLast);
	} else if (type == Metadata.METADATA_TYPE_PICTURE) {
	    metadata = new Picture(bitStream, length, isLast);
        } else {
            metadata = new Unknown(bitStream, length, isLast);
        }
        frameListeners.processMetadata(metadata);
        //if (isLast) state = DECODER_SEARCH_FOR_FRAME_SYNC;
        return metadata;
    }

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


Question:
Set Fieldset Legend name.

<code>
$fieldset->legend('User Information');
</code>

@param  string $name

@return string

public function legend($name = null)
    {
        if (!is_null($name)) {
            $this->legend = $name;
        }

        return $this->legend;
    }

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

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


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

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

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

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

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

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

	parser.simple_key_allowed = false

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

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


Question: strip a BED file down to its three necessary columns: chrom start end

def minimize(bed_file):

    if not bed_file:
        return bed_file
    else:
        sorted_bed = bt.BedTool(bed_file).cut(range(3)).sort()
        if not sorted_bed.fn.endswith(".bed"):
            return sorted_bed.moveto(sorted_bed.fn + ".bed")
        else:
            return sorted_bed

func (c *CSV) NewReader(res *exchange.Resource, context *qor.Context) (exchange.Rows, error) {
	var rows = Rows{CSV: c, Resource: res}

	readCloser, err := c.getReader()
	if err == nil {
		defer readCloser.Close()
		reader := csv.NewReader(readCloser)
		reader.TrimLeadingSpace = true

		rows.records, err = reader.ReadAll()

		if c.config.TrimSpace {
			for _, rows := range rows.records {
				for i, record := range rows {
					rows[i] = strings.TrimSpace(record)
				}
			}
		}

		rows.total = len(rows.records) - 1
		if res.Config.WithoutHeader {
			rows.total++
		}
	}

	return &rows, err
}

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


Question: Restart an aurora job

@Override
  public boolean restart(Integer containerId) {
    List<String> auroraCmd = new ArrayList<>(Arrays.asList("aurora", "job", "restart"));
    if (containerId != null) {
      auroraCmd.add(String.format("%s/%d", jobSpec, containerId));
    } else {
      auroraCmd.add(jobSpec);
    }

    appendAuroraCommandOptions(auroraCmd, isVerbose);

    return runProcess(auroraCmd);
  }

function DisplayOTron(model) {
    if (!(this instanceof DisplayOTron)) {
        return new DisplayOTron(model);
    }

    this.model = model;

    this.pythonProcess = null;

    this.reset();

    events.EventEmitter.call(this);
}

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


Question:
Get IMAP resource stream.

@throws InvalidResourceException

@return resource

public function getStream()
    {
        if (false === \is_resource($this->resource) || 'imap' !== \get_resource_type($this->resource)) {
            throw new InvalidResourceException('Supplied resource is not a valid imap resource');
        }

        $this->initMailbox();

        return $this->resource;
    }

public MimeMessage getMessage(Session session) {

		Assert.notNull(emails, "No email address given!");

		Map<String, String> recipients = emails.get(Message.RecipientType.TO);
		Assert.isTrue(recipients != null && recipients.size() > 0, "Missing to email address(es)!");

		boolean found = false;
		for (String email : recipients.keySet()) {
			if (!excluded(email)) { // at least one address is not excluded
				found = true;
				break;
			}
		}

		Assert.isTrue(found, "All to email address(es) are excluded!");

		if (StringUtils.isNullOrEmptyTrimmed(fromName)) {
			fromName = fromEmail;
		}

		Assert.notNullOrEmptyTrimmed(fromEmail, "Missing from email address!");
		Assert.notNullOrEmptyTrimmed(subject, "Missing email subject!");

		Assert.isTrue(!StringUtils.isNullOrEmptyTrimmed(content) || !StringUtils.isNullOrEmptyTrimmed(htmlContent), "Missing email content!");

		subject = subject.trim();
		content = content != null ? content.trim() : null;
		htmlContent = htmlContent != null ? htmlContent.trim() : null;

		log.info("Sending from: " + fromEmail + " (" + fromName + ")");

		MimeMessage msg = new MimeMessage(session);

		// FROM:
		try {
			msg.setFrom(new InternetAddress(fromEmail, fromName, UTF_8));

			// TO:
			addRecipients(Message.RecipientType.TO, msg);
			// CC:
			addRecipients(Message.RecipientType.CC, msg);
			// BCC:
			addRecipients(Message.RecipientType.BCC, msg);

			//msg.setSubject(subject, UTF_8);
			msg.setSubject(MimeUtility.encodeText(subject, UTF_8, "Q"));

			// add headers
			if (headers != null && headers.size() > 0) {
				for (String name : headers.keySet()) {
					msg.addHeader(name, headers.get(name));
				}
			}

			try {
				// simple message .. no attachment and only content or html content
				if ((attachments == null || attachments.size() == 0) &&
				    ((htmlContent == null && content != null) ||
				     (htmlContent != null && content == null))) {

					if (StringUtils.isNullOrEmptyTrimmed(content)) {
						msg.addHeader("Content-Type", "text/html");
						msg.setContent(htmlContent, "text/html; charset=" + UTF_8);
					} else {
						msg.setContent(content, "text/plain; charset=" + UTF_8);
					}
				}
				// Compose multipart message
				else {
					// must be in correct order from lower fidelity to higher
					Multipart multipart = new MimeMultipart();

					if (!StringUtils.isNullOrEmptyTrimmed(content)) {
						MimeBodyPart contentPart = new MimeBodyPart();
						contentPart.setContent(content, "text/plain; charset=" + UTF_8);
						multipart.addBodyPart(contentPart);
					}

					if (!StringUtils.isNullOrEmptyTrimmed(htmlContent)) {
						MimeBodyPart htmlPart = new MimeBodyPart();
						htmlPart.setContent(htmlContent, "text/html; charset=" + UTF_8);
						multipart.addBodyPart(htmlPart);
					}

					if (attachments != null && attachments.size() > 0) {
						for (MailAttachment attachment : attachments) {

							// add attachment
							MimeBodyPart part = new MimeBodyPart();
							if (attachment.fileName != null) {
								part.setFileName(attachment.fileName);
							}
							DataSource src = new ByteArrayDataSource(attachment.content, attachment.type);
							part.setDataHandler(new DataHandler(src));
							multipart.addBodyPart(part);
						}
					}

					msg.setContent(multipart);
				}

				// if save is not called mime part headers are not updated
				msg.saveChanges();
				// see: http://stackoverflow.com/questions/5028670/how-to-set-mimebodypart-contenttype-to-text-html
			}
			catch (Exception e) {
				log.error("Failed to add attachment to mail message: ", e);
				throw new IllegalArgumentException(e.getMessage(), e);
			}

		}
		catch (MessagingException | UnsupportedEncodingException e) {
			log.error("Mail massage build failed!", e);
			throw new IllegalArgumentException(e.getMessage(), e);
		}

		return msg;
	}

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


Question:
Persist profile

This method is called from the controller_front_send_response_after event

@author Fabrizio Branca
@since 2014-02-01

@param Varien_Event_Observer $event

public function persistProfile(Varien_Event_Observer $event) {
        if (!method_exists('Varien_Profiler', 'isEnabled')) {
            Mage::log('Looks like the wrong Profiler class is being loaded at this point.');
            return;
        }
        if (Varien_Profiler::isEnabled() && Varien_Profiler::checkThresholds()) {
            $run = Mage::getModel('aoe_profiler/run'); /* @var $run Aoe_Profiler_Model_Run */
            $run->loadStackLogFromProfiler();
            $run->populateMetadata();
            try {
                $run->save();
            } catch (Exception $e) {
                Mage::log('Error while saving Aoe_Profiler data: '. $e->getMessage());
            }
        }
    }

public function jsonToInterface( $data )
    {
        $parser = new \PHPFHIRGenerated\PHPFHIRResponseParser();
        $fhirModel = $parser->parse( $data );
        if ( is_a( $fhirModel, 'FHIRAuditEvent' ) ) {
            return $this->modelToInterface( $fhirModel );
        } else {
            // Error, the Resource does not match, expecting a Patient,
            // // but got something else.
        }
    }

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


Question: // SetShutdown sets the Shutdown field's value.

func (s *LifecycleEventConfiguration) SetShutdown(v *ShutdownEventConfiguration) *LifecycleEventConfiguration {
	s.Shutdown = v
	return s
}

public void setOnunload(java.lang.String onunload) {
        getStateHelper().put(PropertyKeys.onunload, onunload);
        handleAttribute("onunload", onunload);
    }

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


Question: // GetAll returns all the plugins for the specified implementation

func GetAll(imp string) ([]*Plugin, error) {
	pluginNames, err := Scan()
	if err != nil {
		return nil, err
	}

	type plLoad struct {
		pl  *Plugin
		err error
	}

	chPl := make(chan *plLoad, len(pluginNames))
	var wg sync.WaitGroup
	for _, name := range pluginNames {
		storage.Lock()
		pl, ok := storage.plugins[name]
		storage.Unlock()
		if ok {
			chPl <- &plLoad{pl, nil}
			continue
		}

		wg.Add(1)
		go func(name string) {
			defer wg.Done()
			pl, err := loadWithRetry(name, false)
			chPl <- &plLoad{pl, err}
		}(name)
	}

	wg.Wait()
	close(chPl)

	var out []*Plugin
	for pl := range chPl {
		if pl.err != nil {
			logrus.Error(pl.err)
			continue
		}
		if err := pl.pl.waitActive(); err == nil && pl.pl.implements(imp) {
			out = append(out, pl.pl)
		}
	}
	return out, nil
}

def show_fabric_trunk_info_input_rbridge_id_or_all_all_all(self, **kwargs):

        config = ET.Element("config")
        show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
        config = show_fabric_trunk_info
        input = ET.SubElement(show_fabric_trunk_info, "input")
        rbridge_id_or_all = ET.SubElement(input, "rbridge-id-or-all")
        all = ET.SubElement(rbridge_id_or_all, "all")
        all = ET.SubElement(all, "all")

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

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


Question:
Maps an eagerly loaded collection from a nested data set.

@param string $property The property that gets a nested eager relationship.
@return MapsProperty    The resulting property mapping.
@throws InvalidMapperConfiguration

private function manyNestedInThe(string $property): MapsProperty
    {
        if (null !== $this->container && !class_exists($this->container)) {
            throw NoSuchClass::couldNotLoadCollection($this->container);
        }
        return $this->addConstraintTo(HasManyNested::inPropertyWithDifferentKey(
            $property,
            $this->keyOr($property),
            $this->container(),
            $this->hydrator()
        ));
    }

public void marshall(ListObjectParentPathsRequest listObjectParentPathsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listObjectParentPathsRequest.getDirectoryArn(), DIRECTORYARN_BINDING);
            protocolMarshaller.marshall(listObjectParentPathsRequest.getObjectReference(), OBJECTREFERENCE_BINDING);
            protocolMarshaller.marshall(listObjectParentPathsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(listObjectParentPathsRequest.getMaxResults(), MAXRESULTS_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:
Convert mixed value fetch from database to array.

@param  \Illuminate\Support\Collection|\Illuminate\Contracts\Support\Arrayable|array  $data

@return array

protected function asArray($data = []): array
    {
        if ($data instanceof Collection) {
            $data = $data->all();
        } elseif ($data instanceof Arrayable) {
            $data = $data->toArray();
        }

        return $data;
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
Register a new component implementation.

@param interfaceClass the interface class implemented
@param implClass the implementation class
@param priority the priority level
@param weight the priority weight strictly less than 1000

protected void register(final Class<? extends Component<?>> interfaceClass, final Class<? extends Component<?>> implClass, final PriorityLevel priority, final int weight) {

        preloadClass(interfaceClass);

        getFacade().componentFactory().register(
                                                RegistrationItemBase.create()
                                                                    .interfaceClass(interfaceClass)
                                                                    .implClass(implClass)
                                                                    .priority(priority)
                                                                    .weight(weight));
    }

private FilterDescriptor createFilter(FilterType filterType, Map<String, FilterDescriptor> filters, ScannerContext context) {
        Store store = context.getStore();
        FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor(FilterDescriptor.class, filterType.getFilterName().getValue(), filters, store);
        setAsyncSupported(filterDescriptor, filterType.getAsyncSupported());
        for (DescriptionType descriptionType : filterType.getDescription()) {
            filterDescriptor.getDescriptions().add(XmlDescriptorHelper.createDescription(descriptionType, store));
        }
        for (DisplayNameType displayNameType : filterType.getDisplayName()) {
            filterDescriptor.getDisplayNames().add(XmlDescriptorHelper.createDisplayName(displayNameType, store));
        }
        FullyQualifiedClassType filterClass = filterType.getFilterClass();
        if (filterClass != null) {
            TypeResolver typeResolver = context.peek(TypeResolver.class);
            TypeCache.CachedType<TypeDescriptor> filterClassDescriptor = typeResolver.resolve(filterClass.getValue(), context);
            filterDescriptor.setType(filterClassDescriptor.getTypeDescriptor());
        }
        for (IconType iconType : filterType.getIcon()) {
            IconDescriptor iconDescriptor = XmlDescriptorHelper.createIcon(iconType, store);
            filterDescriptor.getIcons().add(iconDescriptor);
        }
        for (ParamValueType paramValueType : filterType.getInitParam()) {
            ParamValueDescriptor paramValueDescriptor = createParamValue(paramValueType, store);
            filterDescriptor.getInitParams().add(paramValueDescriptor);
        }
        return filterDescriptor;
    }

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


Question:
Draws a horizontal line.
@param canvas	the canvas to draw on
@param leftX		the left x coordinate
@param rightX	the right x coordindate
@param y			the y coordinate

public void drawLine(PdfContentByte canvas, float leftX, float rightX, float y) {
    	float w;
        if (getPercentage() < 0)
            w = -getPercentage();
        else
            w = (rightX - leftX) * getPercentage() / 100.0f;
        float s;
        switch (getAlignment()) {
            case Element.ALIGN_LEFT:
                s = 0;
                break;
            case Element.ALIGN_RIGHT:
                s = rightX - leftX - w;
                break;
            default:
                s = (rightX - leftX - w) / 2;
                break;
        }
        canvas.setLineWidth(getLineWidth());
        if (getLineColor() != null)
            canvas.setColorStroke(getLineColor());
        canvas.moveTo(s + leftX, y + offset);
        canvas.lineTo(s + w + leftX, y + offset);
        canvas.stroke();
    }

public function humaniceTrace(array $trace) {
        /* @var $html_helper HtmlHelper */
        $html_helper = $this->html;
        $list = [];
        foreach ($trace as $id_trace => $e) {
            $class = explode('\\', key_exists('class', $e) ? $e['class'] : '');
            $type = key_exists('type', $e) ? $e['type'] : '';
            $function = key_exists('function', $e) ? $e['function'] : '';
            $args = key_exists('args', $e) ? $e['args'] : [];
            $file = key_exists('file', $e) ? $e['file'] : [];
            $line = key_exists('line', $e) ? $e['line'] : [];

            $item = $class ? '' . end($class) . '' : '';
            $item .= $type ? '' . $type . '' : '';
            $item .= $function ? '' . $function . '' : '';
            $item .= $args ?
                    '(' .
                        $html_helper->link(count($args) . ' arg', [],
                            ['onclick' => 'var a=document.getElementById(\'args_' . $id_trace . '\');'
                                . ' if (a.style.display==\'block\') { a.style.display=\'none\' } else { a.style.display=\'block\' };'
                                . 'return false;']) .
                    ')' : '()';
            $item .= $file ? ' - ' . $file . '' : '';
            $item .= $line ? ' ' . $line . '' : '';
            $item .= $args ? '
' . @d($args) . '
' : '';

            $list[] = $item;
        }

        return $html_helper->nestedList($list, [
                'style' => 'font-family: arial; line-height:30px;',
                'reversed' => 'reversed'
            ], [], 'ordered');
    }

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


Question:
Determines if this particular token should be included
in the report

@param  \Gems_Tracker_Token $token
@return boolean This dummy implementation always returns true

protected function _isTokenInFilter(\Gems_Tracker_Token $token)
    {
        $result = false;

        // Only if token has a success code
        if ($token->getReceptionCode()->isSuccess()) {
            $result = true;
        }

        if ($result) {
            $tokenInfo = array(
                'code'     => $token->getSurvey()->getCode(),
                'surveyid' => $token->getSurveyId(),
                'tokenid'  => $token->getTokenId()
            );

            // Now check if the tokenfilter is true
            if (empty($this->tokenFilter)) {
                $result = true;
            } else {
                $result = false;
                // Now read the filter and split by track code or track id
                foreach ($this->tokenFilter as $filter)
                {
                    $remaining = array_diff_assoc($filter, $tokenInfo);
                    if (empty($remaining)) {
                        $result = true;
                        break;
                    }
                }
            }
        }

        return $result;
    }

public java.util.Map captureStatistics()
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass
                        , "captureStatistics"
                            );

        java.util.Map statistics = new java.util.HashMap();
        // inMemoryTokens set to null after close().
        if (inMemoryTokens != null)
            statistics.put("inMemoryTokens.size()", Integer.toString(inMemoryTokens.size()));

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass
                       , "captureStatistics"
                       , statistics
                            );
        return statistics;
    }

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


Question:
Gives the Automated Readability Index of text entered rounded to one digit
@param   boolean|string  $strText         Text to be checked
@return  int|float

public function automatedReadabilityIndex($strText = false)
    {
        $strText = $this->setText($strText);

        $score = Maths::bcCalc(
            Maths::bcCalc(
                4.71,
                '*',
                Maths::bcCalc(
                    Text::letterCount($strText, $this->strEncoding),
                    '/',
                    Text::wordCount($strText, $this->strEncoding)
                )
            ),
            '+',
            Maths::bcCalc(
                Maths::bcCalc(
                    0.5,
                    '*',
                    Maths::bcCalc(
                        Text::wordCount($strText, $this->strEncoding),
                        '/',
                        Text::sentenceCount($strText, $this->strEncoding)
                    )
                ),
                '-',
                21.43
            )
        );

        if ($this->normalise) {
            return Maths::normaliseScore($score, 0, $this->maxGradeLevel, $this->dps);
        } else {
            return Maths::bcCalc($score, '+', 0, true, $this->dps);
        }
    }

public static Literal getLiteral(ValueConstant literal)
	{
        Objects.requireNonNull(literal);
		TermType type = literal.getType();
		if (!(type instanceof RDFDatatype))
			// TODO: throw a proper exception
			throw new IllegalStateException("A ValueConstant given to OWLAPI must have a RDF datatype");
		RDFDatatype datatype = (RDFDatatype) type;

		return datatype.getLanguageTag()
				.map(lang -> fact.createLiteral(literal.getValue(), lang.getFullString()))
				.orElseGet(() -> fact.createLiteral(literal.getValue(),
						fact.createIRI(datatype.getIRI().getIRIString())));
	}

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


Question: /*-------------------------------------------------[ Helpers ]---------------------------------------------------

public static List<Range> union(List<Range> ranges){
        ranges = new ArrayList<Range>(ranges);
        Collections.sort(ranges, new Comparator<Range>(){
            @Override
            public int compare(Range r1, Range r2){
                return r1.min-r2.min;
            }
        });
        List<Range> union = new ArrayList<Range>();
        for(Range r: ranges){
            if(union.isEmpty())
                union.add(r);
            else
                CollectionUtil.addAll(union, union.remove(union.size() - 1).union(r));
        }
        return union;
    }

function define (HTMLFile, utils) {
  const { callable } = utils;
  const { debug, error, strong } = utils.cnsl;
  const { regexpEscape, uniqueMatch } = utils.string;

  return class DUSTFile extends HTMLFile {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Object} caches
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Object} globalAliases
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     */
    constructor (id, filepath, options) {
      super(id, filepath, options);

      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Parse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    parse (buildOptions, fn) {
      super.parse(buildOptions, (err) => {
        if (err) return fn(err);
        // Add sidecar json file
        const sidecarData = super.parseSidecarDependency();
        // Parse includes
        let matches = uniqueMatch(this.content, RE_INCLUDE)
          .map((match) => {
            match.id = match.match;
            return match;
          });

        if (sidecarData) matches.push(sidecarData);
        super.addDependencies(matches, buildOptions);
        fn();
      });
    }

    /**
     * Inline css/img/js dependency content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineInlineable (buildOptions, fn) {
      // Only dependencies
      parallel([...this.getAllDependencies()].reduce((inlineable, file) => {
        if (file instanceof DUSTFile && this.dependencyReferences.length) {
          inlineable.push(callable(file, 'inline', buildOptions));
        }
        return inlineable;
      }, []), fn);
    }

    /**
     * Inline partials content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineIncludes (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof DUSTFile && file.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.context) {
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), reference.file.content);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    compile (buildOptions, fn) {
      // Keep whitespace
      dust.optimizers.format = (ctx, node) => node;
      // Precompile and load
      const source = dust.compile(this.content, this.filepath);

      dust.loadSource(source);
      dust.render(this.filepath, this.findSidecarDependency(), (err, content) => {
        if (err) {
          if (!this.options.runtimeOptions.watch) return fn(err);
          error(err, 4, false);
        }
        this.setContent(content);
        debug(`compile: ${strong(this.relpath)}`, 4);
        fn();
      });
    }

    /**
     * Reparse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    reparse (buildOptions, fn) {
      this.allDependencies = null;
      this.allDependencyReferences = null;
      this.dependencies = [];
      this.dependencyReferences = [];

      super.parse(buildOptions, fn);
    }
  };
}

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


Question:
Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging

    :param pl:
    :param DebugPipe:
    :return:

def augment_pipeline(pl, head_pipe=None, tail_pipe=None):

    for k, v in iteritems(pl):
        if v and len(v) > 0:
            if head_pipe and k != 'source':  # Can't put anything before the source.
                v.insert(0, head_pipe)

            if tail_pipe:
                v.append(tail_pipe)

def main():
    """"""
    parser = argparse.ArgumentParser(
        description=''
    )
    parser.add_argument(
        '--source',
        help='The existing virtual environment.',
        required=True,
    )
    parser.add_argument(
        '--destination',
        help='The location for which to configure the virtual environment.',
        required=True,
    )
    parser.add_argument(
        '--move',
        help='Move the virtual environment to the destination.',
        default=False,
        action='store_true',
    )

    args = parser.parse_args()
    relocate(args.source, args.destination, args.move)

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


Question:
Return the correct gettext translations for a request.

        This will never fail and return a dummy translation object if used
        outside of the request or if a translation cannot be found.

def get_translations(self):

        ctx = _request_ctx_stack.top
        if ctx is None:
            return NullTranslations()

        locale = get_locale()

        cache = self.get_translations_cache(ctx)

        translations = cache.get(str(locale))

        if translations is None:
            translations = self._get_translation_for_locale(locale)
            cache[str(locale)] = translations

        return translations

def save(self, page, language, data, change, extra_data=None):
        """"""
        # if this placeholder is untranslated, we save everything
        # in the default language
        if self.untranslated:
            language = settings.PAGE_DEFAULT_LANGUAGE

        # the page is being changed
        if change:
            # we need create a new content if revision is enabled
            if(settings.PAGE_CONTENT_REVISION and self.name
                not in settings.PAGE_CONTENT_REVISION_EXCLUDE_LIST):
                Content.objects.create_content_if_changed(
                    page,
                    language,
                    self.name,
                    data
                )
            else:
                Content.objects.set_or_create_content(
                    page,
                    language,
                    self.name,
                    data
                )
        # the page is being added
        else:
            Content.objects.set_or_create_content(
                page,
                language,
                self.name,
                data
            )

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


Question: // SetCapacity reloads the size for the loopback device.

func SetCapacity(file *os.File) error {
	if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil {
		logrus.Errorf("Error loopbackSetCapacity: %s", err)
		return ErrSetCapacity
	}
	return nil
}

func NewPool(config *PoolConfig) (*Pool, error) {
	finalConfig := getPoolConfig(config)
	hardwareId, err := getHardwareId()
	if err != nil {
		return nil, err
	}
	return &Pool{
		config:  finalConfig,
		id:      hardwareId,
		wg:      &sync.WaitGroup{},
		exit:    make(chan bool),
		workers: make([]*worker, finalConfig.NumWorkers),
		jobs:    make(chan *Job, finalConfig.BatchSize),
	}, nil
}

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


Question:
Get a key if the network has it.

        Returns:
            :class:`None` if not found, the value otherwise.

async def get(self, key):

        log.info("Looking up key %s", key)
        dkey = digest(key)
        # if this node has it, return it
        if self.storage.get(dkey) is not None:
            return self.storage.get(dkey)
        node = Node(dkey)
        nearest = self.protocol.router.find_neighbors(node)
        if not nearest:
            log.warning("There are no known neighbors to get key %s", key)
            return None
        spider = ValueSpiderCrawl(self.protocol, node, nearest,
                                  self.ksize, self.alpha)
        return await spider.find()

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:
设置忽略类型

@param  string $name

@return self

public function withSkip(string $name): self
    {
        $clone = clone $this;

        if (array_key_exists($name, $clone->skips)) {
            $clone->skips[$name] = 1;
        }

        return $clone;
    }

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
Resizes image according to the given long side (short side proportional)

@param integer $max_long
@param boolean $allow_enlarge
@return static

public function resizeToLongSide($max_long, $allow_enlarge = false)
    {
        if ($this->getSourceHeight() > $this->getSourceWidth()) {
            $ratio = $max_long / $this->getSourceHeight();
            $short = $this->getSourceWidth() * $ratio;

            $this->resize($short, $max_long, $allow_enlarge);
        } else {
            $ratio = $max_long / $this->getSourceWidth();
            $short = $this->getSourceHeight() * $ratio;

            $this->resize($max_long, $short, $allow_enlarge);
        }

        return $this;
    }

public function setLength(int $length) : self
    {
        $this->minLength = $length;
        $this->maxLength = $length;

        return $this;
    }

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


Question:
ex_expression : OP_EXISTS cmp_expression
                         | cmp_expression

def p_ex_expression(tok):
        """"""
        if len(tok) == 3:
            tok[0] = UnaryOperationRule(tok[1], tok[2])
        else:
            tok[0] = tok[1]

public function renderTableRow($row)
	{
		$htmlOptions=array();
		if($this->rowHtmlOptionsExpression!==null)
		{
			$data=$this->dataProvider->data[$row];
			$options=$this->evaluateExpression($this->rowHtmlOptionsExpression,array('row'=>$row,'data'=>$data));
			if(is_array($options))
				$htmlOptions = $options;
		}

		if($this->rowCssClassExpression!==null)
		{
			$data=$this->dataProvider->data[$row];
			$class=$this->evaluateExpression($this->rowCssClassExpression,array('row'=>$row,'data'=>$data));
		}
		elseif(is_array($this->rowCssClass) && ($n=count($this->rowCssClass))>0)
			$class=$this->rowCssClass[$row%$n];

		if(!empty($class))
		{
			if(isset($htmlOptions['class']))
				$htmlOptions['class'].=' '.$class;
			else
				$htmlOptions['class']=$class;
		}

		echo CHtml::openTag('tr', $htmlOptions)."\n";
		foreach($this->columns as $column)
			$this->renderDataCell($column, $row);
		echo "</tr>\n";
	}

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


Question:
Gets human-readable representation of the url (as unicode string,
        IRI according RFC3987)

def get_readable(self):
        '''

        '''
        query = (u'?' + u'&'.join(u'{}={}'.format(urlquote(k), urlquote(v))
                                  for k, v in six.iteritems(self.query))
                 if self.query else '')
        hash_part = (u'#' + self.fragment) if self.fragment is not None else u''

        path, query, hash_part = uri_to_iri_parts(self.path, query, hash_part)

        if self.host:
            port = u':' + self.port if self.port else u''
            return u''.join((self.scheme, '://', self.host, port, path, query, hash_part))
        else:
            return path + query + hash_part

def unescape(s):

    def handle_match(m):
        name = m.group(1)
        if name in HTMLBuilder._entities:
            return unichr(HTMLBuilder._entities[name])
        try:
            if name[:2] in ('#x', '#X'):
                return unichr(int(name[2:], 16))
            elif name.startswith('#'):
                return unichr(int(name[1:]))
        except ValueError:
            pass
        return u''
    return _entity_re.sub(handle_match, s)

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


Question:
Get the queue stats for a specific tube.

@param  \Eyewitness\Eye\Repo\Queue  $queue
@return void

public function storeTubeStats(QueueRepo $queue)
    {
        $history = History::firstOrNew(['date' => date('Y-m-d'),
                                        'hour' => date('H'),
                                        'queue_id' => $queue->id]);

        $history->pending_count = $this->getPendingJobsCount($queue);
        $history->failed_count = $this->getFailedJobsCount($queue);

        $history->exception_count += Cache::pull('eyewitness_q_exception_count_'.$queue->id);
        $history->process_count += Cache::pull('eyewitness_q_process_count_'.$queue->id);
        $history->process_time += Cache::pull('eyewitness_q_process_time_'.$queue->id);
        $history->sonar_time += Cache::pull('eyewitness_q_sonar_time_'.$queue->id);
        $history->sonar_count += Cache::pull('eyewitness_q_sonar_count_'.$queue->id);
        $history->idle_time += Cache::pull('eyewitness_q_idle_time_'.$queue->id);

        $deploy = Cache::get('eyewitness_q_sonar_deployed_'.$queue->id, null);
        if (is_null($deploy)) {
            $history->sonar_deployed = null;
        } else {
            $history->sonar_deployed = time()-$deploy;
        }

        $history->save();
    }

def simulate(self, action):

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

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


Question:
Subscription Type validity

@param string $subscriptionType
Subscription Type to validate
@return boolean Validity is ok or not

static public function isSubscriptionType($subscriptionType) {
    return ((string) $subscriptionType == Connect2PayClient::SUBSCRIPTION_TYPE_NORMAL ||
        (string) $subscriptionType == Connect2PayClient::SUBSCRIPTION_TYPE_INFINITE ||
        (string) $subscriptionType == Connect2PayClient::SUBSCRIPTION_TYPE_ONETIME ||
        (string) $subscriptionType == Connect2PayClient::SUBSCRIPTION_TYPE_LIFETIME);
  }

protected function setValidator()
    {
        // Get query data
        if (!isset($_SERVER['REQUEST_METHOD'])) {
            throw new Exception('Error: The server request method is not set.');
        }
        $queryData = [];
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                $queryData = $_GET;
                break;
            case 'POST':
                $queryData = $_POST;
                break;
            default:
                $input = fopen('php://input', 'r');
                $qData = null;
                while ($data = fread($input, 1024)) {
                    $qData .= $data;
                }
                parse_str($qData, $queryData);
        }
        // If there is query data, set validator to check against the token value
        if (count($queryData) > 0) {
            $val = (isset($queryData[$this->name])) ? $queryData[$this->name] : '';
            $this->addValidator(new \Pop\Validator\Equal($val, 'The security token does not match.'));
        }
    }

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


Question: // Similar to PushLast but with interface provided by funcs.

func PushLastF(Len int, Less func(i, j int) bool, Swap func(i, j int)) {
	heapUp(Less, Swap, Len-1)
}

public function publish(EventInterface $event)
    {
        $commandsToDispatch = $this->eventBus->publish($event);

        $commands = $this->extractCommands($commandsToDispatch);
        foreach ($commands as $command) {
            $this->dispatch($command);
        }
    }

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


Question:
Return a child URLRecord.

        This function is useful for testing filters before adding to table.

def child_url_record(self, url: str, inline: bool=False,
                         link_type: Optional[LinkType]=None,
                         post_data: Optional[str]=None,
                         level: Optional[int]=None):
        '''
        '''
        url_record = URLRecord()
        url_record.url = url
        url_record.status = Status.todo
        url_record.try_count = 0
        url_record.level = self.url_record.level + 1 if level is None else level
        url_record.root_url = self.url_record.root_url or self.url_record.url
        url_record.parent_url = self.url_record.url
        url_record.inline_level = (self.url_record.inline_level or 0) + 1 if inline else 0
        url_record.link_type = link_type
        url_record.post_data = post_data

        return url_record

func (s *AccountsService) Select() ([]Account, *http.Response, error) {
	var ald AccountListDTO
	res, err := s.client.get(AccountsURI(), &ald)

	accts := []Account{}
	for _, t := range ald.Accounts {
		accts = append(accts, t)
	}
	return accts, res, err
}

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


Question:
Returns whether the given item has a specific descendant.
@param string $itemName name of the item.
@param string $descendantName name of the descendant.
@return boolean the result.

public function hasDescendant($itemName, $descendantName)
    {
        $descendants = $this->getDescendants($itemName);
        return isset($descendants[$descendantName]);
    }

def _update_requires_resolution_inputs(self):

        input_paths = [quad[1] for quad in self.requires_resolution]
        results = resolve_multiple_existing_paths(input_paths)
        for input_name, input_value, input_class, input_index in self.requires_resolution:
            project = results[input_value]['project']
            folderpath = results[input_value]['folder']
            entity_result = results[input_value]['name']
            if input_class is None:
                if entity_result is not None:
                    if isinstance(entity_result, basestring):
                        # Case: -ifoo=job-012301230123012301230123
                        # Case: -ifoo=analysis-012301230123012301230123
                        assert(is_job_id(entity_result) or
                               (is_analysis_id(entity_result)))
                        input_value = entity_result
                    elif is_hashid(input_value):
                        input_value = {'$dnanexus_link': entity_result['id']}
                    elif 'describe' in entity_result:
                        # Then findDataObjects was called (returned describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['describe']['project'],
                                                          "id": entity_result['id']}}
                    else:
                        # Then resolveDataObjects was called in a batch (no describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                          "id": entity_result['id']}}
                if input_index >= 0:
                    if self.inputs[input_name][input_index] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name][input_index] = input_value
                else:
                    if self.inputs[input_name] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name] = input_value
            else:
                msg = 'Value provided for input field "' + input_name + '" could not be parsed as ' + \
                      input_class + ': '
                if input_value == '':
                    raise DXCLIError(msg + 'empty string cannot be resolved')
                if entity_result is None:
                    raise DXCLIError(msg + 'could not resolve \"' + input_value + '\" to a name or ID')
                try:
                    dxpy.bindings.verify_string_dxid(entity_result['id'], input_class)
                except DXError as details:
                    raise DXCLIError(msg + str(details))
                if is_hashid(input_value):
                    input_value = {'$dnanexus_link': entity_result['id']}
                elif 'describe' in entity_result:
                    # Then findDataObjects was called (returned describe hash)
                    input_value = {'$dnanexus_link': {"project": entity_result['describe']['project'],
                                                      "id": entity_result['id']}}
                else:
                    # Then resolveDataObjects was called in a batch (no describe hash)
                    input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                      "id": entity_result['id']}}
                if input_index != -1:
                    # The class is an array, so append the resolved value
                    self.inputs[input_name].append(input_value)
                else:
                    self.inputs[input_name] = input_value

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


Question: Create the Record Class for this Record

public void writeClass(String strClassName, ClassProject.CodeType codeType)
    {
        FieldStuff fieldStuff = new FieldStuff();
        ClassInfo recClassInfo = (ClassInfo)this.getMainRecord();
        if (!this.readThisClass(strClassName))  // Get the field this is based on
            return;
        if (RESOURCE_CLASS.equals(recClassInfo.getField(ClassInfo.BASE_CLASS_NAME).toString()))
        {
            this.writeFieldResources(strClassName);
            return;     // Resource only class
        }

        this.writeHeading(strClassName, this.getPackage(codeType), CodeType.THICK);        // Write the first few lines of the files
        this.writeIncludes(CodeType.THICK);
    // Now include any BaseField classes not included in this source (method include)
        try   {
            FieldData recFieldData = (FieldData)this.getRecord(FieldData.FIELD_DATA_FILE);

            this.writeRecordClassDetail(strClassName);  // Write the Thick Record Class

            this.writeFieldResources(strClassName);

            this.writeThinRecord(strClassName);

            this.writeRecordInterface(strClassName);  // Write the Record Class Interface

        // Now write out the BaseField classes
            Record recFileHdr = this.getRecord(FileHdr.FILE_HDR_FILE);

            FieldIterator fieldIterator = new FieldIterator(recFileHdr, recClassInfo, recFieldData, true);
            while (fieldIterator.hasNext())
            {
                recFieldData = (FieldData)fieldIterator.next();
                ClassInfo recClassInfo2 = null;
                boolean ignoreThisField = this.ignoreFieldData(recFieldData);
                this.getFieldData(fieldStuff, false);
                if ((recFieldData.getField(FieldData.FIELD_TYPE).getString().equalsIgnoreCase(FieldTypeField.VIRTUAL_FIELD)) || (fieldStuff.bNotNullField))
                    ignoreThisField = false;
                if (ignoreThisField)
                    continue;
                if ((recClassInfo2 = this.readFieldClass()) != null)
                    if (recClassInfo2.getField(ClassInfo.CLASS_SOURCE_FILE).equals(recClassInfo.getField(ClassInfo.CLASS_SOURCE_FILE)))
                {   // If they are in the same source file, write the field class also.
                    String strFieldDataHandle = recFieldData.getHandle(DBConstants.OBJECT_ID_HANDLE).toString();
                    Map<String,Object> properties = new Hashtable<String,Object>();
                    properties.put(FieldData.FIELD_DATA_FILE, strFieldDataHandle);
                    if ((recClassInfo2.getEditMode() == DBConstants.EDIT_CURRENT)
                        || (recClassInfo2.getEditMode() == DBConstants.EDIT_IN_PROGRESS))
                    {
                        String strClassInfoHandle = recClassInfo2.getHandle(DBConstants.OBJECT_ID_HANDLE).toString();
                        properties.put(ClassInfo.CLASS_INFO_FILE, strClassInfoHandle);
                    }
                    else
                    {
                        properties.put(recClassInfo2.getField(ClassInfo.CLASS_NAME).getFieldName(), recClassInfo2.getField(ClassInfo.CLASS_NAME).toString());
                        properties.put(recClassInfo2.getField(ClassInfo.BASE_CLASS_NAME).getFieldName(), recClassInfo2.getField(ClassInfo.BASE_CLASS_NAME).toString());
                        properties.put(recClassInfo2.getField(ClassInfo.CLASS_PACKAGE).getFieldName(), this.getPackage(codeType));
                        properties.put(recClassInfo2.getField(ClassInfo.CLASS_PROJECT_ID).getFieldName(), recClassInfo2.getField(ClassInfo.CLASS_PROJECT_ID).toString());
                    }

                        WriteFieldClass classWriter = new WriteFieldClass(this.getTask(), null, properties);
                        String strFieldClassName = null;
                        classWriter.writeClass(strFieldClassName, codeType);
                        classWriter.free();
                        classWriter = null;
                }
            }
            recFieldData.close();
        } catch (DBException ex)   {
            ex.printStackTrace();
        }
    }

public function setCustomer($customer)
    {
        $this->data->customer = new stdClass;
        $this->data->customer = $customer;

        return $this;
    }

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


Question: Recursivelt set the parent, section and doc for a children

def set_ownership(self):
        """"""
        assert self.section is not None

        for t in self.children:
            t.parent = self
            t._section = self.section
            t.doc = self.doc
            t.set_ownership()

public function getTreeAction(Lesson $lesson)
    {
        $this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);

        return new JsonResponse($this->chapterManager->serializeChapterTree($lesson));
    }

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


Question: // SetActualProperties sets the ActualProperties field's value.

func (s *StackResourceDrift) SetActualProperties(v string) *StackResourceDrift {
	s.ActualProperties = &v
	return s
}

public function getArgs($name)
    {
        $name = (string)$name;
        if (array_key_exists($name, $this->propertySetArgs)) {
            return $this->propertySetArgs[$name];
        }
        return null;
    }

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


Question:
Set the drawable that is used as this button's icon.
@param icon The drawable.
@param animation Indicate should show animation when switch drawable or not.

public void setIcon(Drawable icon, boolean animation){
        if(icon == null)
            return;

        if(animation) {
            mSwitchIconAnimator.startAnimation(icon);
            invalidate();
        }
        else{
            if(mIcon != null){
                mIcon.setCallback(null);
                unscheduleDrawable(mIcon);
            }

            mIcon = icon;
            float half = mIconSize / 2f;
            mIcon.setBounds((int)(mBackground.getCenterX() - half), (int)(mBackground.getCenterY() - half), (int)(mBackground.getCenterX() + half), (int)(mBackground.getCenterY() + half));
            mIcon.setCallback(this);
            invalidate();
        }
	}

public static void main(String[] args)
    {
        String splashImage = Splash.getParam(args, SPLASH);
        if ((splashImage == null) || (splashImage.length() == 0))
            splashImage = DEFAULT_SPLASH;
        URL url = Splash.class.getResource(splashImage);
        if (url == null)
            if (ClassServiceUtility.getClassService().getClassFinder(null) != null)
                url = ClassServiceUtility.getClassService().getClassFinder(null).findResourceURL(splashImage, null);

        Container container = null;
        Splash.splash(container, url);
        String main = Splash.getParam(args, MAIN);
        if ((main == null) || (main.length() == 0))
            main = ROOT_PACKAGE + "Thin";
        else if (main.charAt(0) == '.')
            main = ROOT_PACKAGE + main.substring(1);
        Splash.invokeMain(main, args);
        Splash.disposeSplash();
    }

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


Question: // ParseClusterAdvertiseSettings parses the specified advertise settings

func ParseClusterAdvertiseSettings(clusterStore, clusterAdvertise string) (string, error) {
	if clusterAdvertise == "" {
		return "", daemondiscovery.ErrDiscoveryDisabled
	}
	if clusterStore == "" {
		return "", errors.New("invalid cluster configuration. --cluster-advertise must be accompanied by --cluster-store configuration")
	}

	advertise, err := discovery.ParseAdvertise(clusterAdvertise)
	if err != nil {
		return "", errors.Wrap(err, "discovery advertise parsing failed")
	}
	return advertise, nil
}

public function setGroupId(int $group_id) : CNabuDataObject
    {
        if ($group_id === null) {
            throw new ENabuCoreException(
                    ENabuCoreException::ERROR_NULL_VALUE_NOT_ALLOWED_IN,
                    array("\$group_id")
            );
        }
        $this->setValue('nb_cluster_user_group_id', $group_id);

        return $this;
    }

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


Question:
<Purpose>
    Returns all valid input completions for the specified command line input.

  <Arguments>
    input_list: A list of tokens.

  <Side Effects>
    None

  <Exceptions>
    None

  <Returns>
    A list of strings representing valid completions.

def autocomplete(input_list):

  # We are only interested if the last token starts with a single '$'
  # Double $$'s indicate that it is meant to be a '$', so we don't do anything.
  if input_list[-1].startswith('$') and not input_list[-1].startswith('$$'):
    # Omit the '$'
    partial_variable = input_list[-1][1:]
    commands = []

    for variable in uservariables:
      # No need to include variables that don't match...
      if variable.startswith(partial_variable):
        # Reconstruct the string
        tokens = input_list[:-1] + ['$'+variable]
        commands.append(' '.join(tokens))
    return commands
  return []

func newTerminalPrompter() *terminalPrompter {
	p := new(terminalPrompter)
	// Get the original mode before calling NewLiner.
	// This is usually regular "cooked" mode where characters echo.
	normalMode, _ := liner.TerminalMode()
	// Turn on liner. It switches to raw mode.
	p.State = liner.NewLiner()
	rawMode, err := liner.TerminalMode()
	if err != nil || !liner.TerminalSupported() {
		p.supported = false
	} else {
		p.supported = true
		p.normalMode = normalMode
		p.rawMode = rawMode
		// Switch back to normal mode while we're not prompting.
		normalMode.ApplyMode()
	}
	p.SetCtrlCAborts(true)
	p.SetTabCompletionStyle(liner.TabPrints)
	p.SetMultiLineMode(true)
	return p
}

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


Question:
Encode the special characters in the string to its URL encoded representation.
@param str The string to encode
@return The encoded string

public static String urlEncode(String str)
    {
        String ret = str;

        try
        {
            ret = URLEncoder.encode(str, "UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
            logger.severe("Failed to encode value: "+str);
        }

        return ret;
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question: // SetNonCompliantChecks sets the NonCompliantChecks field's value.

func (s *TaskStatistics) SetNonCompliantChecks(v int64) *TaskStatistics {
	s.NonCompliantChecks = &v
	return s
}

def is_correct(self):

        state = True

        # Internal checks before executing inherited function...
        cls = self.__class__
        if hasattr(self, 'host_name'):
            for char in cls.illegal_object_name_chars:
                if char in self.host_name:
                    self.add_error("[%s::%s] host_name contains an illegal character: %s"
                                   % (self.my_type, self.get_name(), char))
                    state = False

        # Fred: do not alert about missing check_command for an host... this because 1/ it is
        # very verbose if hosts are not checked and 2/ because it is the Nagios default behavior
        # if not self.check_command:
        #     self.add_warning("[%s::%s] has no defined check command"
        #                      % (self.my_type, self.get_name()))

        if self.notifications_enabled and not self.contacts:
            self.add_warning("[%s::%s] notifications are enabled but no contacts nor "
                             "contact_groups property is defined for this host"
                             % (self.my_type, self.get_name()))

        return super(Host, self).is_correct() and state

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


Question:
@param ResponseInterface $response
@param string $contents

@return ResponseInterface

private function withNewBody(ResponseInterface $response, $contents)
    {
        $body = new Body(fopen('php://temp', 'r+'));
        $body->write($contents);

        return $response->withBody($body);
    }

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:
Get all updates available for all translations.

@see wp_get_translation_updates()

@return array

protected function get_translation_updates() {
		$available = $this->get_installed_languages();

		$func = function() use ( $available ) {
			return $available;
		};

		switch ( $this->obj_type ) {
			case 'plugins':
				add_filter( 'plugins_update_check_locales', $func );

				wp_clean_plugins_cache();
				// Check for Plugin translation updates.
				wp_update_plugins();

				remove_filter( 'plugins_update_check_locales', $func );

				$transient = 'update_plugins';
				break;
			case 'themes':
				add_filter( 'themes_update_check_locales', $func );

				wp_clean_themes_cache();
				// Check for Theme translation updates.
				wp_update_themes();

				remove_filter( 'themes_update_check_locales', $func );

				$transient = 'update_themes';
				break;
			default:
				delete_site_transient( 'update_core' );

				// Check for Core translation updates.
				wp_version_check();

				$transient = 'update_core';
				break;
		}

		$updates   = array();
		$transient = get_site_transient( $transient );

		if ( empty( $transient->translations ) ) {
			return $updates;
		}

		foreach ( $transient->translations as $translation ) {
			$updates[] = (object) $translation;
		}

		return $updates;
	}

protected function addTranslatedColumnGetter(Column $column)
    {
        $objectBuilder = $this->builder->getNewObjectBuilder($this->behavior->getI18nTable());
        $comment = '';
        $functionStatement = '';
        if ($this->isDateType($column->getType())) {
            $objectBuilder->addTemporalAccessorComment($comment, $column);
            $objectBuilder->addTemporalAccessorOpen($functionStatement, $column);
        } else {
            $objectBuilder->addDefaultAccessorComment($comment, $column);
            $objectBuilder->addDefaultAccessorOpen($functionStatement, $column);
        }
        $comment = preg_replace('/^\t/m', '', $comment);
        $functionStatement = preg_replace('/^\t/m', '', $functionStatement);
        preg_match_all('/\$[a-z]+/i', $functionStatement, $params);

        return $this->behavior->renderTemplate('objectTranslatedColumnGetter', [
            'comment'           => $comment,
            'functionStatement' => $functionStatement,
            'columnPhpName'     => $column->getPhpName(),
            'params'            => implode(', ', $params[0]),
        ]);
    }

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


Question:
Creates a bounding box of the entire world in EPSG: 3857

        :return: Bounding box of entire world
        :rtype: BBox

def get_world_bbox(self):

        return BBox((-self.POP_WEB_MAX, -self.POP_WEB_MAX, self.POP_WEB_MAX, self.POP_WEB_MAX), crs=CRS.POP_WEB)

def prepare_package(err, path, expectation=0, for_appversions=None,
                    timeout=-1):

    package = None
    try:
        # Test that the package actually exists. I consider this Tier 0
        # since we may not even be dealing with a real file.
        if not os.path.isfile(path):
            err.error(('main', 'prepare_package', 'not_found'),
                      'The package could not be found')
            return

        # Pop the package extension.
        package_extension = os.path.splitext(path)[1]
        package_extension = package_extension.lower()

        def timeout_handler(signum, frame):
            raise validator.ValidationTimeout(timeout)

        if timeout != -1:
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.setitimer(signal.ITIMER_REAL, timeout)

        if package_extension == '.xml':
            test_search(err, path, expectation)
        elif package_extension not in ('.xpi', '.jar'):
            err.error(('main', 'prepare_package', 'unrecognized'),
                      'The package is not of a recognized type.')
        else:
            package = open(path, 'rb')
            test_package(err, package, path, expectation, for_appversions)

        err.metadata['is_extension'] = err.detected_type == PACKAGE_EXTENSION

    except validator.ValidationTimeout:
        err.system_error(
            msg_id='validation_timeout',
            message='Validation has timed out',
            signing_severity='high',
            description=('Validation was unable to complete in the allotted '
                         'time. This is most likely due to the size or '
                         'complexity of your add-on.',
                         'This timeout has been logged, but please consider '
                         'filing an issue report here: '
                         'https://bit.ly/1POrYYU'),
            exc_info=sys.exc_info())

    except Exception:
        err.system_error(exc_info=sys.exc_info())

    finally:
        # Remove timers and signal handlers regardless of whether
        # we've completed successfully or the timer has fired.
        if timeout != -1:
            signal.setitimer(signal.ITIMER_REAL, 0)
            signal.signal(signal.SIGALRM, signal.SIG_DFL)

        if package:
            package.close()

        decorator.cleanup()

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


Question:
Attempts to resolve issues where our samples use
        'http://example.com/' for our example namespace but python-stix uses
        'http://example.com' by removing the former.

def _fix_example_namespace(self):

        example_prefix = 'example'  # Example ns prefix
        idgen_prefix = idgen.get_id_namespace_prefix()

        # If the ID namespace alias doesn't match the example alias, return.
        if idgen_prefix != example_prefix:
            return

        # If the example namespace prefix isn't in the parsed namespace
        # prefixes, return.
        if example_prefix not in self._input_namespaces:
            return

        self._input_namespaces[example_prefix] = idgen.EXAMPLE_NAMESPACE.name

def find_scraperclasses(comic, multiple_allowed=False):
    """"""
    if not comic:
        raise ValueError("empty comic name")
    candidates = []
    cname = comic.lower()
    for scraperclass in get_scraperclasses():
        lname = scraperclass.getName().lower()
        if lname == cname:
            # perfect match
            if not multiple_allowed:
                return [scraperclass]
            else:
                candidates.append(scraperclass)
        elif cname in lname:
            candidates.append(scraperclass)
    if len(candidates) > 1 and not multiple_allowed:
        comics = ", ".join(x.getName() for x in candidates)
        raise ValueError('multiple comics found: %s' % comics)
    elif not candidates:
        raise ValueError('comic %r not found' % comic)
    return candidates

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


Question:
Create a new Voice App
@throws \CALLR\API\Exception\LocalException if missing $apiObjectName
@return boolean true or throws Exception otherwise

public function create()
    {
        if ($this->apiObjectName === null) {
            throw new LocalException('Missing Object Name in "'.get_class($this).'"');
        }
        $result = $this->api->call('apps.create', [$this->apiObjectName, $this->name, $this->p]);
        $this->setProperties($result);
        return true;
    }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question: delete ///////////////////////////////////////////////////////////////////

public void deleteHistoricExternalTaskLogsByProcessInstanceIds(List<String> processInstanceIds) {
    deleteExceptionByteArrayByParameterMap("processInstanceIdIn", processInstanceIds.toArray());
    getDbEntityManager().deletePreserveOrder(HistoricExternalTaskLogEntity.class, "deleteHistoricExternalTaskLogByProcessInstanceIds", processInstanceIds);
  }

def truncate content  #:nodoc:
      #maxlen = @maxlen || @width-2
      _maxlen = @maxlen || @width-@internal_width
      _maxlen = @width-@internal_width if _maxlen > @width-@internal_width
      _maxlen -= @left_margin
      if !content.nil?
        cl = content.length
        if cl > _maxlen # only show maxlen
          @longest_line = cl if cl > @longest_line
          ## taking care of when scrolling is needed but longest_line is misreported
          # So we scroll always and need to check 2013-03-06 - 00:09
          #content.replace content[@pcol..@pcol+_maxlen-1]
          content.replace(content[@pcol..@pcol+maxlen-1] || " ")
        else
          #content.replace content[@pcol..-1] if @pcol > 0
          content.replace(content[@pcol..-1]||" ") if @pcol > 0
        end
      end
      content
    end

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


function produce_one (shared_ctx, self_ctx, cb) {
  if (shared_ctx.push_count > shared_ctx.push_max) {
    console.log ('producer %s ended', self_ctx.id);
    return cb ();
  }

  shared_ctx.push_count ++;
  self_ctx.push_count ++;

  shared_ctx.q.push ({a: chance.integer (), b: chance.word (), n: shared_ctx.push_count}, function (err, res) {
    if (err) return console.error (err);
//    if ((shared_ctx.push_count % 100000) == 0) console.log ('%s : produced #%d elems', self_ctx.id, shared_ctx.push_count);
    produce_one (shared_ctx, self_ctx, cb);
  });
}

public static function create(SteeinResponse $response)
    {
        $data = $response->getDecodedBody();

        if (!isset($data['error']['code']) && isset($data['code'])) {
            $data = ['error' => $data];
        }

        $code = isset($data['error']['code']) ? $data['error']['code'] : null;
        $message = isset($data['error']['message']) ? $data['error']['message'] : 'Неизвестная ошибка из Api.';

        if (isset($data['error']['error_subcode']))
        {
            switch ($data['error']['error_subcode'])
            {
                // Другие проблемы с аутентификацией
                case 458:
                case 459:
                case 460:
                case 463:
                case 464:
                case 467:
                    return new static($response, new AuthenticationException($message, $code));
            }
        }

        switch ($code) {
            // Статус входа или токен устарел, отозван или недействителен
            case 100:
            case 102:
            case 190:
                return new static($response, new AuthenticationException($message, $code));

            // Проблема сервера
            case 1:
            case 2:
                return new static($response, new ServerException($message, $code));

            // Дросселирование API
            case 4:
            case 17:
            case 341:
                return new static($response, new ThrottleException($message, $code));

            // Повторяющаяся запись
            case 506:
                return new static($response, new ClientException($message, $code));
        }

        // Отсутствующие разрешения
        if ($code == 10 || ($code >= 200 && $code <= 299)) {
            return new static($response, new AuthorizationException($message, $code));
        }

        // OAuth ошибка аутентификации
        if (isset($data['error']['type']) && $data['error']['type'] === 'OAuthException') {
            return new static($response, new AuthenticationException($message, $code));
        }

        // Все остальные
        return new static($response, new DefaultException($message, $code));
    }

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


Question:
Sets the summary content.

@param content the new summary content

public void setSummaryContent(String content) {
		Logger.getRootLogger().info("New summary: "+content);
		summaryArea.setText("" + summaryTitleText + "

" + content + "");
	}

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

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

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

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


Question: convert '(1,2),(4,5)' to [{x:1, y:2},{x: 4, y: 5}]

function(str){
    if(typeof str !== 'string') return null
    return str.replace(/,(\([0-9.]+,[0-9.]+\))/g, '|$1')
    .split('|')
    .map(module.exports.convertPoint)
  }

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

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


Question:
Redirect to the current URL with given language code applied
@param string $language the language code to add. Can also be empty to not add any language code.

protected function redirectToLanguage($language)
    {
        $result = parent::parseRequest($this->_request);
        if ($result === false) {
            throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
        }
        list ($route, $params) = $result;
        if($language){
            $params[$this->languageParam] = $language;
        }

        $params = $params + $this->_request->getQueryParams();
        array_unshift($params, $route);
        $url = $this->createUrl($params);

        if ($this->suffix==='/' && $route==='') {
            $url = rtrim($url, '/').'/';
        }
        Yii::$app->getResponse()->redirect($url);
        if (YII_ENV_TEST) {

            throw new Exception(Url::to($url));
        } else {
            Yii::$app->end();
        }
    }

public function type()
    {
        $lang = $this->lang();
        $html = [
            '<!doctype html>',
            '<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7 ie6" '
            . 'lang="' . $lang . '" dir="' . $this->dir . '"> <![endif]-->',
            '<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8 ie7" '
            . 'lang="' . $lang . '" dir="' . $this->dir . '"> <![endif]-->',
            '<!--[if IE 8]><html class="no-js lt-ie9 ie8" '
            . 'lang="' . $lang . '" dir="' . $this->dir . '"> <![endif]-->',
            '<!--[if gt IE 8]><!--><html class="no-js" xmlns="http://www.w3.org/1999/xhtml" '
            . 'lang="' . $lang . '" dir="' . $this->dir . '" '
            . 'prefix="og: http://ogp.me/ns#" '
            . '> <!--<![endif]-->',
        ];
        return implode($this->eol, $html) . $this->eol;
    }

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


Question:
Upload a new PDF template with a file upload
 @param template_document
 @param template_name
 @param [Hash] opts the optional parameters
 @return [Array<(PendingTemplate, Fixnum, Hash)>] PendingTemplate data, response status code and response headers

def create_template_with_http_info(template_document, template_name, opts = {})
      if @api_client.config.debugging
        @api_client.config.logger.debug 'Calling API: PDFApi.create_template ...'
      end
      # verify the required parameter 'template_document' is set
      if @api_client.config.client_side_validation && template_document.nil?
        fail ArgumentError, "Missing the required parameter 'template_document' when calling PDFApi.create_template"
      end
      # verify the required parameter 'template_name' is set
      if @api_client.config.client_side_validation && template_name.nil?
        fail ArgumentError, "Missing the required parameter 'template_name' when calling PDFApi.create_template"
      end
      # resource path
      local_var_path = '/templates'

      # query parameters
      query_params = {}

      # header parameters
      header_params = {}
      # HTTP header 'Accept' (if needed)
      header_params['Accept'] = @api_client.select_header_accept(['application/json'])
      # HTTP header 'Content-Type'
      header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])

      # form parameters
      form_params = {}
      form_params['template[document]'] = template_document
      form_params['template[name]'] = template_name

      # http body (model)
      post_body = nil
      auth_names = ['api_token_basic']
      data, status_code, headers = @api_client.call_api(:POST, local_var_path,
        :header_params => header_params,
        :query_params => query_params,
        :form_params => form_params,
        :body => post_body,
        :auth_names => auth_names,
        :return_type => 'PendingTemplate')
      if @api_client.config.debugging
        @api_client.config.logger.debug "API called: PDFApi#create_template\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
      end
      return data, status_code, headers
    end

private function prepareRequestArguments(array $data = null, string $method = null): array
    {
        $data   = $data ?? [];
        $method = $method ?? 'GET';

        // Removes null entries.
        $data = array_filter($data, function ($val) {
            return (null !== $val);
        });

        $headers = [
            'Content-Type' => 'application/json',
            'X-Auth-Email' => $this->email,
            'X-Auth-Key'   => $this->auth_key,
        ];

        $args = [
            'body'    => wp_json_encode($data),
            'headers' => $headers,
            'method'  => strtoupper($method),
            'timeout' => 15,
        ];

        return $args;
    }

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


Question:
设置授权方的选项信息

@param $authorizer_appid
@param $option_name
@param $option_value
@return mixed

public function setAuthorizerOption($authorizer_appid, $option_name, $option_value)
    {
        $params = array(
            'component_appid'  => $this->appid,
            'authorizer_appid' => $authorizer_appid,
            'option_name'      => $option_name,
            'option_value'     => $option_value,
        );

        return $this->http->jsonPost(self::API_SET_AUTHORIZER_OPTION, $params);
    }

public function read( $curlOptions = array() )
	{
		$curl		= new Net_CURL( $this->url );

		$curl->setOption( CURLOPT_SSL_VERIFYHOST, $this->verifyHost );
		$curl->setOption( CURLOPT_SSL_VERIFYPEER, $this->verifyPeer );
		$curl->setOption( CURLOPT_FOLLOWLOCATION, !ini_get( 'safe_mode' ) && !ini_get( 'open_basedir' ) );
		$curl->setOption( CURLOPT_HEADER, TRUE );
		if( self::$userAgent )
			$curl->setOption( CURLOPT_USERAGENT, self::$userAgent );
		if( $this->username )
			$curl->setOption( CURLOPT_USERPWD, $this->username.":".$this->password );
		if( $this->proxyAddress ){
			$curl->setOption( CURLOPT_HTTPPROXYTUNNEL, TRUE);
			$curl->setOption( CURLOPT_PROXY, $this->proxyAddress );
			$curl->setOption( CURLOPT_PROXYTYPE, $this->proxyType );
			if( $this->proxyAuth )
				$curl->setOption( CURLOPT_PROXYUSERPWD, $this->proxyAuth );
		}

		foreach( $curlOptions as $key => $value )
		{
			if( is_string( $key ) )
			{
				if( !( preg_match( "@^CURLOPT_@", $key ) && defined( $key ) ) )
					throw new InvalidArgumentException( 'Invalid option constant key "'.$key.'"' );
				$key	= constant( $key );
			}
			if( !is_int( $key ) )
				throw new InvalidArgumentException( 'Option must be given as integer or string' );
			$curl->setOption( $key, $value );
		}
		$result			= $curl->exec( TRUE, FALSE );
		$response		= Net_HTTP_Response_Parser::fromString( $result );

		$this->body		= $response->getBody();
		$this->headers	= $response->getHeaders();
		$this->info		= $curl->getInfo();
		$code			= $curl->getInfo( Net_CURL::INFO_HTTP_CODE );
		$error			= $curl->getInfo( Net_CURL::INFO_ERROR );
		$errno			= $curl->getInfo( Net_CURL::INFO_ERRNO );
		if( $errno )
			throw new Exception_IO( 'HTTP request failed: '.$error, $errno, $this->url );
		if( !in_array( $code, array( '200', '301', '303', '304', '307' ) ) )
			throw new Exception_IO( 'HTTP request failed', $code, $this->url );
		return $this->body;
	}

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