Question:
@param Exception|Throwable $exception

@return string

private function formatExceptionStacktrace($exception)
    {
        if (!$exception instanceof Throwable) {
            return '';
        }

        $trace = $this->formatStacktraceEntry('ERR', [
            'function' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
        ]);

        if (!$this->logStacktraces) {
            return $trace;
        }

        foreach ($exception->getTrace() as $index => $entry) {
            $trace .= $this->formatStacktraceEntry(sprintf('#%d', $index), $entry);
        }

        return $trace;
    }

private void readTag() throws XMLException, IOException {
		try {
			char c;
			if ((c = stream.read()) == '!') {
				readTagExclamation();
			} else if (c == '?') {
				readProcessingInstruction();
			} else if (c == '/') {
				readEndTag();
			} else if (isNameStartChar(c)) {
				readStartTag(c);
			} else {
				throw new XMLException(getPosition(), "Unexpected character", Character.valueOf(c));
			}
		} catch (EOFException e) {
			throw new XMLException(getPosition(), new LocalizableString("lc.xml.error", "Unexpected end"),
					new LocalizableString("lc.xml.error", "in XML document"));
		}
	}

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


Question:
Build select query string and bindings

@param $statements

@throws Exception
@return array

public function select($statements)
    {
        if (!array_key_exists('tables', $statements)) {
            throw new Exception('No table specified.', 3);
        } elseif (!array_key_exists('selects', $statements)) {
            $statements['selects'][] = '*';
        }

        // From
        $tables = $this->arrayStr($statements['tables'], ', ');
        // Select
        $selects = $this->arrayStr($statements['selects'], ', ');

        // Wheres
        list($whereCriteria, $whereBindings) = $this->buildCriteriaWithType($statements, 'wheres', 'WHERE');
        // Group bys
        $groupBys = '';
        if (isset($statements['groupBys']) && $groupBys = $this->arrayStr($statements['groupBys'], ', ')) {
            $groupBys = 'GROUP BY ' . $groupBys;
        }

        // Order bys
        $orderBys = '';
        if (isset($statements['orderBys']) && is_array($statements['orderBys'])) {
            foreach ($statements['orderBys'] as $orderBy) {
                $orderBys .= $this->wrapSanitizer($orderBy['field']) . ' ' . $orderBy['type'] . ', ';
            }

            if ($orderBys = trim($orderBys, ', ')) {
                $orderBys = 'ORDER BY ' . $orderBys;
            }
        }

        // Limit and offset
        $limit = isset($statements['limit']) ? 'LIMIT ' . $statements['limit'] : '';
        $offset = isset($statements['offset']) ? 'OFFSET ' . $statements['offset'] : '';

        // Having
        list($havingCriteria, $havingBindings) = $this->buildCriteriaWithType($statements, 'havings', 'HAVING');

        // Joins
        $joinString = $this->buildJoin($statements);

        $sqlArray = array(
            'SELECT' . (isset($statements['distinct']) ? ' DISTINCT' : ''),
            $selects,
            'FROM',
            $tables,
            $joinString,
            $whereCriteria,
            $groupBys,
            $havingCriteria,
            $orderBys,
            $limit,
            $offset
        );

        $sql = $this->concatenateQuery($sqlArray);

        $bindings = array_merge(
            $whereBindings,
            $havingBindings
        );

        return compact('sql', 'bindings');
    }

private void doInterceptBeforeQuery(Class<?> clazz, StringBuilder sql, List<Object> args) {
        for (DBHelperInterceptor interceptor : interceptors) {
            boolean isContinue = interceptor.beforeSelect(clazz, sql.toString(), args);
            if (!isContinue) {
                throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
            }
        }
    }

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


Question: // RunOutput runs the command with the given arguments and returns the output of stdout.

func RunOutput(args ...string) ([]byte, error) {
	stdout := bytes.NewBuffer(nil)
	err := RunStdout(stdout, args...)
	return stdout.Bytes(), err
}

public function main()
    {
        $this->out('Welcome to the Proffer shell.');
        $this->out('This shell can be used to regenerate thumbnails and cleanup unlinked images.');
        $this->hr();
        $this->out($this->OptionParser->help());
    }

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


Question: // CompareAndSwap atomatically swaps the old with the new value.

func (s *AtomicString) CompareAndSwap(oldval, newval string) (swqpped bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.str == oldval {
		s.str = newval
		return true
	}
	return false
}

public void updateMapping(String virtual, String physical, String archive, String primary, short inspect, boolean toplevel, int listenerMode, int listenerType,
	    boolean readOnly) throws ExpressionException, SecurityException {
	checkWriteAccess();
	_updateMapping(virtual, physical, archive, primary, inspect, toplevel, listenerMode, listenerType, readOnly);
    }

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


Question: Get row_sparse data from row_sparse parameters based on row_id.

def _get_row_sparse(self, arr_list, ctx, row_id):

        # get row sparse params based on row ids
        if not isinstance(row_id, ndarray.NDArray):
            raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id)))
        if not self._trainer:
            raise RuntimeError("Cannot get row_sparse data for Parameter '%s' when no " \
                               "Trainer is created with it."%self.name)
        results = self._check_and_get(arr_list, ctx)

        # fetch row sparse params from the trainer
        self._trainer._row_sparse_pull(self, results, row_id)
        return results

def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

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


Question:
Filter the current collection by a user-defined function

@param callable $filter - the user-defined function to filter by
@param array $args - OPTIONAL array of arguments to pass to the callable
@return self

final public function filter(callable $filter, array $args = []): self
    {
        // Start a new Collection to collect the filtered results
        $collection = new Collection();

        // Iterate over current Collection
        iterator_apply(

            // Use $this object as the iterator
            $this,

            // Wrap callable in closure that alway returns true
            function(IteratorAggregate $iterator) use ($filter, $args, &$collection) {

                // Pass current element and optional arguments to callable
                if ($filter($iterator->current(), $args) === true) {

                    $collection->set(
                        $iterator->key(),
                        $iterator->current()
                    );
                }

                return true;
            },

            // Pass $this (again) to the function for reasons unbeknown to science
            // {@see https://www.reddit.com/r/lolphp/comments/5zkn29/what_the_hell_with_iterator_apply/}
            [$this->toArray()]
        );

        // Return filtered Collection
        return $collection;
    }

public function getController(Request $request)
    {
        $controller = $request->attributes->get('controller');

        if($request->attributes->has('_sub_request') && $request->attributes->get('_sub_request'))
        {
            $controller = $request->attributes->get('_controller');
        }

        if (!$controller)
        {
            if (null !== $this->logger)
            {
                $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing');
            }

            return false;
        }

        if(is_array($controller))
        {
            return $controller;
        }

        if(is_object($controller))
        {
            if (method_exists($controller, '__invoke'))
            {
                return $controller;
            }

            throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
        }

        $prepare = $this->prepare($request->attributes->all());

        $request->attributes->set('_bundle', $prepare['bundle']);
        $request->attributes->set('_controller', strtolower($prepare['parts'][1]));
        $request->attributes->set('_action', strtolower($prepare['parts'][2]));

        $callable = array($this->instantiateController($prepare['controller']), $prepare['action']);

        $request->attributes->set('_callable', $callable);

        if (!is_callable($callable))
        {
            throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', $controller, $request->getPathInfo()));
        }

        return $callable;
    }

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


Question: View aggregated application logs

function logs(appName, callback) {
    commons.get(format('/%s/apps/%s/logs/', deis.version, appName), callback);
  }

func (o *Enterprise) SyslogDestinations(info *bambou.FetchingInfo) (SyslogDestinationsList, *bambou.Error) {

	var list SyslogDestinationsList
	err := bambou.CurrentSession().FetchChildren(o, SyslogDestinationIdentity, &list, info)
	return list, err
}

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


Question:
Sets buckets ordering.

@param string $mode
@param string $direction

public function setOrder($mode, $direction = self::DIRECTION_ASC)
    {
        $this->orderMode = $mode;
        $this->orderDirection = $direction;
    }

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
@param  Type\Union $candidate
@param  bool       $is_property

@return void

private function convertPhpStormGenericToPsalmGeneric(Type\Union $candidate, $is_property = false)
    {
        $atomic_types = $candidate->getTypes();

        if (isset($atomic_types['array']) && count($atomic_types) > 1) {
            $iterator_name = null;
            $generic_params = null;

            try {
                foreach ($atomic_types as $type) {
                    if ($type instanceof Type\Atomic\TIterable
                        || ($type instanceof Type\Atomic\TNamedObject
                            && (!$type->from_docblock || $is_property)
                            && (
                                strtolower($type->value) === 'traversable'
                                || $this->classlikes->interfaceExtends(
                                    $type->value,
                                    'Traversable'
                                )
                                || $this->classlikes->classImplements(
                                    $type->value,
                                    'Traversable'
                                )
                            ))
                    ) {
                        $iterator_name = $type->value;
                    } elseif ($type instanceof Type\Atomic\TArray) {
                        $generic_params = $type->type_params;
                    }
                }
            } catch (\InvalidArgumentException $e) {
                // ignore class-not-found issues
            }

            if ($iterator_name && $generic_params) {
                if ($iterator_name === 'iterable') {
                    $generic_iterator = new Type\Atomic\TIterable($generic_params);
                } else {
                    if (strtolower($iterator_name) === 'generator') {
                        $generic_params[] = Type::getMixed();
                        $generic_params[] = Type::getMixed();
                    }
                    $generic_iterator = new Type\Atomic\TGenericObject($iterator_name, $generic_params);
                }

                $candidate->removeType('array');
                $candidate->addType($generic_iterator);
            }
        }
    }

public function addParticipation($testIdentifier, $variationIdentifier)
    {
        Assert::string($testIdentifier, 'Test identifier must be a string');
        Assert::string($variationIdentifier, 'Variation name must be a string');

        $this->participations[$testIdentifier] = $variationIdentifier;
    }

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


