Question:
Czyści wysłane starsze niż tydzień
@return integer ilość usuniętych

public static function clean()
    {
        return (new Orm\CmsMailQuery)
            ->whereActive()->equals(1)
            ->andFieldDateSent()->less(date('Y-m-d H:i:s', strtotime('-1 week')))
            ->find()
            //kasowanie całej kolekcji
            ->delete();
    }

def recv_match(self, condition=None, type=None, blocking=False, timeout=None):
        ''''''
        if type is not None and not isinstance(type, list):
            type = [type]
        start_time = time.time()
        while True:
            if timeout is not None:
                now = time.time()
                if now < start_time:
                    start_time = now # If an external process rolls back system time, we should not spin forever.
                if start_time + timeout < time.time():
                    return None
            m = self.recv_msg()
            if m is None:
                if blocking:
                    for hook in self.idle_hooks:
                        hook(self)
                    if timeout is None:
                        self.select(0.05)
                    else:
                        self.select(timeout/2)
                    continue
                return None
            if type is not None and not m.get_type() in type:
                continue
            if not evaluate_condition(condition, self.messages):
                continue
            return m

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


Question:
Commits the batch.

        This is called by :meth:`commit`.

def _commit(self):

        if self._id is None:
            mode = _datastore_pb2.CommitRequest.NON_TRANSACTIONAL
        else:
            mode = _datastore_pb2.CommitRequest.TRANSACTIONAL

        commit_response_pb = self._client._datastore_api.commit(
            self.project, mode, self._mutations, transaction=self._id
        )
        _, updated_keys = _parse_commit_response(commit_response_pb)
        # If the back-end returns without error, we are guaranteed that
        # ``commit`` will return keys that match (length and
        # order) directly ``_partial_key_entities``.
        for new_key_pb, entity in zip(updated_keys, self._partial_key_entities):
            new_id = new_key_pb.path[-1].id
            entity.key = entity.key.completed_key(new_id)

public function doRun(InputInterface $input, OutputInterface $output)
    {
        $this->setOutput($output);

        $this->resetCodeBuffer();

        $this->setAutoExit(false);
        $this->setCatchExceptions(false);

        $this->readline->readHistory();

        $this->output->writeln($this->getHeader());
        $this->writeVersionInfo();
        $this->writeStartupMessage();

        try {
            $this->beforeRun();
            $this->loop->run($this);
            $this->afterRun();
        } catch (ThrowUpException $e) {
            throw $e->getPrevious();
        } catch (BreakException $e) {
            // The ProcessForker throws a BreakException to finish the main thread.
            return;
        }
    }

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


