Question:
Parse all branches.

@param \WP_Query $query

@return \stdClass

private function parse(\WP_Query $query = null)
    {
        (is_null($query) && isset($GLOBALS['wp_query'])) and $query = $GLOBALS['wp_query'];

        $data = (object)['hierarchy' => [], 'templates' => [], 'query' => $query];

        $branches = self::$branches;

        // make the branches filterable, but assuring each item still implement branch interface
        if ($this->flags & self::FILTERABLE) {
            $branches = array_filter(
                (array)apply_filters('brain.hierarchy.branches', $branches),
                function ($branch) {
                    return is_subclass_of($branch, Branch\BranchInterface::class, true);
                }
            );
        }

        // removed indexes, we added them to make filtering easier
        $branches = array_values($branches);

        if ($query instanceof \WP_Query) {
            $data = array_reduce($branches, [$this, 'parseBranch'], $data);
        }

        $data->hierarchy = $this->addIndexLeaves($data->hierarchy);
        $data->templates[] = 'index';
        $data->templates = array_values(array_unique($data->templates));

        return $data;
    }

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(searchRequest.getCursor(), CURSOR_BINDING);
            protocolMarshaller.marshall(searchRequest.getExpr(), EXPR_BINDING);
            protocolMarshaller.marshall(searchRequest.getFacet(), FACET_BINDING);
            protocolMarshaller.marshall(searchRequest.getFilterQuery(), FILTERQUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getHighlight(), HIGHLIGHT_BINDING);
            protocolMarshaller.marshall(searchRequest.getPartial(), PARTIAL_BINDING);
            protocolMarshaller.marshall(searchRequest.getQuery(), QUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryOptions(), QUERYOPTIONS_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryParser(), QUERYPARSER_BINDING);
            protocolMarshaller.marshall(searchRequest.getReturn(), RETURN_BINDING);
            protocolMarshaller.marshall(searchRequest.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(searchRequest.getSort(), SORT_BINDING);
            protocolMarshaller.marshall(searchRequest.getStart(), START_BINDING);
            protocolMarshaller.marshall(searchRequest.getStats(), STATS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Returns the ad hoc hooks that have been enabled for a hook type.

def enabled_ad_hoc_hooks(hook_context)
      @hash[hook_context.hook_class_name].keys.
        reject { |hook_name| hook_name == 'ALL' }.
        select { |hook_name| ad_hoc_hook?(hook_context, hook_name) }.
        select { |hook_name| hook_enabled?(hook_context, hook_name) }
    end

private void installShutdownHook() {
		if (shutdownHook == null) {
			this.shutdownHook = ShutdownHookUtil.addShutdownHook(this::dispose, getClass().getSimpleName(), LOG);
		}
	}

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


Question: Marshall the given parameter object.

public void marshall(GetRateBasedRuleRequest getRateBasedRuleRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getRateBasedRuleRequest.getRuleId(), RULEID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
This method is responsible for spawning a local hub for supporting local executions

@param testSession
- A {@link AbstractTestSession} that represents the type of test session to start (mobile or web).

public static synchronized void spawnLocalHub(AbstractTestSession testSession) {
        LOGGER.entering(testSession.getPlatform());
        if (!isRunLocally()) {
            LOGGER.exiting();
            return;
        }

        setupToBootList();
        for (LocalServerComponent eachItem : toBoot) {
            try {
                eachItem.boot(testSession);
            } catch (Exception e) { //NOSONAR
                // If either the Grid or the Node failed to start at the first attempt then there is NO point in trying
                // to keep restarting it for every iteration. So lets log a severe message and exit the JVM.
                LOGGER.log(Level.SEVERE, e.getMessage(), e);
                System.exit(1);
            }
        }
        LOGGER.exiting();
    }

public void init(Database database, String host, String port) throws DevFailed {
        super.init(database, host, port);
    }

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


Question:
Temporaneo per i test, ritorna i dati sotto forma di matrice.

@return

public double[][] getResults() {
        double[][] results = new double[networkPipes.length][28];
        double[] one = new double[networkPipes.length];
        double[] two = new double[networkPipes.length];
        for( int i = 0; i < networkPipes.length; i++ ) {
            one[i] = i;
            two[i] = networkPipes[i].getId();

        }
        QuickSortAlgorithm t = new QuickSortAlgorithm(pm);
        t.sort(two, one);

        for( int i = 0; i < networkPipes.length; i++ ) {
            int index = (int) one[i];
            results[i][0] = networkPipes[index].getId();
            results[i][1] = networkPipes[index].getIdPipeWhereDrain();
            results[i][2] = networkPipes[index].getDrainArea();
            results[i][3] = networkPipes[index].getLenght();
            results[i][4] = networkPipes[index].getInitialElevation();
            results[i][5] = networkPipes[index].getFinalElevation();
            results[i][6] = networkPipes[index].getRunoffCoefficient();
            results[i][7] = networkPipes[index].getAverageResidenceTime();
            results[i][8] = networkPipes[index].getKs();
            results[i][9] = networkPipes[index].getMinimumPipeSlope();
            results[i][10] = networkPipes[index].getPipeSectionType();
            results[i][11] = networkPipes[index].getAverageSlope();
            results[i][12] = networkPipes[index].discharge;
            results[i][13] = networkPipes[index].coeffUdometrico;
            results[i][14] = networkPipes[index].residenceTime;
            results[i][15] = networkPipes[index].tP;
            results[i][16] = networkPipes[index].tQmax;
            results[i][17] = networkPipes[index].meanSpeed;
            results[i][18] = networkPipes[index].pipeSlope;
            results[i][19] = networkPipes[index].diameter;
            results[i][20] = networkPipes[index].emptyDegree;
            results[i][21] = networkPipes[index].depthInitialPipe;
            results[i][22] = networkPipes[index].depthFinalPipe;
            results[i][23] = networkPipes[index].initialFreesurface;
            results[i][24] = networkPipes[index].finalFreesurface;
            results[i][25] = networkPipes[index].totalSubNetArea;
            results[i][26] = networkPipes[index].meanLengthSubNet;
            results[i][27] = networkPipes[index].varianceLengthSubNet;

        }

        return results;
    }

public function transform($dateInterval)
    {
        if ($dateInterval === null) {
            return [
                'year' => '0',
                'month' => '0',
                'day' => '0',
                'hour' => '0',
                'minute' => '0',
                'second' => '0',
            ];
        }

        if (!$dateInterval instanceof DateInterval) {
            throw new TransformationFailedException('Expected a DateInterval.');
        }

        $result = [
            'year' => $dateInterval->format('%y'),
            'month' => $dateInterval->format('%m'),
            'day' => $dateInterval->format('%d'),
            'hour' => $dateInterval->format('%h'),
            'minute' => $dateInterval->format('%i'),
            'second' => $dateInterval->format('%s'),
        ];

        return $result;
    }

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


Question:
ArrayObjectをmergeします。

@param	\ArrayObject		$array_object	マージされるArrayObject
@param	\ArrayObject/array	[, $array...]	マージする\ArrayObject/array
@return	LazyArrayObject	マージ後のインスタンス

public static function ArrayObjectMerge (\ArrayObject $array_object) {
		$args = func_get_args();
		array_shift($args);
		return static::_ArrayObjectMerge($array_object, $args);
	}

public function Merge($OldUserID, $NewUserID) {
      $OldUser = $this->GetID($OldUserID, DATASET_TYPE_ARRAY);
      $NewUser = $this->GetID($NewUserID, DATASET_TYPE_ARRAY);

      if (!$OldUser || !$NewUser) {
         throw new Gdn_UserException("Could not find one or both users to merge.");
      }

      $Map = array('UserID', 'Name', 'Email', 'CountVisits', 'CountDiscussions', 'CountComments');

      $Result = array('MergeID' => NULL, 'Before' => array(
         'OldUser' => ArrayTranslate($OldUser, $Map),
         'NewUser' => ArrayTranslate($NewUser, $Map)));

      // Start the merge.
      $MergeID = $this->MergeStart($OldUserID, $NewUserID);

      // Copy all discussions from the old user to the new user.
      $this->MergeCopy($MergeID, 'Discussion', 'InsertUserID', $OldUserID, $NewUserID);

      // Copy all the comments from the old user to the new user.
      $this->MergeCopy($MergeID, 'Comment', 'InsertUserID', $OldUserID, $NewUserID);

      // Copy all of the activities.
      $this->MergeCopy($MergeID, 'Activity', 'NotifyUserID', $OldUserID, $NewUserID);
      $this->MergeCopy($MergeID, 'Activity', 'InsertUserID', $OldUserID, $NewUserID);
      $this->MergeCopy($MergeID, 'Activity', 'ActivityUserID', $OldUserID, $NewUserID);

      // Copy all of the activity comments.
      $this->MergeCopy($MergeID, 'ActivityComment', 'InsertUserID', $OldUserID, $NewUserID);

      // Copy all conversations.
      $this->MergeCopy($MergeID, 'Conversation', 'InsertUserID', $OldUserID, $NewUserID);
      $this->MergeCopy($MergeID, 'ConversationMessage', 'InsertUserID', $OldUserID, $NewUserID, 'MessageID');
      $this->MergeCopy($MergeID, 'UserConversation', 'UserID', $OldUserID, $NewUserID, 'ConversationID');

      $this->MergeFinish($MergeID);

      $OldUser = $this->GetID($OldUserID, DATASET_TYPE_ARRAY);
      $NewUser = $this->GetID($NewUserID, DATASET_TYPE_ARRAY);

      $Result['MergeID'] = $MergeID;
      $Result['After'] = array(
         'OldUser' => ArrayTranslate($OldUser, $Map),
         'NewUser' => ArrayTranslate($NewUser, $Map));

      return $Result;
   }

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


Question:
根据扩展名过滤上传的文件,该方法会生成一个错误列表
@return array 过滤后的文件

private function filterFile($files)
    {
        if (strpos($this->setting['ext'], '*') !== false) {
            return $files;
        }
        $exts = explode('|', $this->setting['ext']);

        foreach ($files as $field => &$file) {
            if (!isset($file['name'])) {
                continue;
            }
            $name = $file['name'];
            if (is_array($name)) {
                foreach ($name as $k => $v) {
                    $ext = $this->getExt($v);
                    if (!in_array($ext, $exts)) {
                        unset($file['name'][$k]);
                        unset($file['type'][$k]);
                        unset($file['tmp_name'][$k]);
                        unset($file['error'][$k]);
                        unset($file['size'][$k]);
                        $this->setError('500', $field . '字段中的' . $v . '文件不在允许的扩展名之内');
                    }
                }
            } else {
                $ext = $this->getExt($name);
                if (!in_array($ext, $exts)) {
                    unset($files[$field]);
                    $this->setError('500', $field . '字段中的' . $name . '文件不在允许的扩展名之内');
                }
            }
        }
        return $files;
    }

protected function extractPayload($model, $comments = '')
    {
        $payload = [];
        preg_match('/@payload\ (.*)\n/i', $comments, $doc);
        $isArray = false;
        if (count($doc)) {
            $namespace = str_replace('{__API__}', $model, $doc[1]);
            if (false !== strpos($namespace, '[') && false !== strpos($namespace, ']')) {
                $namespace = str_replace(']', '', str_replace('[', '', $namespace));
                $isArray = true;
            }
            $payload = $this->extractModelFields($namespace);
            $reflector = new \ReflectionClass($namespace);
            $shortName = $reflector->getShortName();
        } else {
            $namespace = $model;
            $shortName = $model;
        }

        return [$namespace, $shortName, $payload, $isArray];
    }

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


Question:
// readHttpLocation reads an http (or https) url.
// It returns the contents, or an error on any non-200 response.  On a 404, it will return os.ErrNotExist
// It will retry a few times on a 500 class error

func (c *VFSContext) readHttpLocation(httpURL string, httpHeaders map[string]string) ([]byte, error) {
	// Exponential backoff, starting with 500 milliseconds, doubling each time, 5 steps
	backoff := wait.Backoff{
		Duration: 500 * time.Millisecond,
		Factor:   2,
		Steps:    5,
	}

	var body []byte

	done, err := RetryWithBackoff(backoff, func() (bool, error) {
		glog.V(4).Infof("Performing HTTP request: GET %s", httpURL)
		req, err := http.NewRequest("GET", httpURL, nil)
		if err != nil {
			return false, err
		}
		for k, v := range httpHeaders {
			req.Header.Add(k, v)
		}
		response, err := http.DefaultClient.Do(req)
		if response != nil {
			defer response.Body.Close()
		}
		if err != nil {
			return false, fmt.Errorf("error fetching %q: %v", httpURL, err)
		}
		body, err = ioutil.ReadAll(response.Body)
		if err != nil {
			return false, fmt.Errorf("error reading response for %q: %v", httpURL, err)
		}
		if response.StatusCode == 404 {
			// We retry on 404s in case of eventual consistency
			return false, os.ErrNotExist
		}
		if response.StatusCode >= 500 && response.StatusCode <= 599 {
			// Retry on 5XX errors
			return false, fmt.Errorf("unexpected response code %q for %q: %v", response.Status, httpURL, string(body))
		}

		if response.StatusCode == 200 {
			return true, nil
		}

		// Don't retry on other errors
		return true, fmt.Errorf("unexpected response code %q for %q: %v", response.Status, httpURL, string(body))
	})
	if err != nil {
		return nil, err
	} else if done {
		return body, nil
	} else {
		// Shouldn't happen - we always return a non-nil error with false
		return nil, wait.ErrWaitTimeout
	}
}

func goErrorHandler(code C.int, reason *C.char) {
	reasonHeader := reflect.StringHeader{
		Data: uintptr(unsafe.Pointer(reason)),
		Len:  int(C.strlen(reason)),
	}
	reasonString := (*string)(unsafe.Pointer(&reasonHeader))
	Log.Printf("%s -- %s", codeToString(int(code)), *reasonString)
}

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


Question: set access control methods

private function methods()
    {
        $methods = '';
        foreach (config('cors.methods') as $method) {
            $methods = $methods . $method . ', ';
        }
        header('Access-Control-Allow-Methods: ' . $methods);
    }

@Override
    public Request<ReplaceNetworkAclAssociationRequest> getDryRunRequest() {
        Request<ReplaceNetworkAclAssociationRequest> request = new ReplaceNetworkAclAssociationRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

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


Question:
// ToMap creates a map of key-value pairs from a variadic key-value pair slice.
//
// The implementation bellow is from go-kit's JSON logger.

func ToMap(kvs []interface{}) map[string]interface{} {
	m := map[string]interface{}{}

	if len(kvs) == 0 {
		return m
	}

	if len(kvs)%2 == 1 {
		kvs = append(kvs, nil)
	}

	for i := 0; i < len(kvs); i += 2 {
		merge(m, kvs[i], kvs[i+1])
	}

	return m
}

def to_dict(self):

        json_dict = {"apiKey": self.api_key,
                     "userArn": self.user_arn,
                     "cognitoAuthenticationType": self.cognito_authentication_type,
                     "caller": self.caller,
                     "userAgent": self.user_agent,
                     "user": self.user,
                     "cognitoIdentityPoolId": self.cognito_identity_pool_id,
                     "cognitoAuthenticationProvider": self.cognito_authentication_provider,
                     "sourceIp": self.source_ip,
                     "accountId": self.account_id
                     }

        return json_dict

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


Question:
Parse the configuration file

@param array $parsedConfig

private function loadConfig($parsedConfig) {
        if(isset($parsedConfig['moduleConf']['Type']) && $parsedConfig['moduleConf']['Type'] == "smtp"){

            $this->transport = \Swift_SmtpTransport::newInstance();

            if(isset($parsedConfig['moduleConf']['Host']) && $parsedConfig['moduleConf']['Host'] != ""){
                $this->transport->setHost($parsedConfig['moduleConf']['Host']);
            }

            if(isset($parsedConfig['moduleConf']['Port']) && $parsedConfig['moduleConf']['Port'] != ""){
                $this->transport->setPort($parsedConfig['moduleConf']['Port']);
            }

            if(isset($parsedConfig['moduleConf']['Username']) && $parsedConfig['moduleConf']['Username'] != ""){
                $this->transport->setUsername($parsedConfig['moduleConf']['Username']);
            }

            if(isset($parsedConfig['moduleConf']['Password']) && $parsedConfig['moduleConf']['Password'] != ""){
                $this->transport->setPassword($parsedConfig['moduleConf']['Password']);
            }

            if(isset($parsedConfig['moduleConf']['Encryption']) && $parsedConfig['moduleConf']['Encryption'] != ""){
                $this->transport->setEncryption($parsedConfig['moduleConf']['Encryption']);
            }

        }
        elseif(isset($parsedConfig['moduleConf']['Type']) && $parsedConfig['moduleConf']['Type'] == "sendmail"){

            $this->transport = \Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');

        }else{

            $this->transport = \Swift_MailTransport::newInstance();

        }

    }

public function setOption($name, $value) {
		$this->validateName($name);
		$this->config[$name] = $value;
	}

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


Question:
replaces content in path with new_content, commits using
 comment and 3-way merges new and old content with the previous
 version of file of the same kind, if it exists.
 returns the number of conflicts

def merge_new_content(new_content, path, comment, kind)
      from_directory do
        log.debug "merging new content to #{path} of kind #{kind}"
        already_existing = File.exist?(path)

        generated_comment = "tetra: generated-#{kind}"
        whole_comment = [comment, generated_comment].join("\n\n")

        if already_existing
          unless @git.latest_id(generated_comment)
            log.debug "committing new file"
            @git.commit_file(path, whole_comment)
          end
          log.debug "moving #{path} to #{path}.tetra_user_edited"
          File.rename(path, "#{path}.tetra_user_edited")
        end

        previous_id = @git.latest_id(generated_comment)

        File.open(path, "w") { |io| io.write(new_content) }
        log.debug "committing new content: #{comment}"
        @git.commit_file(path, whole_comment)

        if already_existing
          # 3-way merge
          conflict_count = @git.merge_with_id(path, "#{path}.tetra_user_edited", previous_id)
          File.delete("#{path}.tetra_user_edited")

          @git.commit_file(path, "User changes merged back") if conflict_count == 0

          return conflict_count
        end
        return 0
      end
    end

protected function updateCode() : array
    {
        $output = [];
        $returnValue = 0;

        $updateMaster = 'ls'; // dummy

        if ($this->getBranch() !== 'master') {
            $updateMaster = ' git checkout master && git pull && git checkout '.$this->getBranch().' ';
        }

        $commands = [
            'git reset --hard HEAD',
            'git pull',
            $updateMaster,
            'composer install --no-dev',
            'yarn install --production',
        ];

        foreach ($commands as $command) {
            exec('cd '.$this->getBasepath().' && '.$command, $output, $returnValue);
        }

        return [
            'output'      => $output,
            'returnValue' => $returnValue,
        ];
    }

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


Question:
addAndStartListener first adds the specific processorListener then starts the listener with
executor.

@param processorListener specific processor listener

public void addAndStartListener(final ProcessorListener<ApiType> processorListener) {
    lock.writeLock().lock();
    try {
      addListenerLocked(processorListener);

      executorService.execute(processorListener);
    } finally {
      lock.writeLock().unlock();
    }
  }

protected void processClass (File source)
    {
        // load up the file and determine it's package and classname
        String name = null;
        try {
            name = GenUtil.readClassName(source);
        } catch (Exception e) {
            System.err.println("Failed to parse " + source + ": " + e.getMessage());
            return;
        }

        System.err.println("Considering " + name + "...");

        try {
            // in order for annotations to work, this task and all the classes it uses must be
            // loaded from the same class loader as the classes on which we are going to
            // introspect; this is non-ideal but unavoidable
            processClass(source, getClass().getClassLoader().loadClass(name));
        } catch (ClassNotFoundException cnfe) {
            System.err.println("Failed to load " + name + ".\nMissing class: " + cnfe.getMessage());
            System.err.println("Be sure to set the 'classpathref' attribute to a classpath\n" +
                               "that contains your projects invocation service classes.");
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }

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


Question:
Parses the command-line arguments and runs the executable
 @return [String] The short url or argument passed

def parse
      opts = OptionParser.new(&method(:set_options))
      opts.parse!(@args)
      return process_url if url_present?
      opts.help
    end

func (c *configCommand) handleZeroArgs() error {
	// If reset is empty we're getting configuration
	if len(c.reset) == 0 {
		c.action = c.getConfig
	}
	// Otherwise we're going to reset args.
	return nil
}

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


Question:
// Whether the snapshot has loaded the reader key masks and key generations we
// need.

func (l *TeamLoader) satisfiesNeedApplicationsAtGenerations(ctx context.Context,
	needApplicationsAtGenerations map[keybase1.PerTeamKeyGeneration][]keybase1.TeamApplication, state *keybase1.TeamData) error {
	if len(needApplicationsAtGenerations) == 0 {
		return nil
	}
	if state == nil {
		return fmt.Errorf("nil team does not contain applications: %v", needApplicationsAtGenerations)
	}
	for ptkGen, apps := range needApplicationsAtGenerations {
		for _, app := range apps {
			if _, err := ApplicationKeyAtGeneration(libkb.NewMetaContext(ctx, l.G()), state, app, ptkGen); err != nil {
				return err
			}
		}
	}
	return nil
}

def verifyInputs(self):

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

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


Question: Executor for `globus endpoint role show`

def role_create(role, principal, endpoint_id):

    principal_type, principal_val = principal

    client = get_client()

    if principal_type == "identity":
        principal_val = maybe_lookup_identity_id(principal_val)
        if not principal_val:
            raise click.UsageError(
                "Identity does not exist. "
                "Use --provision-identity to auto-provision an identity."
            )
    elif principal_type == "provision-identity":
        principal_val = maybe_lookup_identity_id(principal_val, provision=True)
        principal_type = "identity"

    role_doc = assemble_generic_doc(
        "role", principal_type=principal_type, principal=principal_val, role=role
    )

    res = client.add_endpoint_role(endpoint_id, role_doc)
    formatted_print(res, simple_text="ID: {}".format(res["id"]))

def execution_cls(self):

        name = self.campaign.process.type
        for clazz in [ExecutionDriver, SrunExecutionDriver]:
            if name == clazz.name:
                return clazz
        raise NameError("Unknown execution layer: '%s'" % name)

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


Question:
Generate a seo for the page using the current entity.

@param Page   $page
@param Entity $entity

public function updateSeoByEntity(BasePage $page, $entity)
    {
        //if no entity is provided
        if ($entity === null) {
            //we look for the entity of the page
            if ($page->getBusinessEntity() !== null) {
                $entity = $page->getBusinessEntity();
            }
        }

        //only if we have an entity instance
        if ($entity !== null) {
            //the page seo
            $pageSeo = $page->getSeo();

            //the page seo might not exist yet
            if ($pageSeo !== null) {
                $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);

                if ($businessEntity !== null) {
                    $businessProperties = $businessEntity->getBusinessPropertiesByType('seoable');

                    //parse the business properties
                    foreach ($businessProperties as $businessProperty) {
                        //parse of seo attributes
                        foreach ($this->pageSeoAttributes as $seoAttribute) {
                            $value = $this->getEntityAttributeValue($pageSeo, $seoAttribute);
                            // we only update value if its a string and (if its a VBP or its a BP where value is not defined)
                            if (is_string($value) && ($page instanceof VirtualBusinessPage || ($page instanceof BusinessPage && $value == null))) {
                                $value = $this->parameterConverter->setBusinessPropertyInstance(
                                    $value,
                                    $businessProperty,
                                    $entity
                                );
                            }
                            $this->setEntityAttributeValue($pageSeo, $seoAttribute, $value);
                        }
                    }
                }
            }
        }
    }

public final String evaluate(final Map<String, Object> pReqVars,
    final IRequestData pData) throws Exception {
    SeSeller seSeller = this.findSeSeller.find(pReqVars, pData.getUserName());
    if (seSeller == null) {
      throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
        "It's not S.E.Seller - " + pData.getUserName());
    }
    String nmEnt = pData.getParameter("nmEnt");
    boolean isSe = false;
    for (Class<?> cl : this.seEntities) {
      if (cl.getSimpleName().equals(nmEnt)) {
        isSe = true;
        break;
      }
    }
    if (isSe) {
      //simple-hummer implementation:
      String wheSe;
      if (nmEnt.startsWith("I18n")) {
        wheSe = "HASNAME.SELLER=";
      } else if (nmEnt.endsWith("Price") || nmEnt.endsWith("Place")
        || nmEnt.endsWith("Specifics")) {
        wheSe = "ITEM.SELLER=";
      } else if (nmEnt.equals("CuOrSe")) {
        wheSe = "CUORSE.SEL=";
      } else { //good/service/paymd
        wheSe = nmEnt.toUpperCase() + ".SELLER=";
      }
      return wheSe + seSeller.getItsId().getItsId();
    } else {
      return null;
    }
  }

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


Question:
@param          $id
@param callable $closure

@return mixed

protected static function getOrInit($id, Closure $closure)
  {
    if (!self::has($id)) {
      self::set($id, $closure());
    }

    return self::get($id);
  }

def get_routing_tuples(cls):
        ''''''
        for callback in cls.callbacks:
            ep_name = '{}.{}'.format(cls.api.__name__, callback.__name__)
            yield (Rule(cls.endpoint_path,
                        endpoint=ep_name,
                        methods=callback.swagger_ops),
                   callback)

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


Question: // SetDeploymentId sets the DeploymentId field's value.

func (s *DeleteDeploymentInput) SetDeploymentId(v string) *DeleteDeploymentInput {
	s.DeploymentId = &v
	return s
}

public S idColumnName(String idColumnName) {
      attributes.attribute(ID_COLUMN_NAME).set(idColumnName);
      return self();
   }

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


Question:
Sets the Collectors associated with this profiler.

@param DataCollectorInterface[] $collectors An array of collectors

public function set(array $collectors = [])
    {
        $this->collectors = [];
        foreach ($collectors as $collector) {
            $this->add($collector);
        }
    }

func NewFilteredDynamicInformer(client dynamic.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer {
	return &dynamicInformer{
		gvr: gvr,
		informer: cache.NewSharedIndexInformer(
			&cache.ListWatch{
				ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
					if tweakListOptions != nil {
						tweakListOptions(&options)
					}
					return client.Resource(gvr).Namespace(namespace).List(options)
				},
				WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
					if tweakListOptions != nil {
						tweakListOptions(&options)
					}
					return client.Resource(gvr).Namespace(namespace).Watch(options)
				},
			},
			&unstructured.Unstructured{},
			resyncPeriod,
			indexers,
		),
	}
}

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


Question: cleans up if appropriate

public void doFinally() {
        try {
            // If we exposed a Reader in doStartTag(), close it.
            if (varReader != null) {
                // 'r' can be null if an exception was thrown...
                if (r != null) {
                    r.close();
                }
                pageContext.removeAttribute(varReader, PageContext.PAGE_SCOPE);
            }
        } catch (IOException ex) {
            // ignore it; close() failed, but there's nothing more we can do
        }
    }

func New(deps *deps.Deps) *Namespace {
	cache := &partialCache{p: make(map[string]interface{})}
	deps.BuildStartListeners.Add(
		func() {
			cache.clear()
		})

	return &Namespace{
		deps:           deps,
		cachedPartials: cache,
	}
}

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


Question:
Export the given reflected method definition to the provided parent element.

@param \DOMElement      $parent Element to augment.
@param MethodDescriptor $method Element to export.

@return \DOMElement

public function convert(\DOMElement $parent, MethodDescriptor $method)
    {
        $fullyQualifiedNamespaceName = $method->getNamespace() instanceof NamespaceDescriptor
            ? $method->getNamespace()->getFullyQualifiedStructuralElementName()
            : $parent->getAttribute('namespace');

        $child = new \DOMElement('method');
        $parent->appendChild($child);

        $child->setAttribute('final', var_export($method->isFinal(), true));
        $child->setAttribute('abstract', var_export($method->isAbstract(), true));
        $child->setAttribute('static', var_export($method->isStatic(), true));
        $child->setAttribute('visibility', $method->getVisibility());
        $child->setAttribute('namespace', $fullyQualifiedNamespaceName);
        $child->setAttribute('line', (string) $method->getLine());

        $child->appendChild(new \DOMElement('name', $method->getName()));
        $child->appendChild(new \DOMElement('full_name', $method->getFullyQualifiedStructuralElementName()));

        $this->docBlockConverter->convert($child, $method);

        foreach ($method->getArguments() as $argument) {
            $this->argumentConverter->convert($child, $argument);
        }

        return $child;
    }

private function load_command_config_file($file, $prefix) {

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

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

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

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

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

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

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

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


Question:
fetch the image size definition for this preview image
Note: we provide a separate method for this (instead of using GetLookup) because we want
to make sure that these objects are properly cached.

@return TdbShopArticleImageSize

public function &GetImageSizeObject()
    {
        if (is_null($this->oImageSize)) {
            $this->oImageSize = TdbShopArticleImageSize::GetNewInstance();
            if (!$this->oImageSize->Load($this->sqlData['shop_article_image_size_id'])) {
                $this->oImageSize = null;
            }
        }

        return $this->oImageSize;
    }

func New(caption string, border Border, datagetter DataGetter) *Table {
	return &Table{
		caption:       caption,
		border:        border,
		dataget:       datagetter,
		VisibleHeader: true,
	}
}

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


Question: The name of the database column used to store the keys

public S idColumnName(String idColumnName) {
      attributes.attribute(ID_COLUMN_NAME).set(idColumnName);
      return self();
   }

protected function getColumnIndexByValue(string $value, string $error_message): string
    {
        if (false !== array_search($value, $this->header, true)) {
            return $value;
        }

        throw new Exception(sprintf($error_message, $value));
    }

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


Question:
Choix du fichier pour un export.

@return File
@param table
JTable
@param extension
String
@throws IOException
Erreur disque

protected File chooseFile(final JTable table, final String extension) throws IOException {
		final JFileChooser myFileChooser = getFileChooser();

		final MExtensionFileFilter filter = new MExtensionFileFilter(extension);
		myFileChooser.addChoosableFileFilter(filter);

		String title = buildTitle(table);
		if (title != null) {
			// on remplace par des espaces les caractères interdits dans les noms de fichiers : \ / : * ? " < > |
			final String notAllowed = "\\/:*?\"<>|";
			final int notAllowedLength = notAllowed.length();
			for (int i = 0; i < notAllowedLength; i++) {
				title = title.replace(notAllowed.charAt(i), ' ');
			}
			myFileChooser.setSelectedFile(new File(title));
		}
		// l'extension sera ajoutée ci-dessous au nom du fichier

		try {
			final Component parent = table.getParent() != null ? table.getParent() : table;
			if (myFileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
				String fileName = myFileChooser.getSelectedFile().getCanonicalPath();
				if (!fileName.endsWith('.' + extension)) {
					fileName += '.' + extension; // NOPMD
				}

				return new File(fileName);
			}
			return null;
		} finally {
			myFileChooser.removeChoosableFileFilter(filter);
		}
	}

def do_format(self, format):

        fmt = ('jpg' if (format is None) else format)
        if (fmt == 'png'):
            self.logger.debug("format: png")
            self.mime_type = "image/png"
            self.output_format = fmt
            format = 'png'
        elif (fmt == 'jpg'):
            self.logger.debug("format: jpg")
            self.mime_type = "image/jpeg"
            self.output_format = fmt
            format = 'jpeg'
        elif (fmt == 'webp'):
            self.logger.debug("format: webp")
            self.mime_type = "image/webp"
            self.output_format = fmt
            format = 'webp'
        else:
            raise IIIFError(code=415, parameter='format',
                            text="Unsupported output file format (%s), only png,jpg,webp are supported." % (fmt))
        if (self.outfile is None):
            # Create temp
            f = tempfile.NamedTemporaryFile(delete=False)
            self.outfile = f.name
            self.outtmp = f.name
            self.image.save(f, format=format)
        else:
            # Save to specified location
            self.image.save(self.outfile, format=format)

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


Question:
// Args returns slice of arguments that was passed to the composer
// or to any child.

func (c *Composer) Args() []interface{} {
	if len(c.childs) == 0 {
		return c.arguments
	}

	args := make([]interface{}, 0, c.lenWithChilds())
	args = append(args, c.arguments...)
	for _, ch := range c.childs {
		args = append(args, ch.arguments...)
	}

	return args
}

public function endingTask()
    {
        $this->alert("Successfully Create ".$this->vendor.'/'.$this->package." Package");
        $this->comment(str_repeat('*', 65));
        $this->comment('  Package: '.$this->package);
        $this->output->writeln('');
        $this->line('  Namespace: '.htmlentities($this->namespace));
        $this->output->writeln('');
        $this->comment('  Path Location: '.$this->path);
        $this->comment(str_repeat('*', 65));
        $this->output->writeln('');
        $this->alert("Run: composer dump-autoload");
    }

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


Question:
Gather data about a given file.

    Returns a dict with fields name, mtime and size, containing the relevant
    data for the fiel.

def gather_file_data(name):

    res = {'name': name}
    try:
        res['mtime'] = osp.getmtime(name)
        res['size'] = osp.getsize(name)
    except OSError:
        pass
    return res

def char(self, char):

        font_files = fc.query()
        if self._display['group']:
            font_files = self._getCharFont(font_files, char)
            font_families = self._groupFontByFamily(font_files)
            for font_family in sorted(font_families):
                print(font_family)
                if self._display['list']:
                    for font_file in font_families[font_family]:
                        print('  '+font_file)
            self._fontSummary(len(font_files), len(font_families))
        else:
            font_files = self._getCharFont(font_files, char)
            for font_file in sorted(font_files):
                print(font_file)
            self._fontSummary(len(font_files))

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


Question:
Records that we'd like to add {@code $inject} property inferred from
parameters.

public boolean recordNgInject(boolean ngInject) {
    if (!isNgInjectRecorded()) {
      currentInfo.setNgInject(ngInject);
      populated = true;
      return true;
    } else {
      return false;
    }
  }

def direct_create_statement(query_params={},impressionable=nil)
      query_params.reverse_merge!(
        :impressionable_type => controller_name.singularize.camelize,
        :impressionable_id => impressionable.present? ? impressionable.id : params[:id]
        )
      associative_create_statement(query_params)
    end

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


Question: Remove all files and directories in supplied root directory.

def remove_files(root_dir):

    for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
        for filename in filenames:
            os.remove(os.path.join(root_dir, filename))

        for dirname in dirnames:
            shutil.rmtree(os.path.join(root_dir, dirname))

public function getPath()
    {
        $path = parent::getPath();
        if ('' == $path)
        {
            $path = '/';
        }
        if ($this->siteRoot)
        {
            $path = substr($path, strlen($this->siteRoot));
        }
        return $path;
    }

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


Question: This is the cache which we store all key-value pairs.

private InternalQueryCache createUnderlyingQueryCache(QueryCacheConfig queryCacheConfig,
                                                          QueryCacheRequest request,
                                                          String cacheId) {
        SubscriberContext subscriberContext = context.getSubscriberContext();
        QueryCacheFactory queryCacheFactory = subscriberContext.getQueryCacheFactory();
        request.withQueryCacheConfig(queryCacheConfig);
        return queryCacheFactory.create(request, cacheId);
    }

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

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


Question:
Encode contents into RAW string.

@param array $var
@return string

protected function encode($var)
    {
        // Create Markdown file with YAML header.
        $o = (!empty($var['header']) ? "---\n" . trim(YamlParser::dump($var['header'], 20)) . "\n---\n\n" : '') . $var['markdown'];

        // Normalize line endings to Unix style.
        $o = preg_replace("/(\r\n|\r)/", "\n", $o);

        return $o;
    }

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

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


Question:
// See cairo_region_intersect().
//
// C API documentation: http://cairographics.org/manual/cairo-Regions.html#cairo-region-intersect

func (dst *Region) Intersect(other *Region) error {
	ret := Status(C.cairo_region_intersect(dst.Ptr, other.Ptr)).toError()
	if err := dst.status(); err != nil {
		panic(err)
	}
	return ret
}

def process(event, watch_type = nil)
      @zk.raw_event_handler(event)

      logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1
      event.zk = @zk

      cb_keys =
        if event.node_event?
          [event.path, ALL_NODE_EVENTS_KEY]
        elsif event.session_event?
          [state_key(event.state), ALL_STATE_EVENTS_KEY]
        else
          raise ZKError, "don't know how to process event: #{event.inspect}"
        end

      cb_ary = synchronize do
        clear_watch_restrictions(event, watch_type)

        @callbacks.values_at(*cb_keys)
      end

      cb_ary.flatten! # takes care of not modifying original arrays
      cb_ary.compact!

      # we only filter for node events
      if event.node_event?
        interest_key = event.interest_key
        cb_ary.select! { |sub| sub.interests.include?(interest_key) }
      end

      safe_call(cb_ary, event)
    end

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


Question:
Make the authorization service instance.

@return \League\OAuth2\Server\AuthorizationServer

public function makeAuthorizationServer()
    {
        return new AuthorizationServer(
            $this->app->make(Bridge\ClientRepository::class),
            $this->app->make(Bridge\AccessTokenRepository::class),
            $this->app->make(Bridge\ScopeRepository::class),
            $this->makeCryptKey('private'),
            app('encrypter')->getKey()
        );
    }

function(realm, key, ssl) {

    // Initialize with a specified realm, key, and a boolean indicating wther
    // SSL should be enabled or disabled.
    var scheme = 'https';
    if (typeof ssl !== 'undefined' && !ssl) {
        scheme = 'http';
    }
    var uri = scheme + '://api.fanout.io/realm/' + realm;
    var pubControl = new pubcontrol.PubControlClient(uri);
    pubControl.setAuthJwt({'iss': realm}, new Buffer(key, 'base64'));
    this.pubControl = pubControl;
}

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


Question:
validateContainer

@param $container
@return array

private function validateContainer($container)
    {
        if ($container === false)
            return $container;
        $resolver = new OptionsResolver();
        $resolver->setDefaults([
            'panel' => false,
            'class' => false,
            'rows' => false,
            'headerRow' => false,
            'collection' => false,
        ]);
        $resolver->setAllowedTypes('class', ['string', 'boolean']);
        $resolver->setAllowedTypes('panel', ['array', 'boolean']);
        $resolver->setAllowedTypes('rows', ['array', 'boolean']);
        $resolver->setAllowedTypes('headerRow', ['array', 'boolean']);
        $resolver->setAllowedTypes('collection', ['array', 'boolean']);
        $container = $resolver->resolve($container);

        $container['panel'] = $this->validatePanel($container['panel']);

        if (($container['panel'] !== false && $container['class'] !== false) || ( $container['panel'] === false && $container['class'] === false))
            trigger_error(sprintf('Containers must specify one of a panel (%s) or a class (%s), but not both.', $container['panel']['colour'], $container['class']), E_USER_ERROR);

        $container['collection'] = $this->validateCollection($container['collection']);

        $container['headerRow'] = $this->validateRow($container['headerRow']);
        $container['rows'] = $this->validateRows($container['rows']);

        return $container;
    }

public function addCalculator(string $name, string $validation): void{
        $this->calculators[$name] = $validation;
    }

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


Question:
Represents the type mirror as a string in such a way that it can be used for equality comparisons.

@param t type to convert to string
@return the string representation of the type that is fit for equality comparisons

@Nonnull
    public static String toUniqueString(@Nonnull TypeMirror t) {
        StringBuilderAndState<TypeMirror> state = new StringBuilderAndState<>();
        t.accept(toUniqueStringVisitor, state);
        return state.bld.toString();
    }

public static Result convert(final Object res) throws QConnectorException {
		if (res == null) {
			return new EmptyResult();
		}
		// table
		if (res instanceof c.Flip) {
			return new FlipResult("", (c.Flip) res);
		}
		// dict
		if (res instanceof c.Dict) {
			final c.Dict dict = (c.Dict) res;
			if ((dict.x instanceof c.Flip) && (dict.y instanceof c.Flip)) {
				final c.Flip key = (c.Flip) dict.x;
				final c.Flip data = (c.Flip) dict.y;
				return new FlipFlipResult("", key, data);
			}
		}
		if (res instanceof Object[]) {
			final Object[] oa = (Object[]) res;
			if ((oa.length == 2) && (oa[0] instanceof String) && (oa[1] instanceof c.Flip)) {
				final String table = (String) oa[0];
				final c.Flip flip = (c.Flip) oa[1];
				return new FlipResult(table, flip);
			} else if ((oa.length == 3) && (oa[1] instanceof String) && (oa[2] instanceof c.Flip)) {
				final String table = (String) oa[1];
				final c.Flip flip = (c.Flip) oa[2];
				return new FlipResult(table, flip);
			} else {
				return new ListResult<Object>(oa);
			}
		}
		// list
		if (res instanceof byte[]) {
			return new ListResult<Byte>(ArrayUtils.toObject((byte[]) res));
		}

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


Question:
Delete a module from Grapes server

@param name
@param version
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException

public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{
        final Client client = getClient(user, password);
        final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));
        final ClientResponse response = resource.delete(ClientResponse.class);

        client.destroy();
        if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
            final String message = String.format(FAILED_TO_GET_MODULE, "to delete module", name, version);

            if(LOG.isErrorEnabled()) {
                LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
            }
            throw new GrapesCommunicationException(message, response.getStatus());
        }
    }

func (u *Client) RevokeToken(accessToken string) error {
	segments := strings.Split(accessToken, ".")

	if len(segments) < 2 {
		return errors.New("access token missing segments")
	}

	jsonPayload, err := base64.RawURLEncoding.DecodeString(segments[1])

	if err != nil {
		return errors.New("could not base64 decode token payload")
	}

	payload := make(map[string]interface{})
	json.Unmarshal(jsonPayload, &payload)
	jti, ok := payload["jti"].(string)

	if !ok {
		return errors.New("could not parse jti from payload")
	}

	request, err := http.NewRequest(http.MethodDelete, u.AuthURL+"/oauth/token/revoke/"+jti, nil)
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+accessToken)
	resp, err := u.Client.Do(request)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= http.StatusBadRequest {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		return fmt.Errorf("Received HTTP %d error while revoking token from auth server: %q", resp.StatusCode, body)
	}

	return nil
}

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