Question:
Get a list of corporations the current
authenticated user has access to.

@deprecated replace by new ACL system. Must be move to ACL trait

@return mixed

public function getCharacterCorporations()
    {

        // TODO : rewrite the method according to the new ACL mechanic

        $user = auth()->user();

        $corporations = ApiKeyInfoCharacters::join(
            'eve_api_keys',
            'eve_api_keys.key_id', '=',
            'account_api_key_info_characters.keyID')
            ->distinct();

        // If the user us a super user, return all
        if (! $user->hasSuperUser()) {

            $corporations = $corporations->orWhere(function ($query) use ($user) {

                // If the user has any affiliations and can
                // list those characters, add them
                if ($user->has('character.list', false))
                    $query = $query->whereIn('characterID',
                        array_keys($user->getAffiliationMap()['char']));

                // Add any characters from owner API keys
                $query->orWhere('eve_api_keys.user_id', $user->id);
            });
        }

        return $corporations->orderBy('corporationName')
            ->pluck('corporationName');
    }

def unauthorized(cls, errors=None):

        if cls.expose_status:  # pragma: no cover
            cls.response.content_type = 'application/json'
            cls.response._status_line = '401 Unauthorized'

        return cls(401, errors=errors).to_json

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


Question:
Turn this item object into a generic array

@return array

public function transform(Did $did)
    {
        return [
            'id'    => $did->id,
            'text'  => $did->text,
            'created_at' => $did->created_at->toIso8601String()
        ];
    }

protected function storeToAll(FeatureInterface $feature)
    {
        $name = $feature->getName();

        if (!isset($this->all[$name])) {
            $this->all[$name] = [];
        }

        $this->all[$name][$feature->getProvider()->getName()] = $feature;
    }

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


Question:
Calculate the rotation angle for a structure
@param afpChain
@return The rotation angle, in radians
@throws StructureException If the alignment doesn't contain any blocks
@throws NullPointerException If the alignment doesn't have a rotation matrix set

public static double getAngle(AFPChain afpChain) throws StructureException {
		if(afpChain.getBlockNum() < 1) {
			throw new StructureException("No aligned residues");
		}
		Matrix rotation = afpChain.getBlockRotationMatrix()[0];

		if(rotation == null) {
			throw new NullPointerException("AFPChain does not contain a rotation matrix");
		}
		return getAngle(rotation);
	}

protected function getRouteResource($route)
	{
		if (!config('openapischemas.resource_tag')) {
			$this->parentCommand->error('The "resource_tag" value in your apischemas.php configuration file must defined.');
			exit();
		}
		$routeAction = $route->getAction();
		list($class, $method) = explode('@', $routeAction['uses']);
		$reflection = new ReflectionClass($class);

		$comment = $reflection->getDocComment();
		if ($comment) {
			$docBlock = $this->docBlockFactory->create($comment);
			foreach ($docBlock->getTags() as $tag) {
				if ($tag->getName() === config('openapischemas.resource_tag')) {
					return $tag->getDescription()->render();
				}
			}
		}

		return null;
	}

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


Question:
Get an individual value from the existing field array.
@param index -
@param valueDestination - where the SFVec3f value is returned

public void get1Value(int index, float[] valueDestination) {
        try {
            SFVec3f sfVec3f = value.get(index);
            valueDestination[0] = sfVec3f.x;
            valueDestination[1] = sfVec3f.y;
            valueDestination[2] = sfVec3f.z;
        }
        catch (IndexOutOfBoundsException e) {
            Log.e(TAG, "X3D MFVec3f get1Value(index) out of bounds." + e);
        }
        catch (Exception e) {
            Log.e(TAG, "X3D MFVec3f get1Value(index) exception " + e);
        }
    }

protected function handleWriteCustomer($request, $id = null)
    {
        $customer = $id ? $this->getCustomer($id) : null;

        $form = $this->formFactory->createNamed(null, 'sonata_customer_api_form_customer', $customer, [
            'csrf_protection' => false,
        ]);

        $form->handleRequest($request);

        if ($form->isValid()) {
            $customer = $form->getData();
            $this->customerManager->save($customer);

            $context = new Context();
            $context->setGroups(['sonata_api_read']);

            // simplify when dropping FOSRest < 2.1
            if (method_exists($context, 'enableMaxDepth')) {
                $context->enableMaxDepth();
            } else {
                $context->setMaxDepth(10);
            }

            $view = FOSRestView::create($customer);
            $view->setContext($context);

            return $view;
        }

        return $form;
    }

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


Question:
Completes the command name with its namespace.

@param string $name

@return \Symfony\Component\Console\Command\Command

@throws \InvalidArgumentException

@api

public function setName($name): \Symfony\Component\Console\Command\Command
    {
        if (!$this->namespace) {
            return parent::setName($name);
        }
        return parent::setName(sprintf('%s:%s', $this->namespace, $name));
    }

func NewShowCommand() cmd.Command {
	cmd := &showCommand{}
	cmd.newAPIFunc = func() (StorageShowAPI, error) {
		return cmd.NewStorageAPI()
	}
	return modelcmd.Wrap(cmd)
}

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


Question: (13:0) {#if !scrimVisible}

function create_if_block(component, ctx) {
	var button;

	function click_handler(event) {
		component.set({ scrimVisible: true });
	}

	return {
		c() {
			button = createElement("button");
			button.textContent = "Preview Scrim";
			addListener(button, "click", click_handler);
		},

		m(target, anchor) {
			insert(target, button, anchor);
		},

		p: noop,

		d(detach) {
			if (detach) {
				detachNode(button);
			}

			removeListener(button, "click", click_handler);
		}
	};
}

function visible(plugin_name) {
  var obj = get_base_object();
  obj.config = scoped_config(plugin_name);
  obj.logger = scoped_logger(plugin_name);
  return obj;
}

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


Question: // add will only add services in list that don't exist, else failed

func (s *Services) add(newServs []*apitypes.UserService) error {
	var err error
	// check if adding service conflict with existing ones
	exist := make(map[serviceKey]bool, s.size())
	for _, srv := range s.spec {
		exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
	}
	for _, srv := range newServs {
		if exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] {
			err = fmt.Errorf("service %v conflicts with existing ones", newServs)
			s.Log(ERROR, err)
			return err
		}
		exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
	}

	// if pod is running, convert service to patch and send to vm
	if s.p.IsRunning() {
		if err = s.commit(newServs, "add"); err != nil {
			return err
		}
	}
	s.spec = append(s.spec, newServs...)

	return nil
}

public function getTrashService()
    {
        if (null === $this->trashService) {
            $this->trashService = new TrashService(
                $this->getLocationService(),
                $this->client,
                $this->inputDispatcher,
                $this->outputVisitor,
                $this->requestParser
            );
        }

        return $this->trashService;
    }

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


Question:
// ToBPFData converts the counter into a set of prefix lengths that the BPF
// datapath can use for LPM lookup.

func (p *PrefixLengthCounter) ToBPFData() (s6, s4 []int) {
	p.RLock()
	defer p.RUnlock()

	return p.v6.ToBPFData(), p.v4.ToBPFData()
}

def ReadFlowLogEntries(self,
                         client_id,
                         flow_id,
                         offset,
                         count,
                         with_substring=None,
                         cursor=None):
    """"""

    query = ("SELECT message, UNIX_TIMESTAMP(timestamp) "
             "FROM flow_log_entries "
             "FORCE INDEX (flow_log_entries_by_flow) "
             "WHERE client_id = %s AND flow_id = %s ")
    args = [db_utils.ClientIDToInt(client_id), db_utils.FlowIDToInt(flow_id)]

    if with_substring is not None:
      query += "AND message LIKE %s "
      args.append("%{}%".format(with_substring))

    query += "ORDER BY log_id ASC LIMIT %s OFFSET %s"
    args.append(count)
    args.append(offset)

    cursor.execute(query, args)

    ret = []
    for message, timestamp in cursor.fetchall():
      ret.append(
          rdf_flow_objects.FlowLogEntry(
              message=message,
              timestamp=mysql_utils.TimestampToRDFDatetime(timestamp)))

    return ret

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


Question:
// nipN is an internal function that removes the nth item on the stack and
// returns it.
//
// Stack transformation:
// nipN(0): [... x1 x2 x3] -> [... x1 x2]
// nipN(1): [... x1 x2 x3] -> [... x1 x3]
// nipN(2): [... x1 x2 x3] -> [... x2 x3]

func (s *stack) nipN(idx int32) ([]byte, error) {
	sz := int32(len(s.stk))
	if idx < 0 || idx > sz-1 {
		str := fmt.Sprintf("index %d is invalid for stack size %d", idx,
			sz)
		return nil, scriptError(ErrInvalidStackOperation, str)
	}

	so := s.stk[sz-idx-1]
	if idx == 0 {
		s.stk = s.stk[:sz-1]
	} else if idx == sz-1 {
		s1 := make([][]byte, sz-1)
		copy(s1, s.stk[1:])
		s.stk = s1
	} else {
		s1 := s.stk[sz-idx : sz]
		s.stk = s.stk[:sz-idx-1]
		s.stk = append(s.stk, s1...)
	}
	return so, nil
}

def random_deletion(self,fastq,rate):

    sequence = fastq.sequence
    quality = fastq.qual
    seq = ''
    qual = None
    if quality: qual = ''
    for i in range(len(sequence)):
      # check context
      prev = None
      if i >= 1: prev = sequence[i-1]
      next = None
      if i < len(sequence)-1: next = sequence[i+1]
      if self._before_base and (not prev or prev != self._before_base):
        seq+=sequence[i]
        if quality: qual+=quality[i]
        continue
      if self._after_base and (not next or next != self._after_base):
        seq+=sequence[i]
        if quality: qual+=quality[i]
        continue
      if self._observed_base and (sequence[i] != self._observed_base):
        seq+=sequence[i]
        if quality: qual+=quality[i]
        continue

      rnum = self.random.random()
      if rnum >= rate:
        seq += sequence[i]
        if quality: qual+=quality[i]
    return FASTQ('@'+fastq.header+"\n"+seq+"\n+\n"+qual+"\n")

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