Question:
/* (non-Javadoc)
@see org.openprovenance.prov.xml.TypIN#setValueAsJava(java.lang.Object)

@Override
    public void setValueFromObject(Object anObject) {
        if ((anObject!=null) && (value==null)) {
            if(anObject instanceof QualifiedName) {
                setValue((QualifiedName)anObject);
            } else if (anObject instanceof org.openprovenance.prov.model.LangString) {
                setValue((org.openprovenance.prov.model.LangString)anObject);
            } else if (anObject instanceof byte[]) {
                setValueFromObject((byte[]) anObject);
            } else if (anObject instanceof org.w3c.dom.Node) {
                setValueFromObject((org.w3c.dom.Node)anObject);
            } else {
                setValue(anObject.toString());
            }
        }

def wrap_java_property(property)
      pd = property.property_descriptor
      if pd.property_type == Java::JavaLang::String.java_class then
        wrap_java_string_property(property)
      elsif pd.property_type == Java::JavaUtil::Date.java_class then
        wrap_java_date_property(property)
      end
    end

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case SimpleAntlrPackage.NOT_EXPRESSION__VALUE:
        return basicSetValue(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
Branch this comparison: Do not touch this comparison line, but create a new one with exactly the same content,
        just one level deeper.
        :rtype: DiffLevel
        :return: New level in new comparison line

def branch_deeper(self,
                      new_t1,
                      new_t2,
                      child_relationship_class,
                      child_relationship_param=None,
                      report_type=None):

        branch = self.copy()
        return branch.create_deeper(new_t1, new_t2, child_relationship_class,
                                    child_relationship_param, report_type)

func vcsForDir(p *build.Package) (vcs *vcsCmd, root string, err error) {
	// Clean and double-check that dir is in (a subdirectory of) srcRoot.
	dir := filepath.Clean(p.Dir)
	srcRoot := filepath.Clean(p.SrcRoot)
	if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
		return nil, "", fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
	}

	origDir := dir
	for len(dir) > len(srcRoot) {
		for _, vcs := range vcsList {
			if fi, err := os.Stat(filepath.Join(dir, "."+vcs.cmd)); err == nil && fi.IsDir() {
				return vcs, dir[len(srcRoot)+1:], nil
			}
		}

		// Move to parent.
		ndir := filepath.Dir(dir)
		if len(ndir) >= len(dir) {
			// Shouldn't happen, but just in case, stop.
			break
		}
		dir = ndir
	}

	return nil, "", fmt.Errorf("directory %q is not using a known version control system", origDir)
}

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


Question:
Set the current language

@param  string $language
@return bool

public function setCurrentLanguage($language)
    {
        if (!$this->isAvailable($language)) {
            return false;
        }

        $this->session->put('language', $language);

        $this->setLanguage($language);

        return true;
    }

public function addResourcesFromDatabaseAndCacheThem($cacheResources = true)
    {
        try {
            $resources = $this->translationRepository->getAllDomainsByLocale();
            $this->addResources($resources);

            if ($cacheResources === true) {
                $this->resourceCacher->cacheResources($resources);
            }
        } catch (\Exception $ex) {
            // don't load if the database doesn't work
        }
    }

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


Question:
Read DFA transitions from flex compiled file
        Args:
            None
        Returns:
            list: The list of states and the destination for a character

def _read_transitions(self):

        states = []
        i = 0
        regex = re.compile('[ \t\n\r:,]+')
        found = 0  # For maintaining the state of yy_nxt declaration
        state = 0  # For maintaining the state of opening and closing tag of yy_nxt
        substate = 0  # For maintaining the state of opening and closing tag of each set in yy_nxt
        mapping = []  # For writing each set of yy_next
        cur_line = None
        with open(self.outfile) as flex_file:
            for cur_line in flex_file:
                if cur_line[0:35] == "static yyconst flex_int16_t yy_nxt[" or cur_line[0:33] == "static const flex_int16_t yy_nxt[":
                    found = 1
                    # print 'Found yy_next declaration'
                    continue
                if found == 1:
                    if state == 0 and cur_line[0:5] == "    {":
                        state = 1
                        continue
                    if state == 1 and cur_line[0:7] == "    } ;":
                        state = 0
                        break

                    if substate == 0 and cur_line[0:5] == "    {":
                        mapping = []
                        substate = 1
                        continue
                    if substate == 1:
                        if cur_line[0:6] != "    },":
                            cur_line = "".join(cur_line.split())
                            if cur_line == '':
                                continue
                            if cur_line[cur_line.__len__() - 1] == ',':
                                splitted_line = regex.split(
                                    cur_line[:cur_line.__len__() - 1])
                            else:
                                splitted_line = regex.split(cur_line)
                            mapping = mapping + splitted_line
                            continue
                        else:
                            cleared = []
                            for j in mapping:
                                cleared.append(int(j))
                            states.append(cleared)
                            mapping = []
                            substate = 0

        return states

def getStartNodes(fdefs,calls):
    ''''''
    s=[]
    for source in fdefs:
        for fn in fdefs[source]:
            inboundEdges=False
            for call in calls:
                if call.target==fn:
                    inboundEdges=True
            if not inboundEdges:
                s.append(fn)
    return s

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


Question:
// failLeakedDeployments is used to fail deployments that do not have a job.
// This state is a broken invariant that should not occur since 0.8.X.

func (n *nomadFSM) failLeakedDeployments(state *state.StateStore) error {
	// Scan for deployments that are referencing a job that no longer exists.
	// This could happen if multiple deployments were created for a given job
	// and thus the older deployment leaks and then the job is removed.
	iter, err := state.Deployments(nil)
	if err != nil {
		return fmt.Errorf("failed to query deployments: %v", err)
	}

	dindex, err := state.Index("deployment")
	if err != nil {
		return fmt.Errorf("couldn't fetch index of deployments table: %v", err)
	}

	for {
		raw := iter.Next()
		if raw == nil {
			break
		}

		d := raw.(*structs.Deployment)

		// We are only looking for active deployments where the job no longer
		// exists
		if !d.Active() {
			continue
		}

		// Find the job
		job, err := state.JobByID(nil, d.Namespace, d.JobID)
		if err != nil {
			return fmt.Errorf("failed to lookup job %s from deployment %q: %v", d.JobID, d.ID, err)
		}

		// Job exists.
		if job != nil {
			continue
		}

		// Update the deployment to be terminal
		failed := d.Copy()
		failed.Status = structs.DeploymentStatusCancelled
		failed.StatusDescription = structs.DeploymentStatusDescriptionStoppedJob
		if err := state.UpsertDeployment(dindex, failed); err != nil {
			return fmt.Errorf("failed to mark leaked deployment %q as failed: %v", failed.ID, err)
		}
	}

	return nil
}

def check_migrations_applied(app_configs, **kwargs):

    from django.db.migrations.loader import MigrationLoader
    errors = []

    # Load migrations from disk/DB
    try:
        loader = MigrationLoader(connection, ignore_no_migrations=True)
    except (ImproperlyConfigured, ProgrammingError, OperationalError):
        msg = "Can't connect to database to check migrations"
        return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)]

    if app_configs:
        app_labels = [app.label for app in app_configs]
    else:
        app_labels = loader.migrated_apps

    for node, migration in loader.graph.nodes.items():
        if migration.app_label not in app_labels:
            continue
        if node not in loader.applied_migrations:
            msg = 'Unapplied migration {}'.format(migration)
            # NB: This *must* be a Warning, not an Error, because Errors
            # prevent migrations from being run.
            errors.append(checks.Warning(msg,
                                         id=health.WARNING_UNAPPLIED_MIGRATION))

    return errors

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


Question: Generates an authorization uri.

def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type,
                 state, access_type, approval_prompt):
  """"""
  errors = []
  if response_type not in VALID_RESPONSE_TYPES:
    errors.append(
        '{0} is not a valid response_type, must be {1}.'.format(
        response_type, VALID_RESPONSE_TYPES))
  if not client_id:
    errors.append('client_id is missing or empty.')
  if not redirect_uri:
    errors.append('redirect_uri is missing or empty.')
  if not scope:
    errors.append('scope is missing or empty.')
  if access_type not in VALID_ACCESS_TYPES:
    errors.append('access_type is invalid.')
  if approval_prompt not in VALID_APPROVAL_PROMPTS:
    errors.append('approval_prompt is invalid')
  if errors:
    raise ValueError('Invalid parameters: {0}'.format('\n'.join(errors)))
  params = {
      'response_type': response_type,
      'client_id': client_id,
      'redirect_uri': redirect_uri,
      'scope': scope,
      'access_type': access_type,
      'approval_prompt': approval_prompt,
      'state': state,
  }
  return '?'.join([auth_service, urllib.urlencode(params)])

protected function getAuthorizationParameters(array $options)
    {
        $options = parent::getAuthorizationParameters($options);
        $options['purpose'] = $this->purpose;
        return $options;
    }

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


Question:
Describes metadata (field list and object properties) for the specified
    object.

def describeSObject(self, sObjectsType):
    '''

    '''
    self._setHeaders('describeSObject')
    return self._sforce.service.describeSObject(sObjectsType)

public function fill_meta($meta_data) {
	foreach ($meta_data as $key => $single_meta_data) {
		$this->add_meta($key, $single_meta_data);
	}
}

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


Question:
@param string $data

@return string
@throws \Exception

private function sign($data)
    {
        if (openssl_sign((string)$data, $signature, $this->privateKey->toString(), static::SIGNATURE_ALGORITHM) !== true) {
            throw new \Exception("Could not sign request: " . openssl_error_string());
        }

        return $signature;
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question:
Parent module assocation validator.

@param \Cake\ORM\Association $association Association instance
@return bool

private function isParentModuleAssociation(Association $association) : bool
    {
        return in_array($this->getModelByAssociation($association), $this->getParentModules());
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Returns an array of shell names and the paths to their binaries once populated. Will return an empty
array on unsupported platforms (Windows).

@return  array

public static function getShells() : array
    {
        // Return the cached result if it's already available.
        if (static::$shells !== null) {
            return static::$shells;
        }

        // Ensure this method will be ran once at most.
        static::$shells = [];

        // Can't easily check on Windows even if Cygwin or the likes are available.
        if (static::isWindows()) {
            return static::$shells;
        }

        if (file_exists($file = '/etc/shells')) {
            $cat = trim(shell_exec('cat '.$file.' 2> /dev/null'));

            foreach (explode(PHP_EOL, $cat) as $path) {
                // Ignore this line if it doesn't begin with a filepath.
                if ($path[0] != '/') {
                    continue;
                }

                $name = substr($path, strrpos($path, '/') + 1);

                static::$shells[$name] = $path;
            }
        }

        return static::$shells;
    }

public static function generate($args, $opts, $console)
    {
        $checklist = new ConsoleKit\Widgets\Checklist($console);
        foreach ($args as $action) {
            $console->writeln("Generating '$action'");
            $filename = ltrim($action, '/') . '.php';

            $actionsDir = (array) Atomik::get('atomik.dirs.actions');
            $actionsDir = array_shift($actionsDir);
            $checklist->step("Creating action file in $actionsDir", function() use ($actionsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($actionsDir, $filename),
                    "<?php\n\n// Logic goes here\n");
            });

            $viewsDir = (array) Atomik::get('atomik.dirs.views');
            $viewsDir = array_shift($viewsDir);
            $checklist->step("Creating view file in $viewsDir", function() use ($viewsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($viewsDir, $filename));
            });

            Atomik::fireEvent('Console::Generate', array($action));
        }
    }

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


Question:
Given tuple ``data`` encoding a PREMIS element, attempt to return the
    PREMIS version it is using. If none can be found, return the default PREMIS
    version.

def _premis_version_from_data(data):

    for child in data:
        if isinstance(child, dict):
            version = child.get("version")
            if version:
                return version
    return utils.PREMIS_VERSION

def _get_SEQRES_sequences(self):
        ''''''

        pdb_id = self.get_pdb_id()
        SEQRES_lines = self.parsed_lines["SEQRES"]

        modified_residue_mapping_3 = self.modified_residue_mapping_3
        # I commented this out since we do not need it for my current test cases
        #for k, v in self.modified_residues.iteritems():
        #    assert(v['modified_residue'] not in modified_residues)
        #    modified_residues[v['modified_residue']] = v['original_residue_3']

        for x in range(0, len(SEQRES_lines)):
            assert(SEQRES_lines[x][7:10].strip().isdigit())

        if not SEQRES_lines:
            #colortext.warning("WARNING: No SEQRES records were found. Kyle is trying to handle this gracefully, but Shane may need to fix it")
            return

        seqres_chain_order = []
        SEQRES_lines = [line[11:].rstrip() for line in SEQRES_lines] # we cannot strip the left characters as some cases e.g. 2MBP are missing chain identifiers

        # Collect all residues for all chains, remembering the chain order
        chain_tokens = {}
        for line in SEQRES_lines:
            chainID = line[0]
            if missing_chain_ids.get(self.pdb_id):
                chainID = missing_chain_ids[self.pdb_id]
            if chainID not in seqres_chain_order:
                seqres_chain_order.append(chainID)
            chain_tokens[chainID] = chain_tokens.get(chainID, [])
            chain_tokens[chainID].extend(line[6:].strip().split())

        sequences = {}
        self.chain_types = {}

        canonical_acid_types = set(residue_type_3to1_map.keys())
        canonical_acid_types.remove('UNK')
        assert(len(canonical_acid_types) == 20)

        for chain_id, tokens in chain_tokens.iteritems():

            # Determine whether the chain is DNA, RNA, or a protein chain
            # 1H38 is a good test for this - it contains DNA (chains E and G and repeated by H, K, N, J, M, P), RNA (chain F, repeated by I, L, O) and protein (chain D, repeated by A,B,C) sequences
            # 1ZC8 is similar but also has examples of DU
            # 4IHY has examples of DI (I is inosine)
            # 2GRB has RNA examples of I and U
            # 1LRP has protein chains with only CA atoms
            # This will throw an exception when a non-canonical is found which is not listed in basics.py. In that case, the list in basics.py should be updated.

            chain_type = None
            set_of_tokens = set(tokens)
            if (set_of_tokens.union(all_recognized_dna) == all_recognized_dna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'DNA'
            elif (set_of_tokens.union(all_recognized_rna) == all_recognized_rna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'RNA'
            elif len(set_of_tokens) == 1 and 'UNK' in set_of_tokens:
                chain_type = 'Unknown'
            elif not(set_of_tokens.intersection(canonical_acid_types)):
                # Zero canonical residues may imply a ligand or a heterogen chain
                chain_type = PDB._determine_heterogen_chain_type(set_of_tokens)
            else:
                assert(len(set(tokens).intersection(dna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                chain_type = 'Protein'
                if not self.chain_atoms.get(chain_id):
                    # possible for biological unit files
                    continue
                if self.chain_atoms[chain_id] == set(['CA']):
                    chain_type = 'Protein skeleton'

            # Get the sequence, mapping non-canonicals to the appropriate letter
            self.chain_types[chain_id] = chain_type

            sequence = []
            if chain_type == 'DNA':
                for r in tokens:
                    if dna_nucleotides_2to1_map.get(r):
                        sequence.append(dna_nucleotides_2to1_map[r])
                    else:
                        if non_canonical_dna.get(r):
                            sequence.append(non_canonical_dna[r])
                        else:
                            raise Exception("Unknown DNA residue %s." % r)
            elif chain_type == 'RNA':
                for r in tokens:
                    if r in rna_nucleotides:
                        sequence.append(r)
                    else:
                        if non_canonical_rna.get(r):
                            sequence.append(non_canonical_rna[r])
                        else:
                            raise Exception("Unknown RNA residue %s." % r)
            else:
                token_counter = 0
                for r in tokens:
                    token_counter += 1
                    if residue_type_3to1_map.get(r):
                        sequence.append(residue_type_3to1_map[r])
                    else:

                        if self.modified_residue_mapping_3.get(r):
                            sequence.append(residue_type_3to1_map[self.modified_residue_mapping_3.get(r)])
                        elif non_canonical_amino_acids.get(r):
                            #print('Mapping non-canonical residue %s to %s.' % (r, non_canonical_amino_acids[r]))
                            #print(SEQRES_lines)
                            #print(line)
                            sequence.append(non_canonical_amino_acids[r])
                        elif r == 'UNK':
                            continue
                        # Skip these residues
                        elif r == 'ACE' and token_counter == 1:
                            # Always allow ACE as the first residue of a chain
                            sequence.append('X')
                        elif r == 'ACE' and pdb_id in cases_with_ACE_residues_we_can_ignore:
                            sequence.append('X')
                            #continue
                        # End of skipped residues
                        else:
                            #print(modified_residue_mapping_3)
                            if modified_residue_mapping_3.get(r):
                                if modified_residue_mapping_3[r] == 'UNK':
                                    sequence.append('X')
                                else:
                                    assert(modified_residue_mapping_3[r] in residue_types_3)
                                    sequence.append(residue_type_3to1_map[modified_residue_mapping_3[r]])
                            else:
                                raise Exception("Unknown protein residue %s in chain %s." % (r, chain_id))
            sequences[chain_id] = "".join(sequence)

        self.seqres_chain_order = seqres_chain_order

        # Create Sequence objects for the SEQRES sequences
        for chain_id, sequence in sequences.iteritems():
            self.seqres_sequences[chain_id] = Sequence.from_sequence(chain_id, sequence, self.chain_types[chain_id])

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


Question: // ModelByName implements ModelGetter.

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

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

	all, err := ReadModelsFile(JujuModelsPath())
	if err != nil {
		return nil, errors.Trace(err)
	}
	controllerModels, ok := all[controllerName]
	if !ok {
		return nil, errors.NotFoundf(
			"model %s:%s",
			controllerName,
			modelName,
		)
	}
	details, ok := controllerModels.Models[modelName]
	if !ok {
		return nil, errors.NotFoundf(
			"model %s:%s",
			controllerName,
			modelName,
		)
	}
	return &details, nil
}

public function getCaption()
    {
        return $this->caption ?: (isset($this->ui['caption']) ? $this->ui['caption'] :
            ucwords(str_replace('_', ' ', $this->short_name)));
    }

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


Question:
Check if this object configuration is correct ::

        * Check our own specific properties
        * Call our parent class is_correct checker

        :return: True if the configuration is correct, otherwise False
        :rtype: bool

def is_correct(self):

        state = True

        # _internal_host_check is for having an host check result
        # without running a check plugin
        if self.command_name.startswith('_internal_host_check'):
            # Command line may contain: [state_id][;output]
            parameters = self.command_line.split(';')
            if len(parameters) < 2:
                self.command_name = "_internal_host_check;0;Host assumed to be UP"
                self.add_warning("[%s::%s] has no defined state nor output. Changed to %s"
                                 % (self.my_type, self.command_name, self.command_name))
            elif len(parameters) < 3:
                state = 3
                try:
                    state = int(parameters[1])
                except ValueError:
                    self.add_warning("[%s::%s] required a non integer state: %s. Using 3."
                                     % (self.my_type, self.command_name, parameters[1]))

                if state > 4:
                    self.add_warning("[%s::%s] required an impossible state: %d. Using 3."
                                     % (self.my_type, self.command_name, state))

                output = {0: "UP", 1: "DOWN", 2: "DOWN", 3: "UNKNOWN", 4: "UNREACHABLE", }[state]
                self.command_name = "_internal_host_check;Host assumed to be %s" % output

                self.add_warning("[%s::%s] has no defined output. Changed to %s"
                                 % (self.my_type, self.command_name, self.command_name))
            elif len(parameters) > 3:
                self.command_name = "%s;%s;%s" % (parameters[0], parameters[1], parameters[2])

                self.add_warning("[%s::%s] has too many parameters. Changed to %s"
                                 % (self.my_type, self.command_name, self.command_name))

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

def add_item(self, host, key, value, clock=None, state=0):

        if clock is None:
            clock = self.clock
        if self._config.data_type == "items":
            item = {"host": host, "key": key,
                    "value": value, "clock": clock, "state": state}
        elif self._config.data_type == "lld":
            item = {"host": host, "key": key, "clock": clock, "state": state,
                    "value": json.dumps({"data": value})}
        else:
            if self.logger: # pragma: no cover
                self.logger.error("Setup data_type before adding data")
            raise ValueError('Setup data_type before adding data')
        self._items_list.append(item)

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


Question:
// formatFloat converts the floating-point number f to a string,
// after rounding it to the passed unit.
//
// Uses 'f' format (-ddd.dddddd, no exponent), and uses at most
// maxPrec digits after the decimal point.

func formatFloat(f float64, maxPrec int) string {
	v := strconv.FormatFloat(f, 'f', -1, 64)

	idx := strings.LastIndex(v, ".")
	if idx == -1 {
		return v
	}

	sublen := idx + maxPrec + 1
	if sublen > len(v) {
		sublen = len(v)
	}

	return v[:sublen]
}

private Class<?> convertType(Class<?> old)
   {
      if (Boolean.class.equals(old))
      {
         return boolean.class;
      }
      else if (boolean.class.equals(old))
      {
         return Boolean.class;
      }
      else if (Byte.class.equals(old))
      {
         return byte.class;
      }
      else if (byte.class.equals(old))
      {
         return Byte.class;
      }
      else if (Short.class.equals(old))
      {
         return short.class;
      }
      else if (short.class.equals(old))
      {
         return Short.class;
      }
      else if (Integer.class.equals(old))
      {
         return int.class;
      }
      else if (int.class.equals(old))
      {
         return Integer.class;
      }
      else if (Long.class.equals(old))
      {
         return long.class;
      }
      else if (long.class.equals(old))
      {
         return Long.class;
      }
      else if (Float.class.equals(old))
      {
         return float.class;
      }
      else if (float.class.equals(old))
      {
         return Float.class;
      }
      else if (Double.class.equals(old))
      {
         return double.class;
      }
      else if (double.class.equals(old))
      {
         return Double.class;
      }
      else if (Character.class.equals(old))
      {
         return char.class;
      }
      else if (char.class.equals(old))
      {
         return Character.class;
      }

      return null;
   }

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public void setMean(double newMean) {
		double oldMean = mean;
		mean = newMean;
		boolean oldMeanESet = meanESet;
		meanESet = true;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.NORMAL_DISTRIBUTION_TYPE__MEAN, oldMean, mean, !oldMeanESet));
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
Returns the application parameters.

@return array An array of application parameters

protected function getAppParameters()
    {
        return array_merge(
            array(
                'app.root_dir' => $this->rootDir,
                'app.environment' => $this->environment,
                'app.debug' => $this->debug,
                'app.name' => $this->name,
                'app.cache_dir' => $this->getCacheDir(),
                'app.logs_dir' => $this->getLogDir(),
                'app.charset' => $this->getCharset(),
            ),
            $this->getEnvParameters()
        );
    }

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: Adds classification context to views.

def classification(request):

    ctx = {
        'classification_text': getattr(settings, 'CLASSIFICATION_TEXT', 'UNCLASSIFIED'),
        'classification_text_color': getattr(settings, 'CLASSIFICATION_TEXT_COLOR', 'white'),
        'classification_background_color': getattr(settings, 'CLASSIFICATION_BACKGROUND_COLOR', 'green'),
        'classification_banner_enabled': getattr(settings, 'CLASSIFICATION_BANNER_ENABLED', True),
        'classification_link': getattr(settings, 'CLASSIFICATION_LINK', None)
    }

    return ctx

def get_command_class(name, exclude_packages=None, exclude_command_class=None):

    from django.conf import settings
    return get_command_class_from_apps(
        name,
        settings.INSTALLED_APPS \
            if "django.core" in settings.INSTALLED_APPS \
            else ("django.core",) + tuple(settings.INSTALLED_APPS),
        exclude_packages=exclude_packages,
        exclude_command_class=exclude_command_class)

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


Question:
Adds close handler to the current stream.

<p>This is an intermediate operation.

@param closeHandler  an action to execute when the stream is closed
@return the new stream with the close handler
@since 1.1.8

@NotNull
    public Stream<T> onClose(@NotNull final Runnable closeHandler) {
        Objects.requireNonNull(closeHandler);
        final Params newParams = Params.wrapWithCloseHandler(params, closeHandler);
        return new Stream<T>(newParams, iterator);
    }

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: Force invalidation of a VersionedTargetSet.

def force_invalidate(self, vts):
    """"""
    for vt in vts.versioned_targets:
      self._invalidator.force_invalidate(vt.cache_key)
      vt.valid = False
    self._invalidator.force_invalidate(vts.cache_key)
    vts.valid = False

public void setItems(java.util.Collection<RequestValidator> items) {
        if (items == null) {
            this.items = null;
            return;
        }

        this.items = new java.util.ArrayList<RequestValidator>(items);
    }

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


Question: // Get implements backend.B.

func (b *Backend) Get(c context.Context, configSet config.Set, path string, p backend.Params) (*config.Config, error) {
	item, err := b.B.Get(c, configSet, path, p)
	if err != nil {
		return nil, err
	}

	if !p.FormatSpec.Unformatted() {
		formatter, err := getFormatter(p.FormatSpec.Formatter)
		if err != nil {
			return nil, errors.Annotate(err, "failed to get formatter for %q", p.FormatSpec).Err()
		}

		if err := b.formatItem(item, formatter, p.FormatSpec); err != nil {
			return nil, errors.Annotate(err, "failed to format item to %q, data %q",
				p.FormatSpec.Formatter, p.FormatSpec.Data).Err()
		}
	}
	return item, nil
}

func (factory *JenkinsBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface {
	bee := JenkinsBee{
		Bee: bees.NewBee(name, factory.ID(), description, options),
	}
	bee.ReloadOptions(options)

	return &bee
}

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


Question:
Returns the current offset for the given date allowing for daylight savings.
@param dt The date to be checked
@return The current offset for the given date allowing for daylight savings

protected int getOffset(long dt)
    {
        int ret = 0;
        TimeZone tz = DateUtilities.getCurrentTimeZone();
        if(tz != null)
            ret = tz.getOffset(dt);
        return ret;
    }

def _check_choices_attribute(self):   # pragma: no cover
        """"""

        if self.choices:
            warning_params = {
                'msg': (
                    "'choices' contains an invalid time zone value '{value}' "
                    "which was not found as a supported time zone by pytz "
                    "{version}."
                ),
                'hint': "Values must be found in pytz.all_timezones.",
                'obj': self,
            }

            for option_key, option_value in self.choices:
                if isinstance(option_value, (list, tuple)):
                    # This is an optgroup, so look inside the group for
                    # options.
                    for optgroup_key in map(lambda x: x[0], option_value):
                        if optgroup_key not in pytz.all_timezones:
                            # Make sure we don't raise this error on empty
                            #   values
                            if optgroup_key not in self.empty_values:
                                # Update the error message by adding the value
                                warning_params.update({
                                    'msg': warning_params['msg'].format(
                                        value=optgroup_key,
                                        version=pytz.VERSION
                                    )
                                })

                                # Return the warning
                                return [
                                    checks.Warning(**warning_params)
                                ]

                elif option_key not in pytz.all_timezones:
                    # Make sure we don't raise this error on empty
                    #   values
                    if option_key not in self.empty_values:
                        # Update the error message by adding the value
                        warning_params.update({
                            'msg': warning_params['msg'].format(
                                value=option_key,
                                version=pytz.VERSION
                            )
                        })

                        # Return the warning
                        return [
                            checks.Warning(**warning_params)
                        ]

        # When no error, return an empty list
        return []

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


Question:
// computeBlindingFactor for the next hop given the ephemeral pubKey and
// sharedSecret for this hop. The blinding factor is computed as the
// sha-256(pubkey || sharedSecret).

func computeBlindingFactor(hopPubKey *btcec.PublicKey,
	hopSharedSecret []byte) Hash256 {

	sha := sha256.New()
	sha.Write(hopPubKey.SerializeCompressed())
	sha.Write(hopSharedSecret)

	var hash Hash256
	copy(hash[:], sha.Sum(nil))
	return hash
}

Scope enterScope() {
    final Map<VarKey, Variable> currentFrame = new LinkedHashMap<>();
    final Label scopeExit = new Label();
    frames.push(currentFrame);
    return new Scope() {
      boolean exited;

      @Override
      Variable createSynthetic(
          SyntheticVarName varName, Expression initExpr, SaveStrategy strategy) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.SYNTHETIC, varName.name());
        // synthetics are prefixed by $ by convention
        String name = fieldNames.generateName("$" + varName.name());
        return doCreate(name, new Label(), scopeExit, initExpr, key, strategy);
      }

      @Override
      Variable createTemporary(String name, Expression initExpr) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.TEMPORARY, name);
        name = fieldNames.generateName("$$" + name);
        return doCreate(name, new Label(), scopeExit, initExpr, key, SaveStrategy.NEVER);
      }

      @Override
      Variable create(String name, Expression initExpr, SaveStrategy strategy) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.USER_DEFINED, name);
        name = fieldNames.generateName(name);
        return doCreate(name, new Label(), scopeExit, initExpr, key, strategy);
      }

      @Override
      Statement exitScope() {
        checkState(!exited, "Scope already exited");
        exited = true;
        frames.pop();
        // Use identity semantics to make sure we visit each label at most once.  visiting a label
        // more than once tends to corrupt internal asm state.
        final Set<Label> endLabels = Sets.newIdentityHashSet();
        for (Variable var : currentFrame.values()) {
          endLabels.add(var.local.end());
          availableSlots.clear(
              var.local.index(), var.local.index() + var.local.resultType().getSize());
        }
        return new Statement() {
          // TODO(lukes): we could generate null writes for when object typed fields go out of
          // scope.  This would potentially allow intermediate results to be collected sooner.
          @Override
          protected void doGen(CodeBuilder adapter) {
            for (Label label : endLabels) {
              adapter.visitLabel(label);
            }
          }
        };
      }

      private Variable doCreate(
          String name,
          Label start,
          Label end,
          Expression initExpr,
          VarKey key,
          SaveStrategy strategy) {
        int index = reserveSlotFor(initExpr.resultType());
        LocalVariable local =
            LocalVariable.createLocal(name, index, initExpr.resultType(), start, end);
        Variable var;
        switch (strategy) {
          case DERIVED:
            var = new DerivedVariable(initExpr, local);
            break;
          case NEVER:
            var = new TemporaryVariable(initExpr, local);
            break;
          case STORE:
            var = new FieldSavedVariable(initExpr, local);
            break;
          default:
            throw new AssertionError();
        }
        currentFrame.put(key, var);
        allVariables.add(var);
        return var;
      }
    };
  }

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


Question:
Delete resource from a resource set.

@param ResourceSet $sourceResourceSet
@param object      $sourceEntityInstance

return bool true if resources sucessfully deteled, otherwise false

public function deleteResource(
        ResourceSet $sourceResourceSet,
        $sourceEntityInstance
    ) {
        $source = $this->unpackSourceEntity($sourceEntityInstance);

        $verb = 'delete';
        if (!($source instanceof Model)) {
            throw new InvalidArgumentException('Source entity must be an Eloquent model.');
        }

        $class = $sourceResourceSet->getResourceType()->getInstanceType()->getName();
        $id = $source->getKey();
        $name = $source->getKeyName();
        $data = [$name => $id];

        $data = $this->createUpdateDeleteCore($source, $data, $class, $verb);

        $success = isset($data['id']);
        if ($success) {
            return true;
        }
        throw new ODataException('Target model not successfully deleted', 422);
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
After calibration points have been found this invokes the Zhang99 algorithm to
estimate calibration parameters.  Error statistics are also computed.

public <T extends CameraModel>T process() {
		if( zhang99 == null )
			throw new IllegalArgumentException("Please call configure first.");
		zhang99.setVerbose(verbose,0);
		if( !zhang99.process(observations) ) {
			throw new RuntimeException("Zhang99 algorithm failed!");
		}

		structure = zhang99.getStructure();

		errors = zhang99.computeErrors();

		foundIntrinsic = zhang99.getCameraModel();
		foundIntrinsic.width = imageWidth;
		foundIntrinsic.height = imageHeight;

		return (T)foundIntrinsic;
	}

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question: Marshall the given parameter object.

public void marshall(CancelSchemaExtensionRequest cancelSchemaExtensionRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(cancelSchemaExtensionRequest.getDirectoryId(), DIRECTORYID_BINDING);
            protocolMarshaller.marshall(cancelSchemaExtensionRequest.getSchemaExtensionId(), SCHEMAEXTENSIONID_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:
Replaces the specified child control with a new control.

@method replace
@param {tinymce.ui.Control} oldItem Old item to be replaced.
@param {tinymce.ui.Control} newItem New item to be inserted.

function (oldItem, newItem) {
        var ctrlElm, items = this.items(), i = items.length;

        // Replace the item in collection
        while (i--) {
          if (items[i] === oldItem) {
            items[i] = newItem;
            break;
          }
        }

        if (i >= 0) {
          // Remove new item from DOM
          ctrlElm = newItem.getEl();
          if (ctrlElm) {
            ctrlElm.parentNode.removeChild(ctrlElm);
          }

          // Remove old item from DOM
          ctrlElm = oldItem.getEl();
          if (ctrlElm) {
            ctrlElm.parentNode.removeChild(ctrlElm);
          }
        }

        // Adopt the item
        newItem.parent(this);
      }

public static TemplateMetadata fromTemplate(TemplateNode template) {
    TemplateMetadata.Builder builder =
        builder()
            .setTemplateName(template.getTemplateName())
            .setSourceLocation(template.getSourceLocation())
            .setSoyFileKind(SoyFileKind.SRC)
            .setContentKind(template.getContentKind())
            .setStrictHtml(template.isStrictHtml())
            .setDelPackageName(template.getDelPackageName())
            .setVisibility(template.getVisibility())
            .setParameters(Parameter.directParametersFromTemplate(template))
            .setDataAllCallSituations(DataAllCallSituation.fromTemplate(template));
    switch (template.getKind()) {
      case TEMPLATE_BASIC_NODE:
        builder.setTemplateKind(Kind.BASIC);
        break;
      case TEMPLATE_DELEGATE_NODE:
        builder.setTemplateKind(Kind.DELTEMPLATE);
        TemplateDelegateNode deltemplate = (TemplateDelegateNode) template;
        builder.setDelTemplateName(deltemplate.getDelTemplateName());
        builder.setDelTemplateVariant(deltemplate.getDelTemplateVariant());
        break;
      case TEMPLATE_ELEMENT_NODE:
        builder.setTemplateKind(Kind.ELEMENT);
        break;
      default:
        throw new AssertionError("unexpected template kind: " + template.getKind());
    }
    return builder.build();
  }

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


Question: // Making log with PANIC level.

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

def dump_stats(self, fdump, close=True):

        if self.tracker:
            self.tracker.stop_periodic_snapshots()

        if isinstance(fdump, type('')):
            fdump = open(fdump, 'wb')
        pickle.dump(self.index, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        pickle.dump(self.snapshots, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        if close:
            fdump.close()

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


Question: One of ways of creating builder. This is possibly the least verbose way where compiler should be able to guess the generic parameters.

@Nonnull
	public static LFltConsumer fltConsumerFrom(Consumer<LFltConsumerBuilder> buildingFunction) {
		LFltConsumerBuilder builder = new LFltConsumerBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

public <T> Message body(T body, Charset charset) {
        messageWriter.writeBody(body, charset);
        return this;
    }

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


Question:
Register the bindings.

@param \Illuminate\Contracts\Foundation\Application $app

@return void

protected function registerBindings(Application $app) {
        $app->bind('bitbucket.connection', function ($app) {
            $manager = $app['bitbucket'];
            return $manager->connection();
        });
        $app->alias('bitbucket.connection', Api::class);
    }

func ValidateWebhook(w auditregistration.Webhook, fldPath *field.Path) field.ErrorList {
	var allErrs field.ErrorList
	if w.Throttle != nil {
		allErrs = append(allErrs, ValidateWebhookThrottleConfig(w.Throttle, fldPath.Child("throttle"))...)
	}

	cc := w.ClientConfig
	switch {
	case (cc.URL == nil) == (cc.Service == nil):
		allErrs = append(allErrs, field.Required(fldPath.Child("clientConfig"), "exactly one of url or service is required"))
	case cc.URL != nil:
		allErrs = append(allErrs, webhook.ValidateWebhookURL(fldPath.Child("clientConfig").Child("url"), *cc.URL, false)...)
	case cc.Service != nil:
		allErrs = append(allErrs, webhook.ValidateWebhookService(fldPath.Child("clientConfig").Child("service"), cc.Service.Name, cc.Service.Namespace, cc.Service.Path, cc.Service.Port)...)
	}
	return allErrs
}

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


Question:
get message

@param bool $block if block when the queue is empty
@return bool|string

public function get($block = false)
    {
        $queue_status = $this->status();
        if ($queue_status['msg_qnum'] > 0) {
            $option_receive = $block ? 0 : $this->option_receive;
            if (\msg_receive(
                    $this->queue,
                    $this->msg_type,
                    $msgtype_erhalten,
                    $this->maxsize,
                    $data,
                    $this->serialize_needed,
                    $option_receive,
                    $err
                ) === true
            ) {
                return $data;
            } else {
                throw new \RuntimeException($err);
            }
        } else {
            return false;
        }
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end

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


Question: new mercurial-repo

public static function init($path)
    {
        pake_mkdirs($path);

        pake_sh(escapeshellarg(pake_which('hg')).' init -q '.escapeshellarg($path));

        return new pakeMercurial($path);
    }

public void toMediaWiki(
      final String username, final String password, final String url, final String title)
      throws GitChangelogRepositoryException, GitChangelogIntegrationException {
    new MediaWikiClient(url, title, render()) //
        .withUser(username, password) //
        .createMediaWikiPage();
  }

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


Question: Returns the total standard deviation

def get_stddevs(self, mag, imt, stddev_types, num_sites):

        stddevs = []
        for stddev_type in stddev_types:
            assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
            if stddev_type == const.StdDev.TOTAL:
                sigma = self._get_total_sigma(imt, mag)
                stddevs.append(sigma + np.zeros(num_sites))
        return stddevs

def _compute_std(self, C, stddevs, idx):

        for stddev in stddevs:
            stddev[idx] += C['sigma']

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


Question:
@param string $fileName

@return bool|resource|string

public function getFileResource($fileName)
    {
        $resource = fopen('php://temp', 'r+');
        $entry = $this->sevenZip->getEntry($fileName);

        fwrite($resource, $entry->getContent());
        rewind($resource);
        return $resource;
    }

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: // Metrics returns the metrics in this batch.

func (m *MetricBatch) Metrics() []Metric {
	result := make([]Metric, len(m.doc.Metrics))
	copy(result, m.doc.Metrics)
	return result
}

func DiscardMessage(msg *Message, pluginID string, comment string) {
	GetStreamMetric(msg.GetStreamID()).Discarded.Inc(1)
	MessageTrace(msg, pluginID, comment)
}

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


Question:
Sets the number of spaces the exported class should have.

@param integer $numSpaces

@return self

public function setNumSpaces($numSpaces)
    {
        $this->spaces = str_repeat(' ', $numSpaces);
        $this->numSpaces = $numSpaces;

        return $this;
    }

def import_course(course_id, path)
			xml = connection.call("rustici.course.importCourse", :courseid => course_id, :path => path)
			if xml.elements['//rsp/importresult'].attributes["successful"] == "true"
				title = xml.elements['//rsp/importresult/title'].text
				{ :title => title, :warnings => [] }
			else
				nil
			end
		end

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


Question: // SetLogging sets the Logging field's value.

func (s *UpdateClusterConfigInput) SetLogging(v *Logging) *UpdateClusterConfigInput {
	s.Logging = v
	return s
}

public void pushAttributeValueEvent(final String deviceName, final String attributeName) throws DevFailed {
        xlogger.entry();
        for (final EventType eventType : EventType.getEventAttrValueTypeList()) {
            pushAttributeValueEventIdlLoop(deviceName, attributeName, eventType);
        }
        xlogger.exit();
    }

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


Question:
Return all lang strings of a component - call to core get_component_strings().

@param string $component component name
@return array

@since Moodle 2.4

public static function get_component_strings($component, $lang = null) {

        if (empty($lang)) {
            $lang = current_language();
        }

        $params = self::validate_parameters(self::get_component_strings_parameters(),
                      array('component'=>$component, 'lang' => $lang));

        $stringmanager = get_string_manager();

        $wsstrings = array();
        $componentstrings = $stringmanager->load_component_strings($params['component'], $params['lang']);
        foreach($componentstrings as $stringid => $string) {
            $wsstring = array();
            $wsstring['stringid'] = $stringid;
            $wsstring['string'] = $string;
            $wsstrings[] = $wsstring;
        }

        return $wsstrings;
    }

def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False):

    if language_code is None:
        language_code = instance.get_current_language()

    # In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
    # This serves as detection against backwards incompatibility issues.
    if len(field_name) <= 5 and len(language_code) > 5:
        raise RuntimeError("Unexpected language code, did you swap field_name, language_code?")

    translated_model = instance._parler_meta.get_model_by_field(field_name)
    values = _get_cached_values(instance, translated_model, language_code, use_fallback)
    if not values:
        return None

    # Allow older cached versions where the field didn't exist yet.
    return values.get(field_name, None)

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


Question:
Select only matching embedded documents in an array field for the query
projection.

@see http://docs.mongodb.org/manual/reference/projection/elemMatch/

@param array|Expr $expression

public function selectElemMatch(string $fieldName, $expression) : self
    {
        if ($expression instanceof Expr) {
            $expression = $expression->getQuery();
        }
        $this->query['select'][$fieldName] = ['$elemMatch' => $expression];
        return $this;
    }

public static function getMultiple(
        Bookboon $bookboon,
        array $bookIds,
        bool $extendedMetadata = false
    ) : BookboonResponse {
        if (count($bookIds) === 0) {
            throw new UsageException('At least one id is required for bookIds');
        }

        $variables = [
            'id' => $bookIds,
            'extendedMetadata' => $extendedMetadata ? 'true' : 'false'
        ];

        $bResponse = $bookboon->rawRequest("/books", $variables);

        $bResponse->setEntityStore(
            new EntityStore(static::getEntitiesFromArray($bResponse->getReturnArray()))
        );

        return $bResponse;
    }

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


Question: r"""Break N-dimensional signals into N 1D signals.

def _break_signals(self):
        """
        for name in list(self.signals.keys()):
            if self.signals[name].ndim == 2:
                for i, signal_1d in enumerate(self.signals[name].T):
                    self.signals[name + '_' + str(i)] = signal_1d
                del self.signals[name]

func (nk *nick) delChannel(ch *channel) {
	if _, ok := nk.chans[ch]; ok {
		delete(nk.chans, ch)
		delete(nk.lookup, ch.name)
	} else {
		logging.Warn("Nick.delChannel(): %s not on %s.", nk.nick, ch.name)
	}
}

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


Question:
Check if item in map

@param mixed $key
@return bool

public function has($key)
    {
        $key = $this->getScalarKey($key);
        return isset($this->list[$key]);
    }

def other_pins(id = nil, options = {}, &block)
      id, options = nil, id if id.is_a?(Hash)
      options = {
        other_pin: true
      }.merge(options)
      pins(id, options, &block)
    end

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


Question:
Stitches blocks together into a single block columnwise. These blocks are 2D tables usually
    generated from tableproc. The final block will be of dimensions (max(num_rows), sum(num_cols)).

def stitch_block(block_list):
    '''

    '''
    block_out = [[]]
    for block in block_list:
        num_row = len(block)
        row_len = len(block[0])
        if len(block_out) < num_row:
            for i in range(num_row-len(block_out)):
                block_out.append([None]*len(block_out[0]))
        for row_out, row_in in zip(block_out, block):
            row_out.extend(row_in)
        if len(block_out) > num_row:
            for row_out in block_out[num_row:]:
                row_out.extend([None]*row_len)
    return block_out

def update(self, reseed):

        self._screen.print_at(" ", self._x, self._y)
        cell = None
        for _ in range(self._rate):
            self._y += 1
            cell = self._screen.get_from(self._x, self._y)
            if cell is None or cell[0] != 32:
                break

        if ((cell is not None and cell[0] in [ord(x) for x in self._snow_chars + " "]) and
                (self._y < self._screen.start_line + self._screen.height)):
            self._screen.print_at(self._char,
                                  self._x,
                                  self._y)
        else:
            if self._y > self._screen.start_line + self._screen.height:
                self._y = self._screen.start_line + self._screen.height

            drift_index = -1
            if cell:
                drift_index = self._drift_chars.find(chr(cell[0]))
            if 0 <= drift_index < len(self._drift_chars) - 1:
                drift_char = self._drift_chars[drift_index + 1]
                self._screen.print_at(drift_char, self._x, self._y)
            else:
                self._screen.print_at(",", self._x, self._y - 1)
            if reseed:
                self._reseed()

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


Question:
// GetContainerProfileInfo returns a slice of ContainerLXDProfile, 1 for each unit's charm
// which contains an lxd-profile.yaml.

func (st *State) GetContainerProfileInfo(containerTag names.MachineTag) ([]*LXDProfileResult, error) {
	var result params.ContainerProfileResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: containerTag.String()}},
	}
	if err := st.facade.FacadeCall("GetContainerProfileInfo", args, &result); err != nil {
		return nil, err
	}
	if len(result.Results) != 1 {
		return nil, errors.Errorf("expected 1 result, got %d", len(result.Results))
	}
	if err := result.Results[0].Error; err != nil {
		return nil, err
	}
	profiles := result.Results[0].LXDProfiles
	var res []*LXDProfileResult
	for _, p := range profiles {
		if p == nil {
			continue
		}
		res = append(res, &LXDProfileResult{
			Config:      p.Profile.Config,
			Description: p.Profile.Description,
			Devices:     p.Profile.Devices,
			Name:        p.Name,
		})
	}
	return res, nil
}

public function load(string $file)
    {
        $this->data = Yaml::parse(file_get_contents($file));
        $this->filename = basename($file);
    }

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


Question: Notifies user of results of init or destroy commands.

def status_message(bucket_name, state)
      message = ['', "Bucket s3://#{bucket_name} #{state}"]
      message << "Config dir #{config_dir} #{state}"

      state = 'complete' if state == 'created'
      message << "Config #{state}"

      message.join("\n")
    end

def create_service( name, git, path )
      ok = create_dir( name )
      ok = clone_service_shell( name, git ) if ok &&   path.nil?
      ok = copy_service_shell( name, path ) if ok && ! path.nil?
      ok = remove_dot_git( name, git )      if ok
      ok = replace_strings( name )          if ok

      if ok
        puts "Success! ./#{name} created."
        Kernel::exit( KERNEL_EXIT_SUCCESS )
      else
        Kernel::exit( KERNEL_EXIT_FAILURE )
      end
    end

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


Question: // PutInt64 puts the 64 integer.

func PutInt64(v int64) []byte {
	b := make([]byte, 8)
	binary.LittleEndian.PutUint64(b, uint64(v))
	return b
}

func ToIntsRef(input []byte, scratch *util.IntsRefBuilder) *util.IntsRef {
	scratch.Clear()
	for _, v := range input {
		scratch.Append(int(v))
	}
	return scratch.Get()
}

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


Question:
Determine which dataset variables need to be concatenated in the result,
    and which can simply be taken from the first dataset.

def _calc_concat_over(datasets, dim, data_vars, coords):

    # Return values
    concat_over = set()
    equals = {}

    if dim in datasets[0]:
        concat_over.add(dim)
    for ds in datasets:
        concat_over.update(k for k, v in ds.variables.items()
                           if dim in v.dims)

    def process_subset_opt(opt, subset):
        if isinstance(opt, str):
            if opt == 'different':
                # all nonindexes that are not the same in each dataset
                for k in getattr(datasets[0], subset):
                    if k not in concat_over:
                        # Compare the variable of all datasets vs. the one
                        # of the first dataset. Perform the minimum amount of
                        # loads in order to avoid multiple loads from disk
                        # while keeping the RAM footprint low.
                        v_lhs = datasets[0].variables[k].load()
                        # We'll need to know later on if variables are equal.
                        computed = []
                        for ds_rhs in datasets[1:]:
                            v_rhs = ds_rhs.variables[k].compute()
                            computed.append(v_rhs)
                            if not v_lhs.equals(v_rhs):
                                concat_over.add(k)
                                equals[k] = False
                                # computed variables are not to be re-computed
                                # again in the future
                                for ds, v in zip(datasets[1:], computed):
                                    ds.variables[k].data = v.data
                                break
                        else:
                            equals[k] = True

            elif opt == 'all':
                concat_over.update(set(getattr(datasets[0], subset)) -
                                   set(datasets[0].dims))
            elif opt == 'minimal':
                pass
            else:
                raise ValueError("unexpected value for %s: %s" % (subset, opt))
        else:
            invalid_vars = [k for k in opt
                            if k not in getattr(datasets[0], subset)]
            if invalid_vars:
                if subset == 'coords':
                    raise ValueError(
                        'some variables in coords are not coordinates on '
                        'the first dataset: %s' % (invalid_vars,))
                else:
                    raise ValueError(
                        'some variables in data_vars are not data variables '
                        'on the first dataset: %s' % (invalid_vars,))
            concat_over.update(opt)

    process_subset_opt(data_vars, 'data_vars')
    process_subset_opt(coords, 'coords')
    return concat_over, equals

def build_from_table(self):

        table_parts = []

        # get the table sql for each table
        for table in self.tables:
            sql = table.get_sql()
            if len(sql):
                table_parts.append(sql)

        # combine all table sql separated by a comma
        sql = 'FROM {0} '.format(', '.join(table_parts))

        return sql

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


Question:
returns whether the collection has already been reported on

@param stackPos
the position on the opstack to check

@return whether the collection has already been reported.

private boolean alreadyReported(int stackPos) {
        if (stack.getStackDepth() <= stackPos) {
            return false;
        }

        OpcodeStack.Item item = stack.getStackItem(stackPos);
        XField field = item.getXField();
        if (field == null) {
            return false;
        }

        String fieldName = field.getName();
        return !checkedFields.add(fieldName);
    }

public void updateIndex(ChangesHolder changes, ChangesHolder parentChanges)
   {
      // pass lists to search manager
      if (searchManager != null && changes != null)
      {
         try
         {
            searchManager.apply(changes);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               handler.logErrorChanges(new HashSet<String>(changes.getRemove()), new HashSet<String>(changes
                  .getAddIds()));
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
      // pass lists to parent search manager
      if (parentSearchManager != null && parentChanges != null)
      {
         try
         {
            parentSearchManager.apply(parentChanges);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               parentHandler.logErrorChanges(new HashSet<String>(parentChanges.getRemove()), new HashSet<String>(
                  parentChanges.getAddIds()));
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
   }

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


Question: Merges two localization languages and return merged YAML string and indexes of added lines.

public function addStringsFromAnotherLanguage($destContents, $srcArray)
    {
        // 1. Find array keys that exists in the source array and don't exist in the destination array
        // 2. Merge the arrays recursively
        // 3. To find which lines were added:
        //    3.1 get a YAML representation of the destination array
        //    3.2 walk through the missing paths obtained in step 1 and for each path:
        //    3.3 find its path and its corresponding line in the string from 3.1.

        $result = [
            'strings' => '',
            'mismatch' => false,
            'updatedLines' => [],
        ];

        try
        {
            $destArray = Yaml::parse($destContents);
        }
        catch (Exception $ex) {
            throw new ApplicationException(sprintf('Cannot parse the YAML content: %s', $ex->getMessage()));
        }

        if (!$destArray) {
            $result['strings'] = $this->arrayToYaml($srcArray);
            return $result;
        }

        $mismatch = false;
        $missingPaths = $this->findMissingPaths($destArray, $srcArray, $mismatch);
        $mergedArray = self::arrayMergeRecursive($srcArray, $destArray);

        $destStrings = $this->arrayToYaml($mergedArray);
        $addedLines = $this->getAddedLines($destStrings, $missingPaths);

        $result['strings'] = $destStrings;
        $result['updatedLines'] = $addedLines['lines'];
        $result['mismatch'] = $mismatch || $addedLines['mismatch'];

        return $result;
    }

def save_translations(self, instance, translated_data):

        for meta in self.Meta.model._parler_meta:
            translations = translated_data.get(meta.rel_name, {})
            for lang_code, model_fields in translations.items():
                translation = instance._get_translated_model(lang_code, auto_create=True, meta=meta)
                for field, value in model_fields.items():
                    setattr(translation, field, value)

        # Go through the same hooks as the regular model,
        # instead of calling translation.save() directly.
        instance.save_translations()

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


Question:
Returns the SheetResources instance that provides access to Sheet resources.

@return the sheet resources

public SheetResources sheetResources() {
        if (sheets.get() == null) {
            sheets.compareAndSet(null, new SheetResourcesImpl(this));
        }
        return sheets.get();
    }

public static function request($api, $param_keys, $signType = false)
    {
        $params = array_filter(Datasheet::get($param_keys));

        if ($signType !== false) {
            $params['Hash'] = self::signature($signType);
        }

        $client = new Client();
        $option = ['form_params' => $params];

        if (Datasheet::get('SandBoxMode') === "true") {
            $url = self::SANDBOX_DOMAIN . $api;
        } else {
            $url = self::PRODUCT_DOMAIN . $api;
        }

        $response = $client->request('POST', $url, $option);

        if ($response->getStatusCode() != '200') {
            throw new \Exception('网络发生错误，请稍后再试。cURL返回码：' . $response->getReasonPhrase());
        }
        $json = $response->getBody()->getContents();

        return self::response(json_decode($json, true));
    }

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


Question: Determines if the given layer is a rectangular layer

function isRectLayer(layer) {
	var method = layer._method;
	return (method === $.fn.drawRect || method === $.fn.drawEllipse || method === $.fn.drawImage);
}

def raster_work
      parents.select do |parent|
        parent.class.included_modules.include?(::GeoWorks::RasterWorkBehavior)
      end.to_a
    end

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


Question: Set the PB Id for this device.

def pb_id(self, pb_id: str):
        """"""
        # FIXME(BMo) instead of creating the object to check if the PB exists
        #            use a method on PB List?
        # ProcessingBlock(pb_id)
        self.set_state(DevState.ON)
        self._pb_id = pb_id

public static String toPDB(Atom a){
		StringBuffer w = new StringBuffer();

		toPDB(a,w);

		return w.toString();

	}

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


Question: // ListDir is part of the Conn interface

func (st *StatsConn) ListDir(ctx context.Context, dirPath string, full bool) ([]DirEntry, error) {
	startTime := time.Now()
	statsKey := []string{"ListDir", st.cell}
	defer topoStatsConnTimings.Record(statsKey, startTime)
	res, err := st.conn.ListDir(ctx, dirPath, full)
	if err != nil {
		topoStatsConnErrors.Add(statsKey, int64(1))
		return res, err
	}
	return res, err
}

public function write(string $file, string $contents): DirectoryInterface
    {
        $this->filesystem->write("{$this->directory}/{$file}", $contents);

        return $this;
    }

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


Question:
// ImageLoad loads an image in the docker host from the client host.
// It's up to the caller to close the io.ReadCloser in the
// ImageLoadResponse returned by this function.

func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
	v := url.Values{}
	v.Set("quiet", "0")
	if quiet {
		v.Set("quiet", "1")
	}
	headers := map[string][]string{"Content-Type": {"application/x-tar"}}
	resp, err := cli.postRaw(ctx, "/images/load", v, input, headers)
	if err != nil {
		return types.ImageLoadResponse{}, err
	}
	return types.ImageLoadResponse{
		Body: resp.body,
		JSON: resp.header.Get("Content-Type") == "application/json",
	}, nil
}

def update(self, lb, name=None, algorithm=None, protocol=None,
            halfClosed=None, port=None, timeout=None, httpsRedirect=None):

        body = {}
        if name is not None:
            body["name"] = name
        if algorithm is not None:
            body["algorithm"] = algorithm
        if protocol is not None:
            body["protocol"] = protocol
        if halfClosed is not None:
            body["halfClosed"] = halfClosed
        if port is not None:
            body["port"] = port
        if timeout is not None:
            body["timeout"] = timeout
        if httpsRedirect is not None:
            body["httpsRedirect"] = httpsRedirect
        if not body:
            # Nothing passed
            return
        body = {"loadBalancer": body}
        uri = "/loadbalancers/%s" % utils.get_id(lb)
        try:
            resp, resp_body = self.api.method_put(uri, body=body)
        except exc.ClientException as e:
            message = e.message
            details = e.details
            if message and details:
                errmsg = "%s - %s" % (message, details)
            else:
                errmsg = message
            raise exc.InvalidLoadBalancerParameters(errmsg)
        return resp, resp_body

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


Question:
Returns request types supported by a service desk instance.
        :param service_desk: The service desk instance.
        :type service_desk: ServiceDesk
        :rtype: List[RequestType]

def request_types(self, service_desk):

        if hasattr(service_desk, 'id'):
            service_desk = service_desk.id
        url = (self._options['server'] +
               '/rest/servicedeskapi/servicedesk/%s/requesttype'
               % service_desk)
        headers = {'X-ExperimentalApi': 'opt-in'}
        r_json = json_loads(self._session.get(url, headers=headers))
        request_types = [
            RequestType(self._options, self._session, raw_type_json)
            for raw_type_json in r_json['values']]
        return request_types

def add(self, child):

        if isinstance(child, Run):
            self.add_run(child)
        elif isinstance(child, Record):
            self.add_record(child)
        elif isinstance(child, EventRecord):
            self.add_event_record(child)
        elif isinstance(child, DataDisplay):
            self.add_data_display(child)
        elif isinstance(child, DataWriter):
            self.add_data_writer(child)
        elif isinstance(child, EventWriter):
            self.add_event_writer(child)
        else:
            raise ModelError('Unsupported child element')

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


Question:
Get an item from the cache, or store the default value.

@param  string        $key
@param  \DateTime|int $minutes
@param  \Closure      $callback
@return mixed

public function remember($key, $minutes, Closure $callback)
    {
        return $this->cache->remember($key, $minutes, $callback);
    }

public function profile($description, \Closure $callback) {
        $this->startGroup($description);
        $returnVar = $callback();
        $this->endGroup($description);
        return $returnVar;
    }

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


Question:
/* PROTECTED METHODS
***********************************************************************

protected function getRedirectUri()
    {
        if (isset($_POST['redirect'])) {
            return $_POST['redirect'];
        }
        if (isset($_GET['redirect'])) {
            return $_GET['redirect'];
        }
        return \Staq::App()->getCurrentUri();
    }

public Set<HttpMethod> allAllowedMethods() {
		if (anyMethodRouter.size() > 0) {
			Set<HttpMethod> ret = new HashSet<HttpMethod>(9);
			ret.add(HttpMethod.CONNECT);
			ret.add(HttpMethod.DELETE);
			ret.add(HttpMethod.GET);
			ret.add(HttpMethod.HEAD);
			ret.add(HttpMethod.OPTIONS);
			ret.add(HttpMethod.PATCH);
			ret.add(HttpMethod.POST);
			ret.add(HttpMethod.PUT);
			ret.add(HttpMethod.TRACE);
			return ret;
		} else {
			return new HashSet<HttpMethod>(routers.keySet());
		}
	}

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


Question:
Displays the columns for a row

@param mixed $row the row to display.
@param mixed $next_row the next row that will be displayed. If there is
no next row, this is null.
@param integer $count the ordinal position of the current row. Starts
at one.

protected function displayRowColumns($row, $next_row, $count)
    {
        // Make sure we should display a row for the current data. If there
        // are no visible columns for the row data, just skip displaying the
        // entire row.
        $should_show_row = false;
        foreach ($this->getVisibleColumns() as $column) {
            if ($column->hasVisibleRenderer($row)) {
                $should_show_row = true;
                break;
            }
        }

        // Display a row of data.
        if ($should_show_row) {
            $tr_tag = new SwatHtmlTag('tr');
            $tr_tag->class = $this->getRowClassString($row, $count);

            foreach ($this->columns as $column) {
                $tr_tag->addAttributes($column->getTrAttributes($row));
            }

            if ($this->rowHasMessage($row)) {
                $tr_tag->class .= ' swat-error';
            }

            $tr_tag->open();

            foreach ($this->columns as $column) {
                $column->display($row);
            }

            $tr_tag->close();
        }
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
Generates a CFile from its json representation

@param jObj JSON object representing a CFile
@return the CFile object corresponding to the JSON object

private CFile parseCFile( JSONObject jObj )
    {
        CFile cfile;

        if ( jObj.optBoolean( "is_dir", false ) ) {
            cfile = new CFolder( new CPath( jObj.getString( "path" ) ) );

        } else {
            cfile = new CBlob( new CPath( jObj.getString( "path" ) ), jObj.getLong( "bytes" ), jObj.getString( "mime_type" ) );
            String stringDate = jObj.getString( "modified" );

            try {
                // stringDate looks like: "Fri, 07 Mar 2014 17:47:55 +0000"
                SimpleDateFormat sdf = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z", Locale.US );
                Date modified = sdf.parse( stringDate );
                cfile.setModificationDate( modified );

            } catch ( ParseException ex ) {
                throw new CStorageException( "Can't parse date modified: " + stringDate + " (" + ex.getMessage() + ")", ex );
            }
        }

        return cfile;
    }

def download(self, uuid, url, forced_file_name=None,
                 progress_bar=True, chunk_size=256,
                 directory=None, overwrite=False):

        self.last_req_time = None
        url = self.get_full_url(url)
        self.log.debug("download url : " + url)
        # Building request
        request = urllib2.Request(url)
        # request.add_header('Content-Type', 'application/json; charset=UTF-8')
        request.add_header('Accept', 'application/json,*/*;charset=UTF-8')
        # request start
        starttime = datetime.datetime.now()
        # doRequest
        resultq = urllib2.urlopen(request)
        code = resultq.getcode()
        file_name = uuid
        self.log.debug("ret code : '" + str(code) + "'")
        if code == 200:
            content_lenth = resultq.info().getheader('Content-Length')
            if not content_lenth:
                msg = "No content lengh header found !"
                self.log.debug(msg)
                progress_bar = False
            else:
                file_size = int(content_lenth.strip())
            if forced_file_name:
                file_name = forced_file_name
            else:
                content_dispo = resultq.info().getheader('Content-disposition')
                if content_dispo:
                    content_dispo = content_dispo.strip()
                    file_name = extract_file_name(content_dispo)
            if directory:
                if os.path.isdir(directory):
                    file_name = directory + "/" + file_name
            if os.path.isfile(file_name):
                if not overwrite:
                    cpt = 1
                    while 1:
                        if not os.path.isfile(file_name + "." + str(cpt)):
                            file_name += "." + str(cpt)
                            break
                        cpt += 1
                else:
                    self.log.warn("'%s' already exists. It was overwriten.",
                                  file_name)
            stream = None
            pbar = None
            if progress_bar:
                widgets = [FileTransferSpeed(), ' <<<', Bar(), '>>> ',
                           Percentage(), ' ', ETA()]
                pbar = ProgressBar(widgets=widgets, maxval=file_size)
                stream = FileWithCallback(file_name, 'w', pbar.update,
                                          file_size, file_name)
                pbar.start()
            else:
                stream = file(file_name, 'w')
            while 1:
                chunk = resultq.read(chunk_size)
                if not chunk:
                    break
                stream.write(chunk)
            stream.flush()
            stream.close()
            if pbar:
                pbar.finish()
        # request end
        endtime = datetime.datetime.now()
        self.last_req_time = str(endtime - starttime)
        self.log.debug("download url : %(url)s : request time : %(time)s",
                       {"url": url,
                        "time": self.last_req_time})
        return (file_name, self.last_req_time)

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