Question:
Sets a rounded image with a given image mode to the drawer item

@param image     Image to set
@param imageMode Image mode to set

public DrawerItem setRoundedImage(BitmapDrawable image, int imageMode) {
        return setImage(new RoundedAvatarDrawable(image.getBitmap()), imageMode);
    }

public function set_model( $model )
    {
        // Check that the required arguments are provided.
        foreach( $this->required_arguments() as $key )
        {
            if ( !isset($model[$key]) )
            {
                throw new \RuntimeException('The required argument "'.$key.'" was not provided for '.get_called_class());
            }
        }

        // Assign the name of the component as the id if no id was specified
        if( !isset($model['id']) && isset($model['name']) )
        {
            $model['id'] = $model['name'];
        }

        // A name must be specified when a component has a visibility condition
        if( isset($model['show']) && !isset($model['name']) )
        {
            throw new \RuntimeException('Components with a visibility condition (a "show" argument) must have a name');
        }

        $this->model = array_merge( $this->default_model(), $model );
    }

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


Question: Use this API to fetch dnszone_binding resource of given name .

public static dnszone_binding get(nitro_service service, String zonename) throws Exception{
		dnszone_binding obj = new dnszone_binding();
		obj.set_zonename(zonename);
		dnszone_binding response = (dnszone_binding) obj.get_resource(service);
		return response;
	}