Question:
Simple implementation of variable merging. Variables are only overridden if they have the same name and are
in the same scope (ie are process instance, task or case execution variables).

protected void mergeVariables(TaskQueryImpl extendedQuery, TaskQueryImpl extendingQuery) {
    List<TaskQueryVariableValue> extendingVariables = extendingQuery.getVariables();

    Set<TaskQueryVariableValueComparable> extendingVariablesComparable = new HashSet<TaskQueryVariableValueComparable>();

    // set extending variables and save names for comparison of original variables
    for (TaskQueryVariableValue extendingVariable : extendingVariables) {
      extendedQuery.addVariable(extendingVariable);
      extendingVariablesComparable.add(new TaskQueryVariableValueComparable(extendingVariable));
    }

    for (TaskQueryVariableValue originalVariable : this.getVariables()) {
      if (!extendingVariablesComparable.contains(new TaskQueryVariableValueComparable(originalVariable))) {
        extendedQuery.addVariable(originalVariable);
      }
    }

  }

def main():

    # Define Parser object and add to toil
    parser = build_parser()
    Job.Runner.addToilOptions(parser)
    args = parser.parse_args()
    # Store inputs from argparse
    inputs = {'config': args.config,
              'config_fastq': args.config_fastq,
              'input': args.input,
              'unc.bed': args.unc,
              'hg19.transcripts.fa': args.fasta,
              'composite_exons.bed': args.composite_exons,
              'normalize.pl': args.normalize,
              'output_dir': args.output_dir,
              'rsem_ref.zip': args.rsem_ref,
              'chromosomes.zip': args.chromosomes,
              'ebwt.zip': args.ebwt,
              'ssec': args.ssec,
              's3_dir': args.s3_dir,
              'sudo': args.sudo,
              'single_end_reads': args.single_end_reads,
              'upload_bam_to_s3': args.upload_bam_to_s3,
              'uuid': None,
              'sample.tar': None,
              'cpu_count': None}

    # Launch jobs
    Job.Runner.startToil(Job.wrapJobFn(download_shared_files, inputs), args)

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


Question:
This decorator allows you to access ``ctx.bitshares`` which is
        an instance of BitShares with ``offline=True``.

def offline(f):

    @click.pass_context
    @verbose
    def new_func(ctx, *args, **kwargs):
        ctx.obj["offline"] = True
        ctx.bitshares = BitShares(**ctx.obj)
        ctx.blockchain = ctx.bitshares
        ctx.bitshares.set_shared_instance()
        return ctx.invoke(f, *args, **kwargs)

    return update_wrapper(new_func, f)

def version_info(self):

        # Retrive and show local version info
        package = pkg.get_distribution('git-up')
        local_version_str = package.version
        local_version = package.parsed_version

        print('GitUp version is: ' + colored('v' + local_version_str, 'green'))

        if not self.settings['updates.check']:
            return

        # Check for updates
        print('Checking for updates...', end='')

        try:
            # Get version information from the PyPI JSON API
            reader = codecs.getreader('utf-8')
            details = json.load(reader(urlopen(PYPI_URL)))
            online_version = details['info']['version']
        except (HTTPError, URLError, ValueError):
            recent = True  # To not disturb the user with HTTP/parsing errors
        else:
            recent = local_version >= pkg.parse_version(online_version)

        if not recent:
            # noinspection PyUnboundLocalVariable
            print(
                '\rRecent version is: '
                + colored('v' + online_version, color='yellow', attrs=['bold'])
            )
            print('Run \'pip install -U git-up\' to get the update.')
        else:
            # Clear the update line
            sys.stdout.write('\r' + ' ' * 80 + '\n')

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


Question: // SetRoomArn sets the RoomArn field's value.

func (s *DeleteSkillAuthorizationInput) SetRoomArn(v string) *DeleteSkillAuthorizationInput {
	s.RoomArn = &v
	return s
}

@POST
    public void broadcast(String message) {
        AtmosphereResource r = (AtmosphereResource) request.getAttribute(ApplicationConfig.ATMOSPHERE_RESOURCE);

        if (r != null) {
            r.getBroadcaster().broadcast(message);
        } else {
            throw new IllegalStateException();
        }
    }

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


Question:
Call the pipe Closure or the method 'handle' in its class instance.

@param  mixed  $pipe
@param  mixed  $passable
@param  \Closure  $stack
@return \Closure
@throws \BadMethodCallException

protected function call($pipe, $passable, $stack)
    {
        if ($pipe instanceof Closure) {
            return call_user_func($pipe, $passable, $stack);
        }

        // The pipe is not a Closure instance.
        else if (! is_object($pipe)) {
            list($name, $parameters) = $this->parsePipeString($pipe);

            $pipe = $this->getContainer()->make($name);

            $parameters = array_merge(array($passable, $stack), $parameters);
        } else {
            $parameters = array($passable, $stack);
        }

        return call_user_func_array(array($pipe, $this->method), $parameters);
    }

func wrapRoute(middlewares *alice.Chain) func(*mux.Route, *mux.Router, []*mux.Route) error {
	return func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		handler, err := middlewares.Then(route.GetHandler())
		if err != nil {
			return err
		}

		route.Handler(handler)
		return nil
	}
}

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


Question:
Generate CSRF token.

@return string

public function generateCsrfToken() {
		$token = hash("sha512", mt_rand(0, mt_getrandmax()));
		$_SESSION[$this->csrfTokenSessionKey] = $token;
		return $token;
	}

def rws_call(ctx, method, default_attr=None):
    """"""
    try:
        response = ctx.obj['RWS'].send_request(method)

        if ctx.obj['RAW']:  # use response from RWS
            result = ctx.obj['RWS'].last_result.text
        elif default_attr is not None:  # human-readable summary
            result = ""
            for item in response:
                result = result + item.__dict__[default_attr] + "\n"
        else:  # use response from RWS
            result = ctx.obj['RWS'].last_result.text

        if ctx.obj['OUTPUT']:  # write to file
            ctx.obj['OUTPUT'].write(result.encode('utf-8'))
        else:  # echo
            click.echo(result)

    except RWSException as e:
        click.echo(str(e))

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


Question:
Adds a Node ID field to the root form view.

@param FormView      $view    The form view
@param FormInterface $form    The form
@param array         $options The options

public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $data = $this->context->getCurrentNodeId();

        if (!$view->parent && $options['compound'] and !empty($data)) {
            $factory = $form->getConfig()->getFormFactory();

            $form = $factory->createNamed($options['node_id_field_name'], 'hidden', $data, ['mapped' => false]);

            $view->children[$options['node_id_field_name']] = $form->createView($view);
        }
    }

public function setCoreRequestController($value)
    {
        $this->setFieldName('request_controller');
        $this->loadObject(true);
        $this->setFieldValue($value);

        return $this;
    }

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


Question:
Buffer the central file header record for a single entry.

@return true if the next central file header was buffered
@throws IOException if any problems occur

private boolean bufferNextCentralFileHeader() throws IOException {
        buffer.reset();

        if (currentCentralEntryIdx == processedEntries.size()) { return false; }

        ProcessedEntry entry = processedEntries.get(currentCentralEntryIdx++);

        JarEntry jarEntry = entry.jarEntry;
        bufferInt(ZipEntry.CENSIG);       // Central file header signature
        bufferShort(10);                  // Version made by
        bufferShort(10);                  // Extraction version
        bufferShort(0);                   // Flags
        bufferShort(ZipEntry.STORED);     // Compression type
        bufferInt(jarEntry.getTime());    // Entry time
        bufferInt(entry.crc);             // CRC
        bufferInt(jarEntry.getSize());    // Compressed size
        bufferInt(jarEntry.getSize());    // Uncompressed size
        byte[] nameBytes = jarEntry.getName().getBytes("UTF8");
        bufferShort(nameBytes.length);    // Entry name length
        bufferShort(0);                   // Extra field length
        bufferShort(0);                   // File comment length
        bufferShort(0);                   // Disk number start
        bufferShort(0);                   // Internal file attributes
        bufferInt(0);                     // External file attributes
        bufferInt(entry.offset);          // Relative offset of local header
        buffer(nameBytes);
        return true;
    }

private void switchToBackward() {
        assert(state == State.ITER_CHECK_FWD ||
                (state == State.ITER_IN_FCD_SEGMENT && pos == start) ||
                (state.compareTo(State.IN_NORM_ITER_AT_LIMIT) >= 0 && pos == 0));
        if(state == State.ITER_CHECK_FWD) {
            // Turn around from forward checking.
            limit = pos = iter.getIndex();
            if(pos == start) {
                state = State.ITER_CHECK_BWD;  // Check backward.
            } else {  // pos > start
                state = State.ITER_IN_FCD_SEGMENT;  // Stay in FCD segment.
            }
        } else {
            // Reached the start of the FCD segment.
            if(state == State.ITER_IN_FCD_SEGMENT) {
                // The input text segment is FCD, extend it backward.
            } else {
                // The input text segment needed to be normalized.
                // Switch to checking backward from it.
                if(state == State.IN_NORM_ITER_AT_LIMIT) {
                    iter.moveIndex(start - limit);
                }
                limit = start;
            }
            state = State.ITER_CHECK_BWD;
        }
    }

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


Question:
Attempt to fetch the size from the Content-Length response header.
If we cannot, return 0.

@return int The Size of the stream