Question: // GetImageStream retrieves a named image stream

func (c Client) GetImageStream(ctx context.Context, name string, options *metav1.GetOptions) (*imagev1.ImageStream, error) {
	return c.ImageStreams.ImageStreams(apirequest.NamespaceValue(ctx)).Get(name, *options)
}

public function img($src, $alt = '', $class = '', $attributes = [])
    {
        return sprintf('<img src="%s" alt="%s" class="%s" %s>',
            $this->url($src),
            $alt,
            $class,
            $this->HtmlAttributes($attributes)
        );
    }

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


Question:
Handles the specified flask request for one of the POST URLS
    Invokes the specified endpoint to generate a response.

def handleFlaskPostRequest(flaskRequest, endpoint):

    if flaskRequest.method == "POST":
        return handleHttpPost(flaskRequest, endpoint)
    elif flaskRequest.method == "OPTIONS":
        return handleHttpOptions()
    else:
        raise exceptions.MethodNotAllowedException()

func NewCoindesk(client *http.Client, channels *BotChannels) (coindesk Exchange, err error) {
	reqs := newRequests()
	reqs.price, err = http.NewRequest(http.MethodGet, CoindeskURLs.Price, nil)
	if err != nil {
		return
	}
	coindesk = &CoindeskExchange{
		CommonExchange: newCommonExchange(Coindesk, client, reqs, channels),
	}
	return
}

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