func NewProductPrivateHostAPI(client *Client) *ProductPrivateHostAPI {
	return &ProductPrivateHostAPI{
		&baseAPI{
			client: client,
			// FuncGetResourceURL
			FuncGetResourceURL: func() string {
				return "product/privatehost"
			},
		},
	}
}

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


Question:
Register event.

@param string   $event    event name
@param string   $listener listener name
@param \Closure $callback call when fire

@return string|int

public function register($event, $listener, \Closure $callback)
    {
        if (!isset($this->events[$event])) {
            $this->events[$event] = [];
        }

        if ($listener) {
            $this->events[$event][$listener] = $callback;
        } else {
            $this->events[$event][] = $callback;
            $keys = array_keys($this->events[$event]);
            $listener = array_pop($keys);
        }

        return $listener;
    }

func (c *Client) newRequest(method string, args *dnode.Partial) (*Request, func(interface{}, *Error)) {
	// Parse dnode method arguments: [options]
	var options callOptions
	args.One().MustUnmarshal(&options)

	// Notify the handlers registered with Kite.OnFirstRequest().
	if _, ok := c.session.(*sockjsclient.WebsocketSession); !ok {
		c.firstRequestHandlersNotified.Do(func() {
			c.m.Lock()
			c.Kite = options.Kite
			c.m.Unlock()
			c.LocalKite.callOnFirstRequestHandlers(c)
		})
	}

	request := &Request{
		ID:        utils.RandomString(16),
		Method:    method,
		Args:      options.WithArgs,
		LocalKite: c.LocalKite,
		Client:    c,
		Auth:      options.Auth,
		Context:   c.context(),
	}

	// Call response callback function, send back our response
	callFunc := func(result interface{}, err *Error) {
		if options.ResponseCallback.Caller == nil {
			return
		}

		// Only argument to the callback.
		response := Response{
			Result: result,
			Error:  err,
		}

		if err := options.ResponseCallback.Call(response); err != nil {
			c.LocalKite.Log.Error(err.Error())
		}
	}

	return request, callFunc
}

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