private function getSizeFromMetadata()
    {
        foreach ($this->stream->getMetadata('wrapper_data') as $value) {
            if (substr($value, 0, 15) == "Content-Length:") {
                return (int) substr($value, 16);
            }
        }
        return 0;
    }

public function download($url)
	{
		$getResult = $this->session->get($url);

		if (!$getResult->success) {
			$this->error = array();
			$this->error['file'] = 'Download error (HTTP status: ' . $getResult->status_code . ')';
			$this->error['http'] = $getResult->status_code;
			return null;
		}
		return $getResult->body;
	}

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


Question: Object has been transitioned to an new state

def ObjectTransitionedEventHandler(obj, event):

    # only snapshot supported objects
    if not supports_snapshots(obj):
        return

    # default transition entry
    entry = {
        "modified": DateTime().ISO(),
        "action": event.action,
    }

    # get the last history item
    history = api.get_review_history(obj, rev=True)
    if history:
        entry = history[0]
        # make transitions also a modification entry
        timestamp = entry.pop("time", DateTime())
        entry["modified"] = timestamp.ISO()
        entry["action"] = event.action

    # take a new snapshot
    take_snapshot(obj, **entry)

    # reindex the object in the auditlog catalog
    reindex_object(obj)

def complete_transfer(self, relation, cleanup=True):

    relation.completed_at = utc_now().isoformat()
    self.data_access.update_model(relation)
    if cleanup:
      self.cleanup()
    return relation

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


Question:
// listenForNodeChanges listens for changes to node status using change feeds.
// This function will block until the query fails

func (c *Cluster) listenForNodeChanges() error {
	// Start listening to changes from a random active node
	node, hpr, err := c.GetNextNode()
	if err != nil {
		return err
	}

	q, err := newQuery(
		DB("rethinkdb").Table("server_status").Changes(),
		map[string]interface{}{},
		c.opts,
	)
	if err != nil {
		return fmt.Errorf("Error building query: %s", err)
	}

	cursor, err := node.Query(context.Background(), q) // no need for timeout due to Changes()
	if err != nil {
		hpr.Mark(err)
		return err
	}

	// Keep reading node status updates from changefeed
	var result struct {
		NewVal nodeStatus `rethinkdb:"new_val"`
		OldVal nodeStatus `rethinkdb:"old_val"`
	}
	for cursor.Next(&result) {
		addr := fmt.Sprintf("%s:%d", result.NewVal.Network.Hostname, result.NewVal.Network.ReqlPort)
		addr = strings.ToLower(addr)

		switch result.NewVal.Status {
		case "connected":
			// Connect to node using exponential backoff (give up after waiting 5s)
			// to give the node time to start-up.
			b := backoff.NewExponentialBackOff()
			b.MaxElapsedTime = time.Second * 5

			backoff.Retry(func() error {
				node, err := c.connectNodeWithStatus(result.NewVal)
				if err == nil {
					if !c.nodeExists(node) {
						c.addNode(node)

						Log.WithFields(logrus.Fields{
							"id":   node.ID,
							"host": node.Host.String(),
						}).Debug("Connected to node")
					}
				}

				return err
			}, b)
		}
	}

	err = cursor.Err()
	hpr.Mark(err)
	return err
}

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question:
Sets the id of this Shift.
        UUID for this object

        :param id: The id of this Shift.
        :type: str

def id(self, id):

        if id is None:
            raise ValueError("Invalid value for `id`, must not be `None`")
        if len(id) > 255:
            raise ValueError("Invalid value for `id`, length must be less than `255`")

        self._id = id

def get_delete_api(self, resource):

        parameters = self.delete_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}/' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            "responseClass": "void",
            'operations': [
                {
                    'httpMethod': 'DELETE',
                    'nickname': 'delete%s' % resource.model.__name__,
                    'summary': 'Delete %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

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


Question:
<p>
The associated API stages of a usage plan.
</p>

@param apiStages
The associated API stages of a usage plan.

public void setApiStages(java.util.Collection<ApiStage> apiStages) {
        if (apiStages == null) {
            this.apiStages = null;
            return;
        }

        this.apiStages = new java.util.ArrayList<ApiStage>(apiStages);
    }

protected function get_registered_options() {
		$rest_options = array();

		foreach ( get_registered_settings() as $name => $args ) {
			if ( empty( $args['show_in_rest'] ) ) {
				continue;
			}

			$rest_args = array();
			if ( is_array( $args['show_in_rest'] ) ) {
				$rest_args = $args['show_in_rest'];
			}

			$defaults = array(
				'name'   => ! empty( $rest_args['name'] ) ? $rest_args['name'] : $name,
				'schema' => array(),
			);
			$rest_args = array_merge( $defaults, $rest_args );

			$default_schema = array(
				'type'        => empty( $args['type'] ) ? null : $args['type'],
				'description' => empty( $args['description'] ) ? '' : $args['description'],
				'default'     => isset( $args['default'] ) ? $args['default'] : null,
			);

			$rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
			$rest_args['option_name'] = $name;

			// Skip over settings that don't have a defined type in the schema.
			if ( empty( $rest_args['schema']['type'] ) ) {
				continue;
			}

			// Whitelist the supported types for settings, as we don't want invalid types
			// to be updated with arbitrary values that we can't do decent sanitizing for.
			if ( ! in_array( $rest_args['schema']['type'], array( 'number', 'string', 'boolean' ), true ) ) {
				continue;
			}

			$rest_options[ $rest_args['name'] ] = $rest_args;
		}

		return $rest_options;
	}

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


Question:
if all elements in arr are 'some', their inner values are passed as arguments to f
f must have arity arr.length

function(arr, f) {
      var r = [];
      for (var i = 0; i < arr.length; i++) {
        var x = arr[i];
        if (x.isSome()) {
          r.push(x.getOrDie());
        } else {
          return Option.none();
        }
      }
      return Option.some(f.apply(null, r));
    }

def views_show_many(self, ids=None, **kwargs):
        ""
        api_path = "/api/v2/views/show_many.json"
        api_query = {}
        if "query" in kwargs.keys():
            api_query.update(kwargs["query"])
            del kwargs["query"]
        if ids:
            api_query.update({
                "ids": ids,
            })
        return self.call(api_path, query=api_query, **kwargs)

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


Question:
Get SSH key

REST: GET /cloud/project/{serviceName}/sshkey/{keyId}
@param keyId [required] SSH key id
@param serviceName [required] Project name

public OvhSshKeyDetail project_serviceName_sshkey_keyId_GET(String serviceName, String keyId) throws IOException {
		String qPath = "/cloud/project/{serviceName}/sshkey/{keyId}";
		StringBuilder sb = path(qPath, serviceName, keyId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhSshKeyDetail.class);
	}

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

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


Question:
Custom attribute writer method with validation
 @param [Object] tender_id Value to be assigned

def tender_id=(tender_id)
      if tender_id.nil?
        fail ArgumentError, "tender_id cannot be nil"
      end

      if tender_id.to_s.length > 192
        fail ArgumentError, "invalid value for 'tender_id', the character length must be smaller than or equal to 192."
      end

      if tender_id.to_s.length < 1
        fail ArgumentError, "invalid value for 'tender_id', the character length must be great than or equal to 1."
      end

      @tender_id = tender_id
    end

def onHello(self, realm, details):

        log.msg("onHello: {} {}".format(realm, details))

        self._pending_auth = None

        if details.authmethods:
            for authmethod in details.authmethods:
                if authmethod == u"wampcra":

                    ## lookup user in user DB
                    salt, key, role, uid = yield self.factory.userdb.get(details.authid)
                    log.msg("salt, key, role: {} {} {} {}".format(salt, key, role, uid))

                    ## if user found ..
                    if key:

                        log.msg("found key")

                        ## setup pending auth
                        self._pending_auth = PendingAuth(key, details.pending_session,
                            details.authid, role, authmethod, u"userdb", uid)

                        log.msg("setting challenge")
                        ## send challenge to client
                        extra = {
                            u'challenge': self._pending_auth.challenge
                        }

                        ## when using salted passwords, provide the client with
                        ## the salt and then PBKDF2 parameters used
                        if salt:
                            extra[u'salt'] = salt
                            extra[u'iterations'] = 1000
                            extra[u'keylen'] = 32

                        defer.returnValue(types.Challenge(u'wampcra', extra))

        ## deny client
        defer.returnValue(types.Deny())

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


Question: Configure an app key/value pair

def set(self, key, value):
        """"""
        cmd = [
            "heroku",
            "config:set",
            "{}={}".format(key, quote(str(value))),
            "--app",
            self.name,
        ]
        if self._is_sensitive_key(key):
            self._run_quiet(cmd)
        else:
            self._run(cmd)

public com.google.privacy.dlp.v2.KmsWrappedCryptoKeyOrBuilder getKmsWrappedOrBuilder() {
    if (sourceCase_ == 3) {
      return (com.google.privacy.dlp.v2.KmsWrappedCryptoKey) source_;
    }
    return com.google.privacy.dlp.v2.KmsWrappedCryptoKey.getDefaultInstance();
  }

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


Question:
// Download downloads recorded session from S3 bucket and writes the results into writer
// return trace.NotFound error is object is not found

func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error {
	written, err := l.downloader.DownloadWithContext(ctx, writer, &s3.GetObjectInput{
		Bucket: aws.String(l.Bucket),
		Key:    aws.String(l.path(sessionID)),
	})
	if err != nil {
		return ConvertS3Error(err)
	}
	if written == 0 {
		return trace.NotFound("recording for %v is not found", sessionID)
	}
	return nil
}

private function readResponse() {
        $lines = null;
        while (trim($line = fgets($this->connection)) != '') {
            $lines .= $line;
            if (substr($line, 3, 1) == ' ')
                break;
        }
        $data = stream_get_meta_data($this->connection);
        if ($data['timed_out'])
            throw new RuntimeException('Timeout on socket connection');

        $this->logResponse($lines);
        return $lines;
    }

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


Question:
Initialize locale.

@return $this Self object

public function initialize()
    {
        setlocale(LC_ALL, $this->locale->getIso() . '.' . $this->encoding);
        $this->localeInfo = localeconv();

        return $this;
    }

public void setUserLocalService(
		com.liferay.portal.kernel.service.UserLocalService userLocalService) {
		this.userLocalService = userLocalService;
	}

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


Question:
// statusResponse completes the request with a response describing the health
// of the service.

func statusResponse(w http.ResponseWriter, r *http.Request, status int, checks map[string]string) {
	p, err := json.Marshal(checks)
	if err != nil {
		context.GetLogger(context.Background()).Errorf("error serializing health status: %v", err)
		p, err = json.Marshal(struct {
			ServerError string `json:"server_error"`
		}{
			ServerError: "Could not parse error message",
		})
		status = http.StatusInternalServerError

		if err != nil {
			context.GetLogger(context.Background()).Errorf("error serializing health status failure message: %v", err)
			return
		}
	}

	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Content-Length", fmt.Sprint(len(p)))
	w.WriteHeader(status)
	if _, err := w.Write(p); err != nil {
		context.GetLogger(context.Background()).Errorf("error writing health status response body: %v", err)
	}
}

public function getStatus()
    {
        if ($this->entity && $this->entity->getStatus()) {
            return new ApiOrderStatus($this->entity->getStatus(), $this->locale);
        } else {
            return null;
        }
    }

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


Question:
Register our view files

@return void

protected function loadViews()
    {
        $this->loadViewsFrom($this->getRelativePath('views'), 'maintenancemode');

        $this->publishes([
            $this->getRelativePath('views') => base_path('resources/views/vendor/maintenancemode'),
        ], 'views');
    }

def SetPackageView(self, directoryView):
        """"""
        self.directoryView = not self.directoryView
        self.packageMenuItem.Check(self.directoryView)
        self.packageViewTool.SetValue(self.directoryView)
        if self.loader:
            self.SetModel(self.loader)
        self.RecordHistory()

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


Question:
Set the status of an object to archived.

    Preconditions:
    - The object with the pid is verified to exist.
    - The object is not a replica.
    - The object is not archived.

def archive_sciobj(pid):

    sciobj_model = d1_gmn.app.model_util.get_sci_model(pid)
    sciobj_model.is_archived = True
    sciobj_model.save()
    _update_modified_timestamp(sciobj_model)

def handle_single_message(self, msg):

        job_id = msg.message['job_id']
        actual_msg = msg.message
        if msg.type == MessageType.JOB_UPDATED:
            progress = actual_msg['progress']
            total_progress = actual_msg['total_progress']
            self.storage_backend.update_job_progress(job_id, progress,
                                                     total_progress)
        elif msg.type == MessageType.JOB_COMPLETED:
            self.storage_backend.complete_job(job_id)
        elif msg.type == MessageType.JOB_FAILED:
            exc = actual_msg['exception']
            trace = actual_msg['traceback']
            self.storage_backend.mark_job_as_failed(job_id, exc, trace)
        elif msg.type == MessageType.JOB_CANCELED:
            self.storage_backend.mark_job_as_canceled(job_id)
        else:
            self.logger.error("Unknown message type: {}".format(msg.type))

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


Question:
Requested video annotation features.

Generated from protobuf field repeated .google.cloud.videointelligence.v1.Feature features = 2;
@param int[]|\Google\Protobuf\Internal\RepeatedField $var
@return $this

public function setFeatures($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::ENUM, \Google\Cloud\VideoIntelligence\V1\Feature::class);
        $this->features = $arr;

        return $this;
    }

function(packedValue)
    {

        var result;

        var t = typeof(packedValue);
        if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
        {
            result = this.handleError(packedValue);
        }
        else if (packedValue instanceof Array)
        {
            result = [];
            for (var i = 0; i < packedValue.length; i++)
            {
                result[i] = this.deserialize(packedValue[i]);
            }
        }
        else if (t == "object")
        {
            for(var i = 0; i < packedValue.newTypes.length; i++)
            {
                this.addTypeDataToCache(packedValue.newTypes[i]);
            }
            for (var aRefID in packedValue.newRefs)
            {
                this.createProxy(aRefID, packedValue.newRefs[aRefID]);
            }
            if (packedValue.type == FABridge.TYPE_PRIMITIVE)
            {
                result = packedValue.value;
            }
            else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
            {
                result = this.getFunctionProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
            {
                result = this.getProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
            {
                result = packedValue.value;
            }
        }
        return result;
    }

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


Question:
Returns the web accessible URI pointing to the specified persistent resource

@param \Neos\Flow\ResourceManagement\PersistentResource $resource Resource object or the resource hash of the resource
@return string The URI
@throws Exception

public function getPublicPersistentResourceUri(PersistentResource $resource)
    {
        if ($this->baseUri != '') {
            return $this->baseUri . $this->encodeRelativePathAndFilenameForUri($this->getRelativePublicationPathAndFilename($resource));
        } else {
            return $this->s3Client->getObjectUrl($this->bucketName, $this->keyPrefix . $this->getRelativePublicationPathAndFilename($resource));
        }
    }

func NewPrometheus(subsystem string, customMetricsList ...[]*Metric) *Prometheus {

	var metricsList []*Metric

	if len(customMetricsList) > 1 {
		panic("Too many args. NewPrometheus( string, <optional []*Metric> ).")
	} else if len(customMetricsList) == 1 {
		metricsList = customMetricsList[0]
	}

	for _, metric := range standardMetrics {
		metricsList = append(metricsList, metric)
	}

	p := &Prometheus{
		MetricsList: metricsList,
		MetricsPath: defaultMetricPath,
		ReqCntURLLabelMappingFn: func(c *gin.Context) string {
			return c.Request.URL.String() // i.e. by default do nothing, i.e. return URL as is
		},
	}

	p.registerMetrics(subsystem)

	return p
}

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


Question:
Returns a {@link CompleteExceptionallyPromise} with {@link StacklessException},
since this method doesn't accept any {@code Promise}s

@see #any(Iterator)

@Contract(pure = true)
	@NotNull
	public static <T> Promise<T> any() {
		return Promise.ofException(new StacklessException(Promises.class, "All promises completed exceptionally"));
	}

async def jsk_python_inspect(self, ctx: commands.Context, *, argument: CodeblockConverter):

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
                        self.last_result = result

                        header = repr(result).replace("``", "`\u200b`").replace(self.bot.http.token, "[token omitted]")

                        if len(header) > 485:
                            header = header[0:482] + "..."

                        paginator = WrappedPaginator(prefix=f"```prolog\n=== {header} ===\n", max_size=1985)

                        for name, res in all_inspections(result):
                            paginator.add_line(f"{name:16.16} :: {res}")

                        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                        await interface.send_to(ctx)
        finally:
            scope.clear_intersection(arg_dict)

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


Question:
Set an option.  Extends RawConfigParser.set by validating type and
        interpolation syntax on the value.

def set(self, section, option, value=None):
        """"""
        _, option, value = self._validate_value_types(option=option, value=value)
        super(ConfigParser, self).set(section, option, value)

@SuppressWarnings("static-method")
	protected boolean isDefaultValuedParameterFunction(XtendFunction function) {
		for (final XtendParameter parameter : function.getParameters()) {
			if (parameter instanceof SarlFormalParameter) {
				final SarlFormalParameter sarlParameter = (SarlFormalParameter) parameter;
				if (sarlParameter.getDefaultValue() != null) {
					return true;
				}
			}
		}
		return false;
	}

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


Question: // New returns a new context with the provided parent.

func New(parent context.Context) types.Context {
	return newContext(parent, nil, nil, nil, nil)
}

func (b *BottleController) Show(ctx *app.ShowBottleContext) error {
	account, ok := b.db.GetAccount(ctx.AccountID)
	if !ok {
		return ctx.NotFound()
	}
	bottle, ok := b.db.GetBottle(account.ID, ctx.BottleID)
	if !ok {
		return ctx.NotFound()
	}
	return ctx.OK(ToBottleMedia(&account, &bottle))
}

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


Question:
Processes an API client exception checking if authorization has to be renewed.
@param ApiClientException $exception
@param RequestInterface $request
@return ResponseInterface
@throws ApiClientException

protected function processApiClientException(
        ApiClientException $exception,
        RequestInterface $request
    ): ResponseInterface {
        if (!$exception instanceof UnauthorizedException) {
            throw $exception;
        }

        $this->clearAuthorizationToken();
        $promise = $this->createPromiseForRequest($request, false);
        return $promise->wait();
    }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

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


Question:
Allocate new internal buffers. This method attempts to allocate
and assign internal buffers atomically (either allocations succeed or not).

protected void allocateBuffers(int arraySize) {
    assert Integer.bitCount(arraySize) == 1;

    // Compute new hash mixer candidate before expanding.
    final int newKeyMixer = this.orderMixer.newKeyMixer(arraySize);

    // Ensure no change is done if we hit an OOM.
    KType[] prevKeys = Intrinsics.<KType[]> cast(this.keys);
    VType[] prevValues = Intrinsics.<VType[]> cast(this.values);
    try {
      int emptyElementSlot = 1;
      this.keys = Intrinsics.<KType> newArray(arraySize + emptyElementSlot);
      this.values = Intrinsics.<VType> newArray(arraySize + emptyElementSlot);
    } catch (OutOfMemoryError e) {
      this.keys = prevKeys;
      this.values = prevValues;
      throw new BufferAllocationException(
          "Not enough memory to allocate buffers for rehashing: %,d -> %,d",
          e,
          this.mask + 1,
          arraySize);
    }

    this.resizeAt = expandAtCount(arraySize, loadFactor);
    this.keyMixer = newKeyMixer;
    this.mask = arraySize - 1;
  }

def run(self):
    """"""
    self._live = True
    self._sock.settimeout(self.LISTEN_TIMEOUT_S)

    # Passing in INADDR_ANY means the kernel will choose the default interface.
    # The localhost address is used to receive messages sent in "local_only"
    # mode and the default address is used to receive all other messages.
    for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS):
      self._sock.setsockopt(
          socket.IPPROTO_IP,
          socket.IP_ADD_MEMBERSHIP,
          # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP
          # assigned to the interface on which to listen.
          struct.pack('!4sL', socket.inet_aton(self.address), interface_ip))

    if sys.platform == 'darwin':
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEPORT,
                            1)  # Allow multiple listeners to bind.
    else:
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEADDR,
                            1)  # Allow multiple listeners to bind.
    self._sock.bind((self.address, self.port))

    while self._live:
      try:
        data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES)
        data = data.decode('utf-8')
        log_line = 'Received multicast message from %s: %s' % (address, data)
        response = self._callback(data)
        if response is not None:
          log_line += ', responding with %s bytes' % len(response)
          # Send replies out-of-band instead of with the same multicast socket
          # so that multiple processes on the same host can listen for
          # requests and reply (if they all try to use the multicast socket
          # to reply, they conflict and this sendto fails).
          response = response.encode('utf-8')
          socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(
              response, address)
        _LOG.debug(log_line)
      except socket.timeout:
        pass
      except socket.error:
        _LOG.debug('Error receiving multicast message', exc_info=True)

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