Question:
Returns true if this provider has been setup correctly, the error message if
otherwise.

@return bool|string

public function isWorking()
    {
        if (!function_exists('mb_internal_encoding')) {
            return Piwik::translate('UserCountry_GeoIPCannotFindMbstringExtension',
                array('mb_internal_encoding', 'mbstring'));
        }

        $geoIpError = false;
        $catchGeoIpError = function ($errno, $errstr, $errfile, $errline) use (&$geoIpError) {
            $filename = basename($errfile);
            if ($filename == 'geoip.inc'
                || $filename == 'geoipcity.inc'
            ) {
                $geoIpError = array($errno, $errstr, $errfile, $errline);
            } else {
                throw new \Exception("Error in PHP GeoIP provider: $errstr on line $errline of $errfile"); // unexpected
            }
        };

        // catch GeoIP errors
        set_error_handler($catchGeoIpError);
        $result = parent::isWorking();
        restore_error_handler();

        if ($geoIpError) {
            list($errno, $errstr, $errfile, $errline) = $geoIpError;
            Log::warning("Got GeoIP error when testing PHP GeoIP location provider: %s(%s): %s", $errfile, $errline, $errstr);

            return Piwik::translate('UserCountry_GeoIPIncorrectDatabaseFormat');
        }

        return $result;
    }

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:
Remove all entries in the i2b2 tables for uploadid.
    :param tables:
    :param uploadid:
    :return:

def clear_i2b2_tables(tables: I2B2Tables, uploadid: int) -> None:

    # This is a static function to support the removefacts operation
    print("Deleted {} patient_dimension records"
          .format(PatientDimension.delete_upload_id(tables, uploadid)))
    print("Deleted {} patient_mapping records"
          .format(PatientMapping.delete_upload_id(tables, uploadid)))
    print("Deleted {} observation_fact records"
          .format(ObservationFact.delete_upload_id(tables, uploadid)))
    print("Deleted {} visit_dimension records"
          .format(VisitDimension.delete_upload_id(tables, uploadid)))
    print("Deleted {} encounter_mapping records"
          .format(EncounterMapping.delete_upload_id(tables, uploadid)))

public function updateTemplate()
    {
        $codeDb = $validationCode = $form = '';

        $form = $this->buildFormOpen();

        foreach ($this->columns as $key => $value) {
            if ($value['COLUMN_NAME'] !== 'id') {
                if ($this->isFormGenerator == false) {
                    $codeDb .= $this->generateDbCode($value);
                }

                $form .= $this->generateFormElements($value);
            }
        }

        $form .= $this->buildFormCloseTags();

        $this->setForm($form);
        $this->setDbCode($codeDb);
    }

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


Question:
/* CONSTRUCTOR
***********************************************************************

public function initBySetting($model, $setting)
    {
        parent::initBySetting($model, $setting);
        if (is_array($setting)) {
            if (isset($setting['remote_class_type'])) {
                $this->remoteModelType = $setting['remote_class_type'];
            }
        }
    }

public function alert($string)
    {
        $length = Str::length(strip_tags($string)) + 12;

        $this->comment(str_repeat('*', $length));
        $this->comment('*     '.$string.'     *');
        $this->comment(str_repeat('*', $length));

        $this->output->newLine();
    }

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


Question:
Create prepped reference directory for pisces.

    Requires a custom GenomeSize.xml file present.

def _prep_genome(out_dir, data):

    genome_name = utils.splitext_plus(os.path.basename(dd.get_ref_file(data)))[0]
    out_dir = utils.safe_makedir(os.path.join(out_dir, genome_name))
    ref_file = dd.get_ref_file(data)
    utils.symlink_plus(ref_file, os.path.join(out_dir, os.path.basename(ref_file)))
    with open(os.path.join(out_dir, "GenomeSize.xml"), "w") as out_handle:
        out_handle.write('<sequenceSizes genomeName="%s">' % genome_name)
        for c in pysam.AlignmentFile("%s.dict" % utils.splitext_plus(ref_file)[0]).header["SQ"]:
            cur_ploidy = ploidy.get_ploidy([data], region=[c["SN"]])
            out_handle.write('<chromosome fileName="%s" contigName="%s" totalBases="%s" knownBases="%s" '
                             'isCircular="false" ploidy="%s" md5="%s"/>' %
                             (os.path.basename(ref_file), c["SN"], c["LN"], c["LN"], cur_ploidy, c["M5"]))
        out_handle.write('</sequenceSizes>')
    return out_dir

def plot_mv_storage_integration(self, **kwargs):

        if self.network.pypsa is not None:
            plots.mv_grid_topology(
                self.network.pypsa, self.network.config,
                node_color='storage_integration',
                filename=kwargs.get('filename', None),
                grid_district_geom=kwargs.get('grid_district_geom', True),
                background_map=kwargs.get('background_map', True),
                xlim=kwargs.get('xlim', None), ylim=kwargs.get('ylim', None),
                title=kwargs.get('title', ''))
        else:
            if self.network.pypsa is None:
                logging.warning("pypsa representation of MV grid needed to "
                                "plot storage integration in MV grid.")

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


Question:
Split ``version`` into a lexicographically comparable tuple.

    "1.0.3" -> ((1, 0, 3),)
    "1.0.3-dev" -> ((1, 0, 3), ("dev",))
    "1.0.3-rc-5" -> ((1, 0, 3), ("rc",), (5,))

def tupleize_version(version):

    if version is None:
        return (("unknown",),)

    if version.startswith("<unknown"):
        return (("unknown",),)

    split = re.split("(?:\.|(-))", version)
    parsed = tuple(try_fix_num(x) for x in split if x)

    # Put the tuples in groups by "-"
    def is_dash(s):
        return s == "-"
    grouped = groupby(parsed, is_dash)

    return tuple(tuple(group) for dash, group in grouped if not dash)

def release_ids(self):

        r = [(k, self._releases[k][0]['upload_time'])
             for k in self._releases.keys()
             if len(self._releases[k]) > 0]
        return [k[0] for k in sorted(r, key=lambda k: k[1])]

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


Question:
Get or create the extension, non-linear geometry type

@param tableName
table name
@param columnName
column name
@param geometryType
geometry type
@return extension
@since 1.1.8

public Extensions getOrCreate(String tableName, String columnName,
			GeometryType geometryType) {

		String extensionName = getExtensionName(geometryType);
		Extensions extension = getOrCreate(extensionName, tableName,
				columnName, GEOMETRY_TYPES_EXTENSION_DEFINITION,
				ExtensionScopeType.READ_WRITE);

		return extension;
	}

func (fc FeatureCollection) MarshalJSON() ([]byte, error) {
	type featureCollection FeatureCollection

	fcol := &featureCollection{
		Type: "FeatureCollection",
	}

	if fc.BoundingBox != nil && len(fc.BoundingBox) != 0 {
		fcol.BoundingBox = fc.BoundingBox
	}

	fcol.Features = fc.Features
	if fcol.Features == nil {
		fcol.Features = make([]*Feature, 0) // GeoJSON requires the feature attribute to be at least []
	}

	if fc.CRS != nil && len(fc.CRS) != 0 {
		fcol.CRS = fc.CRS
	}

	return json.Marshal(fcol)
}

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


Question: // Add state handlers for state

func (s *State) SetActions(e, l Action) {
	s.Enter = e
	s.Leave = l
}

public static <S extends HasAttachHandlers> void fire(S source, PageState pageState,
            JQMPage prevPage, JQMPage nextPage) {
      if (TYPE != null) {
        JQMPageEvent event = new JQMPageEvent(pageState, prevPage, nextPage);
        source.fireEvent(event);
      }
    }

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


Question:
Wraps a stream to make it seekable

@param resource $source
@param string $hash
@param callable $callback
@return resource|bool

@throws \BadMethodCallException

public static function wrap($source, $hash, $callback) {
		$context = [
			'hash' => $hash,
			'callback' => $callback,
		];
		return self::wrapSource($source, $context);
	}

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

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


Question:
Trashes a RedBean OODBBean and removes it from cache.

@param RedBean_OODBBean $bean bean
@return mixed

public function trash( $bean ) {
		$type = $bean->getMeta('type');
		$id = $bean->id;
		if (isset($this->cache[$type][$id])) unset($this->cache[$type][$id]);
		return parent::trash($bean);
	}

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question:
根据路径设置值

@param path 路径语法
@param value 值对象

@return 是否设置成功

public boolean set(String path, Object value) {
        jsonStore.clear();
        return JSONPath.set(jsonObject, checkPath(path), value);
    }

func ConvertWorkItemLinkTypeFromModel(request *http.Request, modelLinkType link.WorkItemLinkType) app.WorkItemLinkTypeSingle {
	spaceTemplateRelatedURL := rest.AbsoluteURL(request, app.SpaceTemplateHref(modelLinkType.SpaceTemplateID.String()))
	spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(space.SystemSpace.String()))

	topologyStr := modelLinkType.Topology.String()
	var converted = app.WorkItemLinkTypeSingle{
		Data: &app.WorkItemLinkTypeData{
			Type: link.EndpointWorkItemLinkTypes,
			ID:   &modelLinkType.ID,
			Attributes: &app.WorkItemLinkTypeAttributes{
				Name:               &modelLinkType.Name,
				Description:        modelLinkType.Description,
				Version:            &modelLinkType.Version,
				CreatedAt:          &modelLinkType.CreatedAt,
				UpdatedAt:          &modelLinkType.UpdatedAt,
				ForwardName:        &modelLinkType.ForwardName,
				ForwardDescription: modelLinkType.ForwardDescription,
				ReverseName:        &modelLinkType.ReverseName,
				ReverseDescription: modelLinkType.ReverseDescription,
				Topology:           &topologyStr,
			},
			Relationships: &app.WorkItemLinkTypeRelationships{
				Space:         app.NewSpaceRelation(space.SystemSpace, spaceRelatedURL),
				SpaceTemplate: app.NewSpaceTemplateRelation(modelLinkType.SpaceTemplateID, spaceTemplateRelatedURL),
			},
		},
	}
	return converted
}

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


Question:
Adds the function declaration for a boolean accessor.

@param string &$script
@param Column $column

public function addBooleanAccessorOpen(&$script, Column $column)
    {
        $name = self::getBooleanAccessorName($column);
        $visibility = $column->getAccessorVisibility();

        $script .= "
    ".$visibility." function $name(";
        if ($column->isLazyLoad()) {
            $script .= "ConnectionInterface \$con = null";
        }

        $script .= ")
    {";
    }

func (bf *Filter) maybeAddOutpoint(pkScript []byte, outHash *chainhash.Hash, outIdx uint32) {
	switch bf.msgFilterLoad.Flags {
	case wire.BloomUpdateAll:
		outpoint := wire.NewOutPoint(outHash, outIdx)
		bf.addOutPoint(outpoint)
	case wire.BloomUpdateP2PubkeyOnly:
		class := txscript.GetScriptClass(pkScript)
		if class == txscript.PubKeyTy || class == txscript.MultiSigTy {
			outpoint := wire.NewOutPoint(outHash, outIdx)
			bf.addOutPoint(outpoint)
		}
	}
}

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


Question: // SetFulfillmentActivity sets the FulfillmentActivity field's value.

func (s *GetIntentOutput) SetFulfillmentActivity(v *FulfillmentActivity) *GetIntentOutput {
	s.FulfillmentActivity = v
	return s
}

def activities(self):

        if self._activities is None:
            self.assert_bind_client()
            self._activities = self.bind_client.get_club_activities(self.id)
        return self._activities

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


Question:
The specification of an API endpoint
@param {Object} spec - Swagger/OpenAPI specification of the endpoint
@param {string} resourcePath - path of the endpoint
@param {string} method - HTTP method of the endpoint
@constructor

function Endpoint(spec, resourcePath, method) {
  this.method = method;
  this.resourcePath = resourcePath || '/';
  this.spec = spec;
}

def request(self, method, url, params=None, **aio_kwargs):
        """"""
        oparams = {
            'oauth_consumer_key': self.consumer_key,
            'oauth_nonce': sha1(str(RANDOM()).encode('ascii')).hexdigest(),
            'oauth_signature_method': self.signature.name,
            'oauth_timestamp': str(int(time.time())),
            'oauth_version': self.version,
        }
        oparams.update(params or {})

        if self.oauth_token:
            oparams['oauth_token'] = self.oauth_token

        url = self._get_url(url)

        if urlsplit(url).query:
            raise ValueError(
                'Request parameters should be in the "params" parameter, '
                'not inlined in the URL')

        oparams['oauth_signature'] = self.signature.sign(
            self.consumer_secret, method, url,
            oauth_token_secret=self.oauth_token_secret, **oparams)
        self.logger.debug("%s %s", url, oparams)

        return self._request(method, url, params=oparams, **aio_kwargs)

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


Question: extracted and simplified from Devise

def set_user_in_warden(scope, resource)
      scope = Devise::Mapping.find_scope!(scope)
      warden.set_user(resource, scope: scope, store: false)
    end

public static function export_user_data(approved_contextlist $contextlist) {
        $context = $contextlist->current();
        $user = \core_user::get_user($contextlist->get_user()->id);
        static::export_recentitems($user->id, $context);
    }

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


Question: // LastInsertId returns last inserted ID

func (result *OCI8Result) LastInsertId() (int64, error) {
	return int64(uintptr(unsafe.Pointer(&result.rowid))), result.rowidErr
}

public function getLastToken($type, $key = 'type')
    {
        return $this->token()->orderBy('tokens.created_at', 'desc')->where($key, $type)->first();
    }

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


Question:
Add the requested post parameters to the Request.

@param request Request to add post params to

private void addPostParams(final Request request) {
        if (to != null) {
            request.addPostParam("To", to.toString());
        }

        if (from != null) {
            request.addPostParam("From", from.toString());
        }

        if (parameters != null) {
            request.addPostParam("Parameters", Converter.mapToJson(parameters));
        }
    }

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:
@inheritdoc

@param \Ekyna\Component\Colissimo\Base\Model\Collection $value

public function toArray($value)
    {
        if (empty($value)) {
            return null;
        }

        $output = [];
        foreach ($value as $val) {
            $output[] = $this->field->toArray($val);
        }

        return $output;
    }

def consume(self, routingKey, msg):

        builder_info = yield self.master.data.get(("builders", msg['builderid']))

        if self._builder_name_matches(builder_info):
            properties = yield self.master.data.get(("builds", msg['buildid'], "properties"))

            if self._regex:
                filtered_prop_names = [
                    pn for pn in properties if re.match(self._property_name, pn)]
            else:
                filtered_prop_names = [self._property_name]

            for pn in filtered_prop_names:
                try:
                    ret_val = self._callback(properties, pn)
                except KeyError:
                    raise CaptureCallbackError("CaptureProperty failed."
                                               " The property %s not found for build number %s on"
                                               " builder %s."
                                               % (pn, msg['number'], builder_info['name']))
                context = self._defaultContext(msg, builder_info['name'])
                series_name = "%s-%s" % (builder_info['name'], pn)
                post_data = {
                    "name": pn,
                    "value": ret_val
                }
                yield self._store(post_data, series_name, context)

        else:
            yield defer.succeed(None)

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


Question:
Remove all attributes with the given *name*.

        Raises :exc:`ValueError` if none were found.

def remove(self, name):

        attrs = [attr for attr in self.attributes if attr.name == name.strip()]
        if not attrs:
            raise ValueError(name)
        for attr in attrs:
            self.attributes.remove(attr)

def del_node(self, char, node):
        """"""
        del self._real.character[char].node[node]
        for cache in (
                self._char_nodes_rulebooks_cache,
                self._node_stat_cache,
                self._node_successors_cache
        ):
            try:
                del cache[char][node]
            except KeyError:
                pass
        if char in self._char_nodes_cache and node in self._char_nodes_cache[char]:
            self._char_nodes_cache[char] = self._char_nodes_cache[char] - frozenset([node])
        if char in self._portal_stat_cache:
            portal_stat_cache_char = self._portal_stat_cache[char]
            if node in portal_stat_cache_char:
                del portal_stat_cache_char[node]
            for charo in portal_stat_cache_char.values():
                if node in charo:
                    del charo[node]
        if char in self._char_portals_rulebooks_cache:
            portal_rulebook_cache_char = self._char_portals_rulebooks_cache[char]
            if node in portal_rulebook_cache_char:
                del portal_rulebook_cache_char[node]
            for porto in portal_rulebook_cache_char.values():
                if node in porto:
                    del porto[node]

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


Question:
Shortcut method for reducing law of Demeters issues.

@param index Index of the problem input to retrieve.
@return Problem input instance required.
@throws ArrayIndexOutOfBoundsException If the given index is not valid.

public ProblemInput getProblemInput(final int index) {
		final List<ProblemInput> inputs = getProblemInputs();
		if (index < 0 || inputs.size() <= index) {
			throw new ArrayIndexOutOfBoundsException();
		}
		return inputs.get(index);
	}

public void error(String key, Object ... args) {
        report(diags.error(source, null, key, args));
    }

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


Question:
Get a list of all collected hook api.php files.

@return
A flat array of filenames, relative to the hooks directory. If no files
are present, an empty array is returned.

public function listHookFiles() {
    $directory = $this->environment->getHooksDirectory();

    $files = array();

    // No need to verify $directory; our sanity check has taken care of it.
    $dh = opendir($directory);
    while (($file = readdir($dh)) !== FALSE) {
      // Ignore files that don't make sense to include.
      // System files and cruft.
      // TODO: replace all the .foo with one of the arcane PHP string checking functions
      if (in_array($file, array('.', '..', '.DS_Store', 'CVS', 'hooks_processed.php'))) {
        continue;
      }
      // Our own processed files.
      if (strpos($file, '_processed.php')) {
        continue;
      }

      $files[] = $file;
    }
    closedir($dh);

    return $files;
  }

public static function getFileExtention($path)
    {

        $ext = pathinfo($path, PATHINFO_EXTENSION);

        if($ext === ''){
            $splitedPath = explode('.', $path);
            $ext = end($splitedPath);
        }

        return $ext;
    }

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


Question: // unitName returns the unescaped base element of the supplied escaped path

func unitName(dpath dbus.ObjectPath) string {
	return pathBusUnescape(path.Base(string(dpath)))
}

func QueryUnEscape(str string) string {
	str = strings.Replace(str, "%20", "+", -1)
	str = strings.Replace(str, "%2A", "*", -1)

	encodeString, _ := url.QueryUnescape(str)

	return encodeString
}

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


Question: received a response, but before it cleans up itself, it receives a HazelcastInstanceNotActiveException

private void warnIfSuspiciousDoubleCompletion(Object s0, Object s1) {
        if (s0 != s1 && !(s0 instanceof CancellationException) && !(s1 instanceof CancellationException)) {
            logger.warning(String.format("Future.complete(Object) on completed future. "
                            + "Request: %s, current value: %s, offered value: %s",
                    invocationToString(), s0, s1));
        }
    }

def wait_for_web_available(self):

        try:
            if not wait_for_service_available(
                    self._get_container_name('web'),
                    self.web_address(),
                    WEB_START_TIMEOUT_SECONDS):
                raise DatacatsError('Error while starting web container:\n' +
                                    container_logs(self._get_container_name('web'), "all",
                                                   False, None))
        except ServiceTimeout:
            raise DatacatsError('Timeout while starting web container. Logs:' +
                                container_logs(self._get_container_name('web'), "all", False, None))

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


Question: Create a product

public function createAction()
    {
        $form = $this->container->get('vespolina.product.form');
        $formHandler = $this->container->get('vespolina.product.form.handler');

        $process = $formHandler->process();
        if ($process) {
            $user = $form->getData();

            $this->setFlash('vespolina_product_created', 'success');
            $url = $this->container->get('router')->generate('vespolina_product_list');

            return new RedirectResponse($url);
        }

        return $this->container->get('templating')->renderResponse('VespolinaCommerceBundle:Product:new.html.'.$this->getEngine(), array(
            'form' => $form->createView(),
        ));
    }

public function findOrCreate($conditions, $data = array())
    {
        $this->findOrInit($conditions, $data);
        if ($this->isNew) {
            $this->save();
        }
        return $this;
    }

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


Question:
Register user
@param  [type] $username [description]
@param  [type] $password [description]
@return [type]           [description]

public function register($username, $password)
    {
        $userData = [
            'auth' => [
                'type' => 'm.login.dummy'
            ],
            'bind_email' => false,
            'bind_msisdn' => false,
            'password' => $password,
            'x_show_msisdn' => false
        ];

        if ($username) {
            $userData['username'] = $username;
        }

        $data = $this->matrix()->request('POST', $this->endpoint('register'), $userData, [
            'kind' => 'user'
        ]);
        $this->setData($data);
        return $this->data;
    }

def __add_default_values(self):

        self.__sp.setdefault('assertionConsumerService', {})
        self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST)

        self.__sp.setdefault('attributeConsumingService', {})

        self.__sp.setdefault('singleLogoutService', {})
        self.__sp['singleLogoutService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT)

        # Related to nameID
        self.__sp.setdefault('NameIDFormat', OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED)
        self.__security.setdefault('nameIdEncrypted', False)

        # Metadata format
        self.__security.setdefault('metadataValidUntil', None)  # None means use default
        self.__security.setdefault('metadataCacheDuration', None)  # None means use default

        # Sign provided
        self.__security.setdefault('authnRequestsSigned', False)
        self.__security.setdefault('logoutRequestSigned', False)
        self.__security.setdefault('logoutResponseSigned', False)
        self.__security.setdefault('signMetadata', False)

        # Sign expected
        self.__security.setdefault('wantMessagesSigned', False)
        self.__security.setdefault('wantAssertionsSigned', False)

        # NameID element expected
        self.__security.setdefault('wantNameId', True)

        # SAML responses with a InResponseTo attribute not rejected when requestId not passed
        self.__security.setdefault('rejectUnsolicitedResponsesWithInResponseTo', False)

        # Encrypt expected
        self.__security.setdefault('wantAssertionsEncrypted', False)
        self.__security.setdefault('wantNameIdEncrypted', False)

        # Signature Algorithm
        self.__security.setdefault('signatureAlgorithm', OneLogin_Saml2_Constants.RSA_SHA1)

        # Digest Algorithm
        self.__security.setdefault('digestAlgorithm', OneLogin_Saml2_Constants.SHA1)

        # AttributeStatement required by default
        self.__security.setdefault('wantAttributeStatement', True)

        self.__idp.setdefault('x509cert', '')
        self.__idp.setdefault('certFingerprint', '')
        self.__idp.setdefault('certFingerprintAlgorithm', 'sha1')

        self.__sp.setdefault('x509cert', '')
        self.__sp.setdefault('privateKey', '')

        self.__security.setdefault('requestedAuthnContext', True)
        self.__security.setdefault('failOnAuthnContextMismatch', False)

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


Question: Recursive Create

def create_recursive(path)
      recursive = path.split("/")
      directory = ""
      recursive.each do |sub_directory|
        directory += sub_directory + "/"
        Dir.mkdir("#{directory}") unless (File.directory? directory)
      end
    end

def child(self, name, data, source=None):

        try:
            if isinstance(data, dict):
                self.children[name].update(data)
            else:
                self.children[name].grow(data)
        except KeyError:
            self.children[name] = Tree(data, name, parent=self)
        # Save source file
        if source is not None:
            self.children[name].sources.append(source)

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


Question: Read a color and depth image from the device.

def _read_color_and_depth_image(self):

        frames = self._pipe.wait_for_frames()
        if self._depth_align:
            frames = self._align.process(frames)

        depth_frame = frames.get_depth_frame()
        color_frame = frames.get_color_frame()

        if not depth_frame or not color_frame:
            logging.warning('Could not retrieve frames.')
            return None, None

        if self._filter_depth:
            depth_frame = self._filter_depth_frame(depth_frame)

        # convert to numpy arrays
        depth_image = self._to_numpy(depth_frame, np.float32)
        color_image = self._to_numpy(color_frame, np.uint8)

        # convert depth to meters
        depth_image *= self._depth_scale

        # bgr to rgb
        color_image = color_image[..., ::-1]

        depth = DepthImage(depth_image, frame=self._frame)
        color = ColorImage(color_image, frame=self._frame)
        return color, depth

private function loadEnvironmentReader(ContainerBuilder $container)
    {
        $definition = new Definition('Behat\Behat\Context\Environment\Reader\ContextEnvironmentReader');
        $definition->addTag(EnvironmentExtension::READER_TAG, array('priority' => 50));
        $container->setDefinition(self::getEnvironmentReaderId(), $definition);
    }

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


Question: Perform the inner iteration.

def _iterate_to_update_x_transforms(self):
        """"""
        self._inner_iters = 0
        self._last_inner_error = float('inf')
        while self._inner_error_is_decreasing():
            print('  Starting inner iteration {0:03d}. Current err = {1:12.5E}'
                  ''.format(self._inner_iters, self._last_inner_error))
            self._update_x_transforms()
            self._inner_iters += 1

def _iterPoints(self, **kwargs):

        points = self.points
        count = len(points)
        index = 0
        while count:
            yield points[index]
            count -= 1
            index += 1

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


Question: Splits a BundleOptions object into smaller, more manageable parts.

function splitBundleOptions(options: BundleOptions): SplitBundleOptions {
  return {
    entryFile: options.entryFile,
    transformOptions: {
      customTransformOptions: options.customTransformOptions,
      dev: options.dev,
      hot: options.hot,
      minify: options.minify,
      platform: options.platform,
      type: 'module',
    },
    serializerOptions: {
      sourceMapUrl: options.sourceMapUrl,
      runModule: options.runModule,
      excludeSource: options.excludeSource,
      inlineSourceMap: options.inlineSourceMap,
    },
    onProgress: options.onProgress,
  };
}

public function output($filename, $content)
    {
        if (!class_exists('JShrink\Minifier')) {
            throw new \Exception(sprintf('Cannot not load filter class "%s".', 'JShrink\Minifier'));
        }
        return Minifier::minify($content, array('flaggedComments' => $this->_settings['flaggedComments']));
    }

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


Question:
Extract the options hash out of the argument to flag/switch and
 set the values if using classic style

def extract_options(names)
      options = {}
      options = names.pop if names.last.kind_of? Hash
      options = { :desc => @next_desc,
                  :long_desc => @next_long_desc,
                  :default_value => @next_default_value,
                  :arg_name => @next_arg_name}.merge(options)
    end

def match_community
      str = config_get('route_map', 'match_community', @get_args)
      if str.empty?
        val = default_match_community
      else
        val = str.split
        val.delete('exact-match')
      end
      val
    end

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


Question:
Add a chunk of html if a (non-strict) condition is met.

@param bool $condition
@param string $html
@param array $parentAttributes

@return $this

public function htmlIf($condition, string $html, array $parentAttributes = [])
    {
        if ($this->resolveCondition($condition)) {
            $this->html($html, $parentAttributes);
        }

        return $this;
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

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


Question:
Get the status for the given ran migrations.

@param  array  $ran
@return \Illuminate\Support\Collection

protected function getStatusFor(array $ran)
    {
        return Collection::make($this->getAllMigrationFiles())
            ->map(function ($migration) use ($ran) {
                $migrationName = $this->migrator->getMigrationName($migration);

                return in_array($migrationName, $ran)
                ? ['<info>Y</info>', $migrationName]
                : ['<fg=red>N</fg=red>', $migrationName];
            });
    }

func (c *BootstrapConfig) ConfigureArgs(args *BootstrapTplArgs) error {

	// Attempt to setup sink(s) from high-level config. Note the args are passed
	// by ref and modified in place.
	if err := c.generateStatsSinks(args); err != nil {
		return err
	}

	if c.StatsConfigJSON != "" {
		// StatsConfig overridden explicitly
		args.StatsConfigJSON = c.StatsConfigJSON
	} else {
		// Attempt to setup tags from high-level config. Note the args are passed by
		// ref and modified in place.
		if err := c.generateStatsConfig(args); err != nil {
			return err
		}
	}

	if c.StaticClustersJSON != "" {
		args.StaticClustersJSON = c.StaticClustersJSON
	}
	if c.StaticListenersJSON != "" {
		args.StaticListenersJSON = c.StaticListenersJSON
	}
	// Setup prometheus if needed. This MUST happen after the Static*JSON is set above
	if c.PrometheusBindAddr != "" {
		if err := c.generatePrometheusConfig(args); err != nil {
			return err
		}
	}

	if c.TracingConfigJSON != "" {
		args.TracingConfigJSON = c.TracingConfigJSON
	}

	if c.StatsFlushInterval != "" {
		args.StatsFlushInterval = c.StatsFlushInterval
	}

	return nil
}

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


Question: Execute the command.

public function exec()
    {
        $this->title();
        $ok = $this->confirm("\nAre you sure ? [y/n]", false);
        //
        if ($ok) {
            $process = Controller::clear();
            //
            $this->show($process);
        }
    }

func (c *downloadCommand) Info() *cmd.Info {
	return jujucmd.Info(&cmd.Info{
		Name:    "download-backup",
		Args:    "<ID>",
		Purpose: "Get an archive file.",
		Doc:     downloadDoc,
	})
}

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


Question:
Return a list of up to 'limit' stops within bounding box with 'n','e'
    and 's','w' in the NE and SW corners. Does not handle boxes crossing
    longitude line 180.

def handle_json_GET_boundboxstops(self, params):
    """"""
    schedule = self.server.schedule
    n = float(params.get('n'))
    e = float(params.get('e'))
    s = float(params.get('s'))
    w = float(params.get('w'))
    limit = int(params.get('limit'))
    stops = schedule.GetStopsInBoundingBox(north=n, east=e, south=s, west=w, n=limit)
    return [StopToTuple(s) for s in stops]

def _find_control_structure(self, start_address, search_length):

        words = self._read_memory(start_address, search_length, chunk_size=4, join=False)
        found_offset = None

        for i, word in enumerate(words):
            if word == ControlStructure.CONTROL_MAGIC_1:
                if (len(words) - i) < 4:
                    continue

                if words[i + 1] == ControlStructure.CONTROL_MAGIC_2 and words[i + 2] == ControlStructure.CONTROL_MAGIC_3 and words[i + 3] == ControlStructure.CONTROL_MAGIC_4:
                    found_offset = i
                    break

        if found_offset is None:
            raise HardwareError("Could not find control structure magic value in search area")

        struct_info = words[found_offset + 4]
        _version, _flags, length = struct.unpack("<BBH", struct.pack("<L", struct_info))

        if length % 4 != 0:
            raise HardwareError("Invalid control structure length that was not a multiple of 4", length=length)

        word_length = length // 4
        control_data = struct.pack("<%dL" % word_length, *words[found_offset:found_offset + word_length])

        logger.info("Found control stucture at address 0x%08X, word_length=%d", start_address + 4*found_offset, word_length)

        return ControlStructure(start_address + 4*found_offset, control_data)

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


Question:
Get self with initial-any-policy-inhibit set.

@param bool $flag
@return self

public function withAnyPolicyInhibit(bool $flag): self
    {
        $obj = clone $this;
        $obj->_anyPolicyInhibit = $flag;
        return $obj;
    }

public void marshall(StartLifecyclePolicyPreviewRequest startLifecyclePolicyPreviewRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(startLifecyclePolicyPreviewRequest.getRegistryId(), REGISTRYID_BINDING);
            protocolMarshaller.marshall(startLifecyclePolicyPreviewRequest.getRepositoryName(), REPOSITORYNAME_BINDING);
            protocolMarshaller.marshall(startLifecyclePolicyPreviewRequest.getLifecyclePolicyText(), LIFECYCLEPOLICYTEXT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param \Closure $prepare a function to prepare the node before putting into the result

@return string the json representation of the hierarchical result

public function toJson(\Closure $prepare = null)
    {
        $tree = $this->toArray($prepare);

        return json_encode($tree);
    }

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

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

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

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

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

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