Question: Return `Hooks` that store activations of all `modules` in `self.stored`

def hook_outputs(modules:Collection[nn.Module], detach:bool=True, grad:bool=False)->Hooks:
    ""
    return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad)

func setOpts(opts map[string]string, supportedOpts backendOptions) error {
	errors := 0

	for key, val := range opts {
		opt, ok := supportedOpts[key]
		if !ok {
			errors++
			log.WithField(logfields.Key, key).Error("unknown kvstore configuration key")
			continue
		}

		if opt.validate != nil {
			if err := opt.validate(val); err != nil {
				log.Errorf("invalid value for key %s: %s", key, err)
				errors++
			}
		}

	}

	// if errors have occurred, print the supported configuration keys to
	// the log
	if errors > 0 {
		log.Error("Supported configuration keys:")
		for key, val := range supportedOpts {
			log.Errorf("  %-12s %s", key, val.description)
		}

		return fmt.Errorf("invalid kvstore configuration, see log for details")
	}

	// modify the configuration atomically after verification
	for key, val := range opts {
		supportedOpts[key].value = val
	}

	return nil
}

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


Question:
Register a list of modules gathered by categories
@param array $modules
@return int The number of registered modules
@throws \common_exception_InconsistentData
@throws \common_exception_InvalidArgumentType

public function registerModulesByCategories(array $modules)
    {
        $count = 0;
        foreach($modules as $categoryModules) {
            if (is_array($categoryModules)) {
                $count += $this->registerModules($categoryModules);
            } else {
                throw new \common_exception_InvalidArgumentType(self::class, __FUNCTION__, 0, 'array', $categoryModules);
            }
        }
        return $count;
    }

public function decorateException($error)
    {
        $application = $this->application;

        if (is_callable($error)) {
            $error = $application->getContainer()->call($error, [$application]);
        }

        if (is_object($error) && !($error instanceof \Exception)) {
            $error = method_exists($error,
                '__toString') ? $error->__toString() : 'Error with object ' . get_class($error);
        }

        if (is_resource($error)) {
            $error = 'Error with resource type ' . get_resource_type($error);
        }

        if (is_array($error)) {
            $error = implode("\n", $error);
        }

        if (!($error instanceof \Exception)) {
            $error = new \Exception(is_scalar($error) ? $error : 'Error with ' . gettype($error));
        }

        return $error;
    }

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


Question: // NewPGPEncrypt creates a PGPEncrypt engine.

func NewPGPEncrypt(g *libkb.GlobalContext, arg *PGPEncryptArg) *PGPEncrypt {
	return &PGPEncrypt{
		arg:          arg,
		Contextified: libkb.NewContextified(g),
	}
}

def load_from_file(swag_path, swag_type='yml', root_path=None):

    if swag_type not in ('yaml', 'yml'):
        raise AttributeError("Currently only yaml or yml supported")
        # TODO: support JSON

    try:
        enc = detect_by_bom(swag_path)
        with codecs.open(swag_path, encoding=enc) as yaml_file:
            return yaml_file.read()
    except IOError:
        # not in the same dir, add dirname
        swag_path = os.path.join(
            root_path or os.path.dirname(__file__), swag_path
        )
        try:
            enc = detect_by_bom(swag_path)
            with codecs.open(swag_path, encoding=enc) as yaml_file:
                return yaml_file.read()
        except IOError:  # pragma: no cover
            # if package dir
            # see https://github.com/rochacbruno/flasgger/pull/104
            # Still not able to reproduce this case
            # test are in examples/package_example
            # need more detail on how to reproduce IOError here
            swag_path = swag_path.replace("/", os.sep).replace("\\", os.sep)
            path = swag_path.replace(
                (root_path or os.path.dirname(__file__)), ''
            ).split(os.sep)[1:]
            site_package = imp.find_module(path[0])[1]
            swag_path = os.path.join(site_package, os.sep.join(path[1:]))
            with open(swag_path) as yaml_file:
                return yaml_file.read()

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


Question:
Draw a zone chart

@param string $SerieA
@param string $SerieB
@param array $Format
@return null|integer

public function drawZoneChart($SerieA, $SerieB, array $Format = [])
    {
        $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
        $LineR = isset($Format["LineR"]) ? $Format["LineR"] : 150;
        $LineG = isset($Format["LineG"]) ? $Format["LineG"] : 150;
        $LineB = isset($Format["LineB"]) ? $Format["LineB"] : 150;
        $LineAlpha = isset($Format["LineAlpha"]) ? $Format["LineAlpha"] : 50;
        $LineTicks = isset($Format["LineTicks"]) ? $Format["LineTicks"] : 1;
        $AreaR = isset($Format["AreaR"]) ? $Format["AreaR"] : 150;
        $AreaG = isset($Format["AreaG"]) ? $Format["AreaG"] : 150;
        $AreaB = isset($Format["AreaB"]) ? $Format["AreaB"] : 150;
        $AreaAlpha = isset($Format["AreaAlpha"]) ? $Format["AreaAlpha"] : 5;

        $this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;

        $Data = $this->DataSet->getData();
        if (!isset($Data["Series"][$SerieA]["Data"])
            || !isset($Data["Series"][$SerieB]["Data"])
        ) {
            return 0;
        }
        $SerieAData = $Data["Series"][$SerieA]["Data"];
        $SerieBData = $Data["Series"][$SerieB]["Data"];

        list($XMargin, $XDivs) = $this->scaleGetXSettings();

        $Mode = $Data["Axis"][$AxisID]["Display"];
        $Format = $Data["Axis"][$AxisID]["Format"];

        $PosArrayA = $this->scaleComputeY($SerieAData, ["AxisID" => $AxisID]);
        $PosArrayB = $this->scaleComputeY($SerieBData, ["AxisID" => $AxisID]);
        if (count($PosArrayA) != count($PosArrayB)) {
            return 0;
        }

        if ($Data["Orientation"] == SCALE_POS_LEFTRIGHT) {
            if ($XDivs == 0) {
                $XStep = ($this->GraphAreaX2 - $this->GraphAreaX1) / 4;
            } else {
                $XStep = ($this->GraphAreaX2 - $this->GraphAreaX1 - $XMargin * 2) / $XDivs;
            }
            $X = $this->GraphAreaX1 + $XMargin;
            $LastX = null;
            $LastY = null;

            $LastY1 = null;
            $LastY2 = null;
            $BoundsA = [];
            $BoundsB = [];
            foreach ($PosArrayA as $Key => $Y1) {
                $Y2 = $PosArrayB[$Key];

                $BoundsA[] = $X;
                $BoundsA[] = $Y1;
                $BoundsB[] = $X;
                $BoundsB[] = $Y2;

                $LastX = $X;
                $LastY1 = $Y1;
                $LastY2 = $Y2;

                $X = $X + $XStep;
            }
            $Bounds = array_merge($BoundsA, $this->reversePlots($BoundsB));
            $this->drawPolygonChart(
                $Bounds,
                [
                    "R" => $AreaR,
                    "G" => $AreaG,
                    "B" => $AreaB,
                    "Alpha" => $AreaAlpha
                ]
            );

            for ($i = 0; $i <= count($BoundsA) - 4; $i = $i + 2) {
                $this->drawLine(
                    $BoundsA[$i],
                    $BoundsA[$i + 1],
                    $BoundsA[$i + 2],
                    $BoundsA[$i + 3],
                    [
                        "R" => $LineR,
                        "G" => $LineG,
                        "B" => $LineB,
                        "Alpha" => $LineAlpha,
                        "Ticks" => $LineTicks
                    ]
                );
                $this->drawLine(
                    $BoundsB[$i],
                    $BoundsB[$i + 1],
                    $BoundsB[$i + 2],
                    $BoundsB[$i + 3],
                    [
                        "R" => $LineR,
                        "G" => $LineG,
                        "B" => $LineB,
                        "Alpha" => $LineAlpha,
                        "Ticks" => $LineTicks
                    ]
                );
            }
        } else {
            if ($XDivs == 0) {
                $YStep = ($this->GraphAreaY2 - $this->GraphAreaY1) / 4;
            } else {
                $YStep = ($this->GraphAreaY2 - $this->GraphAreaY1 - $XMargin * 2) / $XDivs;
            }
            $Y = $this->GraphAreaY1 + $XMargin;
            $LastX = null;
            $LastY = null;

            $LastX1 = null;
            $LastX2 = null;
            $BoundsA = [];
            $BoundsB = [];
            foreach ($PosArrayA as $Key => $X1) {
                $X2 = $PosArrayB[$Key];

                $BoundsA[] = $X1;
                $BoundsA[] = $Y;
                $BoundsB[] = $X2;
                $BoundsB[] = $Y;

                $LastY = $Y;
                $LastX1 = $X1;
                $LastX2 = $X2;

                $Y = $Y + $YStep;
            }
            $Bounds = array_merge($BoundsA, $this->reversePlots($BoundsB));
            $this->drawPolygonChart(
                $Bounds,
                ["R" => $AreaR, "G" => $AreaG, "B" => $AreaB, "Alpha" => $AreaAlpha]
            );

            for ($i = 0; $i <= count($BoundsA) - 4; $i = $i + 2) {
                $this->drawLine(
                    $BoundsA[$i],
                    $BoundsA[$i + 1],
                    $BoundsA[$i + 2],
                    $BoundsA[$i + 3],
                    [
                        "R" => $LineR,
                        "G" => $LineG,
                        "B" => $LineB,
                        "Alpha" => $LineAlpha,
                        "Ticks" => $LineTicks
                    ]
                );
                $this->drawLine(
                    $BoundsB[$i],
                    $BoundsB[$i + 1],
                    $BoundsB[$i + 2],
                    $BoundsB[$i + 3],
                    [
                        "R" => $LineR,
                        "G" => $LineG,
                        "B" => $LineB,
                        "Alpha" => $LineAlpha,
                        "Ticks" => $LineTicks
                    ]
                );
            }
        }
    }

func (c *ScatterChart) AddData(name string, data []EPoint, plotstyle PlotStyle, style Style) {

	// Update styles if non given
	if plotstyle.undefined() {
		plotstyle = PlotStylePoints
	}
	if style.empty() {
		style = AutoStyle(len(c.Data), false)
	}
	// Fix missing values in style
	if (plotstyle & PlotStyleLines) != 0 {
		if style.LineWidth <= 0 {
			style.LineWidth = 1
		}
		if style.LineColor == nil {
			style.LineColor = style.SymbolColor
		}
	}
	if (plotstyle&PlotStylePoints) != 0 && style.Symbol == 0 {
		style.Symbol = '#'
	}

	// Init axis
	if len(c.Data) == 0 {
		c.XRange.init()
		c.YRange.init()
	}

	// Add data
	scd := ScatterChartData{Name: name, PlotStyle: plotstyle, Style: style, Samples: data, Func: nil}
	c.Data = append(c.Data, scd)

	// Autoscale
	for _, d := range data {
		xl, yl, xh, yh := d.BoundingBox()
		c.XRange.autoscale(xl)
		c.XRange.autoscale(xh)
		c.YRange.autoscale(yl)
		c.YRange.autoscale(yh)
	}

	// Add key/legend entry
	if name != "" {
		ke := KeyEntry{Style: style, PlotStyle: plotstyle, Text: name}
		c.Key.Entries = append(c.Key.Entries, ke)
	}
}

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


Question:
Historical vpc event collector.
    This collector is responsible for processing Cloudwatch events and polling events.

def handler(event, context):  # pylint: disable=W0613

    records = deserialize_records(event['Records'])

    # Split records into two groups, update and delete.
    # We don't want to query for deleted records.
    update_records, delete_records = group_records_by_type(records, UPDATE_EVENTS)
    capture_delete_records(delete_records)

    # filter out error events
    update_records = [e for e in update_records if not e['detail'].get('errorCode')]  # pylint: disable=C0103

    # group records by account for more efficient processing
    LOG.debug(f'[@] Update Records: {records}')

    capture_update_records(update_records)

def build_gui(self, container):

        vbox = Widgets.VBox()
        vbox.set_border_width(2)
        vbox.set_spacing(1)

        w = Viewers.GingaViewerWidget(viewer=self)
        vbox.add_widget(w, stretch=1)

        # set up to capture cursor movement for reading out coordinates

        # coordinates reported in base 1 or 0?
        self.pixel_base = 1.0

        self.readout = Widgets.Label("")
        vbox.add_widget(self.readout, stretch=0)

        #self.set_callback('none-move', self.motion_cb)
        self.set_callback('cursor-changed', self.motion_cb)

        # need to put this in an hbox with an expanding label or the
        # browser wants to resize the canvas, distorting it
        hbox = Widgets.HBox()
        hbox.add_widget(vbox, stretch=0)
        hbox.add_widget(Widgets.Label(''), stretch=1)

        container.set_widget(hbox)

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


Question:
// useVar returns a node for a variable reference. It errors if the
// variable is not defined.

func (t *Tree) useVar(pos Pos, name string) Node {
	v := t.newVariable(pos, name)
	for _, varName := range t.vars {
		if varName == v.Ident[0] {
			return v
		}
	}
	t.errorf("undefined variable %q", v.Ident[0])
	return nil
}

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question:
发送钉钉消息
@param $msg string
@return bool

public function send($msg)
    {
        if (!$this->url) {
            return false;
        }
        $data = ["msgtype" => "text", "text" => ["content" => $msg], "at" => ["isAtAll" => true]];
        $curl = new LCurl(LCurl::POST_JSON, 3);
        $result = $curl->post(
            $this->url,
            $data
        );
        if (!$result || (int)Arrays::get($result, 'errcode') != 0) {
            return false;
        }
        return true;
    }

private static function init() {
        $lang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : null;
        if (empty($lang))
            $lang = "es";
        self::$language = $lang;
        self::$messages = [];
        self::$messagesPath = get_property("app.messages_path", get_app()->resourcesPath() . DIRECTORY_SEPARATOR . "messages");
    }

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


Question: // Spaces is defined on the environs.Networking interface.

func (e Environ) Spaces(ctx context.ProviderCallContext) ([]network.SpaceInfo, error) {
	networks, err := e.getSubnetInfo()
	if err != nil {
		return nil, errors.Trace(err)
	}
	exchanges := map[string]network.SpaceInfo{}
	for _, val := range networks {
		if val.SpaceProviderId == "" {
			continue
		}
		logger.Infof("found network %s with space %s",
			string(val.ProviderId), string(val.SpaceProviderId))
		providerID := string(val.SpaceProviderId)
		tmp := strings.Split(providerID, `/`)
		name := tmp[len(tmp)-1]
		// Oracle allows us to attach an IP network to a space belonging to
		// another user using the web portal. We recompose the provider ID
		// (which is unique) and compare to the provider ID of the space.
		// If they match, the space belongs to us
		tmpProviderId := e.client.ComposeName(name)
		if tmpProviderId != providerID {
			continue
		}
		if space, ok := exchanges[name]; !ok {
			logger.Infof("creating new space obj for %s and adding %s",
				name, string(val.ProviderId))
			exchanges[name] = network.SpaceInfo{
				Name:       name,
				ProviderId: val.SpaceProviderId,
				Subnets: []network.SubnetInfo{
					val,
				},
			}
		} else {
			logger.Infof("appending subnet %s to %s", string(val.ProviderId), space.Name)
			space.Subnets = append(space.Subnets, val)
			exchanges[name] = space
		}

	}
	var ret []network.SpaceInfo
	for _, val := range exchanges {
		ret = append(ret, val)
	}

	logger.Infof("returning spaces: %v", ret)
	return ret, nil
}

func NewStatement(ns string, set string, binNames ...string) *Statement {
	return &Statement{
		Namespace:  ns,
		SetName:    set,
		BinNames:   binNames,
		returnData: true,
		TaskId:     uint64(xornd.Int64()),
	}
}

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


Question:
Returns the owner of this entity

@return PKEncryptionEnabledUserInterface

public function getOwnerUser()
    {
        $reflection = ClassUtils::newReflectionObject($this);

        if ($reflection->hasMethod('getUser')) {
            return $this->getUser();
        }
        elseif ($reflection->hasMethod('getUserProfile')) {
            return $this->getUserProfile() ? $this->getUserProfile()->getUser() : null;
        }

        return null;
    }

def ecdh(self, identity, pubkey):
        """"""
        curve_name = identity.get_curve_name(ecdh=True)
        log.debug('"%s" shared session key (%s) for %r from %s',
                  identity.to_string(), curve_name, pubkey, self)
        try:
            result = self._defs.get_ecdh_session_key(
                self.conn,
                identity=self._identity_proto(identity),
                peer_public_key=pubkey,
                ecdsa_curve_name=curve_name)
            log.debug('result: %s', result)
            assert len(result.session_key) in {65, 33}  # NIST256 or Curve25519
            assert result.session_key[:1] == b'\x04'
            return bytes(result.session_key)
        except self._defs.TrezorFailure as e:
            msg = '{} error: {}'.format(self, e)
            log.debug(msg, exc_info=True)
            raise interface.DeviceError(msg)

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


Question: // SetDBSubnetGroupName sets the DBSubnetGroupName field's value.

func (s *CreateDBInstanceReadReplicaInput) SetDBSubnetGroupName(v string) *CreateDBInstanceReadReplicaInput {
	s.DBSubnetGroupName = &v
	return s
}

def get_vnetwork_vswitches_output_vnetwork_vswitches_interface_name(self, **kwargs):

        config = ET.Element("config")
        get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
        config = get_vnetwork_vswitches
        output = ET.SubElement(get_vnetwork_vswitches, "output")
        vnetwork_vswitches = ET.SubElement(output, "vnetwork-vswitches")
        interface_name = ET.SubElement(vnetwork_vswitches, "interface-name")
        interface_name.text = kwargs.pop('interface_name')

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

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


Question: // SetName sets the Name field's value.

func (s *ConfigurationRecorder) SetName(v string) *ConfigurationRecorder {
	s.Name = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
Enables a filter from the collection.

@throws InvalidArgumentException If the filter does not exist.

public function enable(string $name) : BsonFilter
    {
        if (! $this->has($name)) {
            throw new InvalidArgumentException("Filter '" . $name . "' does not exist.");
        }

        if (! $this->isEnabled($name)) {
            $filterClass      = $this->config->getFilterClassName($name);
            $filterParameters = $this->config->getFilterParameters($name);
            $filter           = new $filterClass($this->dm);

            foreach ($filterParameters as $param => $value) {
                $filter->setParameter($param, $value);
            }

            $this->enabledFilters[$name] = $filter;
        }

        return $this->enabledFilters[$name];
    }

public function setFilterDate(
        string $field,
        string $string = '',
        bool $active = true,
        string $format = null,
        string $class = '',
        string $style = '',
        string $placeholder = ''
    ): ColumnInterface {
        $this->setDateActive($active);
        if ($format) {
            $this->setDateFormat($format);
        }

        return $this->setFilter($field, $string, self::FILTER_TYPE_DATE, [], $class, $style, $placeholder);
    }

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


Question:
Compute key/value Tensor kv.

    Args:
      memory_antecedent: a Tensor with dimensions
        {memory_input_dim} + other_dims
    Returns:
      a Tensor with dimensions
        memory_heads_dims + {key_dim} + other_dims

def compute_kv(self, memory_antecedent):

    if not self.shared_kv:
      raise ValueError("compute_kv can only be called with shared_kv")
    ret = mtf.einsum(
        [memory_antecedent, self.wkv], reduced_dims=[self.memory_input_dim])
    if self.combine_dims:
      ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.k_dims)
    return ret

public static PrimitiveObject hadoop2Primitive(Writable object) {
        if (object instanceof NullWritable) {
            return new PrimitiveObject(NULL, null);
        }

        if (object instanceof ByteWritable) {
            return new PrimitiveObject(BYTE, ((ByteWritable) object).get());
        } else if (object instanceof IntWritable) {
            return new PrimitiveObject(INTEGER, ((IntWritable) object).get());
        } else if (object instanceof LongWritable) {
            return new PrimitiveObject(LONG, ((LongWritable) object).get());
        } else if (object instanceof DoubleWritable) {
            return new PrimitiveObject(DOUBLE, ((DoubleWritable) object).get());
        } else if (object instanceof FloatWritable) {
            return new PrimitiveObject(FLOAT, ((FloatWritable) object).get());
        } else if (object instanceof BooleanWritable) {
            return new PrimitiveObject(BOOLEAN, ((BooleanWritable) object).get());
        } else if (object instanceof Text) {
            return new PrimitiveObject(STRING, ((Text) object).toString());
        } else if (object instanceof ArrayWritable) {
            ArrayWritable aw = (ArrayWritable) object;
            if (aw.get().length == 0) {
                return new PrimitiveObject(ARRAY, true, STRING, new ArrayList<String>());
            }

            int type = NULL;
            List<Object> l = new ArrayList<Object>();
            for (Writable w : aw.get()){
                PrimitiveObject no = hadoop2Primitive(w);
                type = no.getType();
                l.add(no.getObject());
            }

            return new PrimitiveObject(ARRAY, true, type, l);
        } else if (object instanceof MapWritable) {
            MapWritable mw = (MapWritable) object;
            if (mw.size() == 0) {
                return new PrimitiveObject(MAP, true, STRING, STRING, new HashMap<String, String>());
            }

            int keyType = NULL;
            int valueType = NULL;
            Map<Object, Object> m = new HashMap<Object, Object>();
            for (Entry<Writable, Writable> entry : mw.entrySet()){
                PrimitiveObject keyNo = hadoop2Primitive(entry.getKey());
                PrimitiveObject valueNo = hadoop2Primitive(entry.getValue());
                keyType = keyNo.getType();
                valueType = valueNo.getType();
                m.put(keyNo.getObject(), valueNo.getObject());
            }

            return new PrimitiveObject(MAP, true, keyType, valueType, m);
        }

        throw new ClassCastException("cast object not found");
    }

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


Question:
Try to find a document based on its document id. if inst=True, if it
        hasn't been instantiated yet, it will be.

def get_doc_from_docid(self, docid, doc_type_name=None, inst=True):

        assert(docid is not None)
        if docid in self._docs_by_id:
            return self._docs_by_id[docid]
        if not inst:
            return None
        doc = self.__inst_doc(docid, doc_type_name)
        if doc is None:
            return None
        self._docs_by_id[docid] = doc
        return doc

def _set_desc(self):
        """"""
        # TODO: manage different in/out styles
        if self.docs['in']['desc']:
            self.docs['out']['desc'] = self.docs['in']['desc']
        else:
            self.docs['out']['desc'] = ''

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


Question:
Return:
            PIL.Image

        Raises:
            EnvironmentError

def screenshot(self, filename=None):

        tmpfile = tempfile.mktemp(prefix='atx-screencap-', suffix='.tiff')
        try:
            idevice("screenshot", "--udid", self.udid, tmpfile)
        except subprocess.CalledProcessError as e:
            sys.exit(e.message)

        try:
            image = Image.open(tmpfile)
            image.load()
            if filename:
                image.save(filename)
            return image
        finally:
            if os.path.exists(tmpfile):
                os.unlink(tmpfile)

def generate_reports(subject_list, output_dir, work_dir, run_uuid, config=None,
                     packagename=None):

    reports_dir = str(Path(work_dir) / 'reportlets')
    report_errors = [
        run_reports(reports_dir, output_dir, subject_label, run_uuid,
                    config, packagename=packagename)
        for subject_label in subject_list
    ]

    errno = sum(report_errors)
    if errno:
        import logging
        logger = logging.getLogger('cli')
        error_list = ', '.join('%s (%d)' % (subid, err)
                               for subid, err in zip(subject_list, report_errors) if err)
        logger.error(
            'Preprocessing did not finish successfully. Errors occurred while processing '
            'data from participants: %s. Check the HTML reports for details.', error_list)
    return errno

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


Question:
Builds and returns an S3MultiRegionClient
@return S3MultiRegionClient|null

protected function getS3MultiRegionClient() {
		if(!$this->enabled()) {
			return null;
		}

		$config = [
			'version' => 'latest',
			'credentials' => [
				'key' => $this->key,
				'secret' => $this->secret
			]
		];

		if(!empty($this->endpoint)) {
			$config['endpoint'] = $this->endpoint;

			if($this->endPointPathStyle) {
				$config['use_path_style_endpoint'] = true;
			}
		}

		if($this->useTransferAcceleration) {
			$config['use_accelerate_endpoint'] = true;
		}

		$s3 = new S3MultiRegionClient($config);

		return $s3;
	}

def connect_service(service, credentials, region_name = None, config = None, silent = False):

    api_client = None
    try:
        client_params = {}
        client_params['service_name'] = service.lower()
        session_params = {}
        session_params['aws_access_key_id'] = credentials['AccessKeyId']
        session_params['aws_secret_access_key'] = credentials['SecretAccessKey']
        session_params['aws_session_token'] = credentials['SessionToken']
        if region_name:
            client_params['region_name'] = region_name
            session_params['region_name'] = region_name
        if config:
            client_params['config'] = config
        aws_session = boto3.session.Session(**session_params)
        if not silent:
            infoMessage = 'Connecting to AWS %s' % service
            if region_name:
                infoMessage = infoMessage + ' in %s' % region_name
            printInfo('%s...' % infoMessage)
        api_client = aws_session.client(**client_params)
    except Exception as e:
        printException(e)
    return api_client

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


Question: // Enabled returns if the UI is enabled

func (c *UIConfig) Enabled() bool {
	c.l.RLock()
	defer c.l.RUnlock()
	return c.enabled
}

public void setEnabled(boolean isEnabled) {
        mCardNumberEditText.setEnabled(isEnabled);
        mExpiryDateEditText.setEnabled(isEnabled);
        mCvcNumberEditText.setEnabled(isEnabled);
    }

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


Question:
/*
INIT: Initialize View

@return   null

protected function _initView ()
    {
        // Create default view model, to be used in all templates and layouts
        $this->appView  = new \Zend\View\Model\ViewModel();

        // Convenience access variables
        $this->_appView = $this->appView;
        $this->view     = $this->appView;
        $this->_view    = $this->appView;
    }

func (c *Controller) OnFirstStartup(fn func() error) {
	c.instance.OnFirstStartup = append(c.instance.OnFirstStartup, fn)
}

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


Question:
Renders "H" tag
@param array $matches
@return string

protected static function h(array $matches)
    {
        $level = strlen($matches[1]);
        return sprintf('<h%d>%s</h%d>', $level, trim($matches[2]), $level);
    }

def resources_by_type(ast)
      raise_unless_xpath!(ast)
      result = Hash.new { |hash, key| hash[key] = Array.new }
      find_resources(ast).each do |resource|
        result[resource_type(resource)] << resource
      end
      result
    end

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


Question: // newRequest augments the default to set a unique request id

func (rt *apiRoundTripper) newRequest(method, prefix, path string,
	query *url.Values, body interface{}) (*http.Request, string, error) {

	requestID := uuid.NewV4().String()

	prefixed := "/" + prefix + path
	req, err := rt.DefaultRequestDoer.NewRequest(method, prefixed, query, body)
	if err != nil {
		return nil, requestID, err
	}

	req.Header.Set("X-Request-ID", requestID)

	return req, requestID, nil
}

def fetch(self):

        params = values.of({})

        payload = self._version.fetch(
            'GET',
            self._uri,
            params=params,
        )

        return AssignedAddOnInstance(
            self._version,
            payload,
            account_sid=self._solution['account_sid'],
            resource_sid=self._solution['resource_sid'],
            sid=self._solution['sid'],
        )

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