Question:
<p>
The ARNs of the public, private, and shared images to describe.
</p>

@param arns
The ARNs of the public, private, and shared images to describe.

public void setArns(java.util.Collection<String> arns) {
        if (arns == null) {
            this.arns = null;
            return;
        }

        this.arns = new java.util.ArrayList<String>(arns);
    }

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question: Test if a 3D (H,W,C) matrix x has the same element in each (H,W) matrix for each channel

def _same_elements_per_channel(x):

    eps = 1e-5
    dims = x.shape
    for c in range(dims[-1]):
        xc = x[:,:,c].flatten()
        if not np.all(np.absolute(xc - xc[0]) < eps):
            return False
    return True

def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):

    if ignore_index is not None:
        assert tensor.size() == tensor_other.size()
        mask_arr = tensor.ne(ignore_index)
        tensor = tensor.masked_select(mask_arr)
        tensor_other = tensor_other.masked_select(mask_arr)

    return torch.equal(tensor, tensor_other)

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


Question:
Increments batch count (after addBatch(..) has been called)
and execute {@code delegate.executeBatch()} if batchSize has been reached.

protected void incrementBatchCount() throws SQLException {
        batchCount++;
        if (batchCount == batchSize /* never true for batchSize of 0 */) {
            int[] result = delegate.executeBatch();
            processResult(result);
            batchCount = 0;
        }
    }

public static TextProtocolBackendHandler newInstance(final String sql, final BackendConnection backendConnection) {
        if (sql.toUpperCase().startsWith(ShardingCTLBackendHandlerFactory.SCTL)) {
            return ShardingCTLBackendHandlerFactory.newInstance(sql, backendConnection);
        }
        // TODO use sql parser engine instead of string compare
        Optional<TransactionOperationType> transactionOperationType = TransactionOperationType.getOperationType(sql.toUpperCase());
        if (transactionOperationType.isPresent()) {
            return new TransactionBackendHandler(transactionOperationType.get(), backendConnection);
        }
        if (sql.toUpperCase().contains(SET_AUTOCOMMIT_1)) {
            return backendConnection.getStateHandler().isInTransaction() ? new TransactionBackendHandler(TransactionOperationType.COMMIT, backendConnection) : new SkipBackendHandler();
        }
        SQLStatement sqlStatement = new SQLJudgeEngine(sql).judge();
        return SQLType.DAL == sqlStatement.getType() ? createDALBackendHandler(sqlStatement, sql, backendConnection) : new QueryBackendHandler(sql, backendConnection);
    }

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


Question:
Checks whether array has exactly $size items.

@param int $size

@return bool

public function sizeIs(int $size): bool
    {
        // init
        $itemsTempCount = 0;

        foreach ($this->getGenerator() as $key => $value) {
            ++$itemsTempCount;
            if ($itemsTempCount > $size) {
                return false;
            }
        }

        return $itemsTempCount === $size;
    }

public final long shallowSizeOf(Object obj) {

		if (obj == null) {
			return 0;
		}

		if (obj.getClass().isArray()) {
			return doShallowSizeOfArray(obj);
		} else {
			return doShallowSizeOfClass(obj.getClass());
		}
	}

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


Question: Update the render setting

private void updateRender() {
		if (inherit.isSelected())
		{
			emitter.usePoints = Particle.INHERIT_POINTS;
			oriented.setEnabled( true );
		}
		if (quads.isSelected())
		{
			emitter.usePoints = Particle.USE_QUADS;
			oriented.setEnabled( true );
		}
		if (points.isSelected())
		{
			emitter.usePoints = Particle.USE_POINTS;
			oriented.setEnabled( false );
			oriented.setSelected( false );
		}

		// oriented
		if( oriented.isSelected())
			emitter.useOriented= true;
		else
			emitter.useOriented= false;

		// additive blending
		if( additive.isSelected())
			emitter.useAdditive= true;
		else
			emitter.useAdditive= false;
	}

def refresh(self):
        """"""
        self.get_devices(refresh=True)
        self.get_automations(refresh=True)

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


Question:
Set the list of selected values.
@param {Array} newValues

function (newValues) {
            var arrayUtil = ariaUtilsArray;

            this._stopUpdates();
            var newlySelectedIndexes = [];
            var newlyUnselectedIndexes = [];

            // Loop through all of the items and update the selection status for each item,
            // depending on the new array of selected values
            var selectedIndex = -1;
            var data = this._data;
            var items = data.items;
            var maxSelectedCount = this._getTrueMaxSelectedCount(items);
            var selectedCount = 0;
            for (var idx = 0, length = items.length; idx < length; idx++) {
                var item = items[idx];
                var selected = arrayUtil.contains(newValues, item.value);
                if (selected) {
                    if (selectedCount == maxSelectedCount) {
                        // cancel selection when there is more than what is allowed
                        selected = false;
                    } else if (selectedIndex == -1) {
                        selectedCount = 1;
                        selectedIndex = idx;
                    } else {
                        selectedCount++;
                        selectedIndex = null;
                    }
                }
                if (data.preselect === "none" || item.selected != selected) {
                    // selection has changed
                    (selected ? newlySelectedIndexes : newlyUnselectedIndexes).push(idx);
                    this.json.setValue(items[idx], "selected", selected);
                }
            }
            this.json.setValue(data, "selectedIndex", selectedIndex);
            this.json.setValue(data, "selectedCount", selectedCount);

            // James removed this because if more than one item is selected, data. selectedIndex is set to null.
            // Also, in the case of the multi-select we don't necessarily
            // Want to focus a selected item - need to check this on the list.
            // this.json.setValue(data, "focusIndex", selectedIndex);
            // this.setFocus(data.focusIndex);

            this._updateCurrentlyDisabled(items);
            this._resumeUpdates();
            if (newlySelectedIndexes.length > 0 || newlyUnselectedIndexes.length > 0) {
                this._raiseOnChangeEvent(newlySelectedIndexes, newlyUnselectedIndexes);
            }
        }

private function _saveDropdownOptions($property, $request)
    {
        if (null !== $request->get('dropdown-options')) {
            $property->propertyDropdownOptions()->delete();

            foreach ($request->get('dropdown-options') as $key => $val) {
                if ($key == '__RANDOM_STRING__') {
                    continue;
                }

                $property->propertyDropdownOptions()->create($val);
            }
        }
    }

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


Question: Saves PopulationSet to HDF file.

def save_hdf(self, filename, path='', overwrite=False):

        if os.path.exists(filename) and overwrite:
            os.remove(filename)

        for pop in self.poplist:
            name = pop.modelshort
            pop.save_hdf(filename, path='{}/{}'.format(path,name), append=True)

def _get_daily_data_collections(self, data_type, unit, values):
        """"""
        data_header = Header(data_type=data_type, unit=unit,
                             analysis_period=self.analysis_period,
                             metadata={'source': self._location.source,
                                       'country': self._location.country,
                                       'city': self._location.city})
        return HourlyContinuousCollection(data_header, values)

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


Question:
Load the {@link ServiceProvider} to be used.

@return {@link ServiceProvider} to be used for loading the services.

private static ServiceProvider loadDefaultServiceProvider() {
        try {
            //noinspection LoopStatementThatDoesntLoop
            for (ServiceProvider sp : ServiceLoader.load(ServiceProvider.class)) {
                return sp;
            }
        } catch (Exception e) {
            Logger.getLogger(Bootstrap.class.getName()).info("No ServiceProvider loaded, using default.");
        }
        return new DefaultServiceProvider();
    }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
Convert to unix timestamp

@param  string|int|\DateTimeInterface $time

@return int

private function getExpiresTime($time): int
    {
        if ($time instanceof \DateTimeInterface) {
            return (int) $time->format('U');
        }

        if (\is_numeric($time)) {
            // average year in seconds
            if ($time <= 31557600) {
                $time += \time();
            }

            return (int) $time;
        }

        return (int) (new \DateTime($time))->format('U');
    }

func Uint(name string, value uint, usage string) *uint {
	return CommandLine.Uint(name, value, usage)
}

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


Question:
Deserialization handling.

@return itself

protected Object readResolve() {
        if (proto != null && scheme == null) {
            scheme = proto;
            proto = null;
        } else if (scheme == null && proto == null) {
            scheme = GerritConnection.GERRIT_PROTOCOL_SCHEME_NAME; //The default for old stuff
        }
        return this;
    }

public static String serialize(Object data) {
        String ret=null;

        if (data != null) {
            if (data.getClass() == String.class) {
                ret = (String)data;
            } else if (data instanceof byte[]) {
                ret = new String((byte[])data);
            } else {
                try {
                    ret = mapper.writeValueAsString(data);
                } catch (JsonProcessingException e) {
                    if (log.isLoggable(Level.FINEST)) {
                        log.log(Level.FINEST, "Failed to serialize object into json", e);
                    }
                }
            }
        }

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


Question: Wrap github calls in to promises

function qG(options) {
  var defer = q.defer();
  var compiledData = [];

  // Recursive call to paginate
  function qGCall(pageLink) {
    var methodCall;

    // Callback
    function callback(error, data) {
      if (error) {
        defer.reject(new Error(error));
      }
      else {
        compiledData = compiledData.concat(data);
        if (github.hasNextPage(data)) {
          qGCall(data);
        }
        else {
          defer.resolve(compiledData);
        }
      }
    }

    // If the call is a link to another page, use that.
    if (pageLink) {
      method = github.getNextPage(pageLink, callback);
    }
    else {
      githubAuth()[options.obj][options.method](options, callback);
    }
  }
  qGCall();

  return defer.promise;
}

def shares(self, token: dict = None, prot: str = "https") -> dict:

        # passing auth parameter
        shares_url = "{}://v1.{}.isogeo.com/shares/".format(prot, self.api_url)
        shares_req = self.get(
            shares_url, headers=self.header, proxies=self.proxies, verify=self.ssl
        )

        # checking response
        checker.check_api_response(shares_req)

        # end of method
        return shares_req.json()

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


Question:
=begin
*
     * Detects a phone (probably) running the Firefox OS.
     * @return detection of a Firefox OS phone

=end

def detect_firefox_o_s_phone()

      if (detect_ios() || detect_android() || detect_sailfish())
        return false
      end

      if ((user_agent.include?(ENGINE_FIREFOX)) && (user_agent.include?(MOBILE)))
        return true
      end

      return false
    end

public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(stack.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(stack.getName(), NAME_BINDING);
            protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING);
            protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING);
            protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING);
            protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING);
            protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING);
            protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING);
            protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING);
            protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
returns all the properties in an array.

@return array

public function getAllProperties()
    {
        $props = array();
        foreach ($this->dynamic as $k => $c) {
            $props[$k] = $c();
        }

        return array_replace($props, $this->properties);
    }

public function errorArray()
    {
        $messages = [];
        foreach ($this->failures as $key => $rule) {
            foreach ($rule->getFailures() as $fail) {
                $messages[] = $fail;
            }
        }
        return $messages;
    }

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


Question:
Set the value of ProjectId / project_id.

Must not be null.
@param $value int

public function setProjectId($value)
    {
        $this->_validateNotNull('ProjectId', $value);
        $this->_validateInt('ProjectId', $value);

        if ($this->data['project_id'] === $value) {
            return;
        }

        $this->data['project_id'] = $value;

        $this->_setModified('project_id');
    }

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

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


Question: // runMethod is called when a method is received from remote Kite.

func (c *Client) runMethod(method *Method, args *dnode.Partial) {
	var (
		callFunc func(interface{}, *Error)
		request  *Request
	)

	// Recover dnode argument errors and send them back. The caller can use
	// functions like MustString(), MustSlice()... without the fear of panic.
	defer func() {
		if r := recover(); r != nil {
			debug.PrintStack()
			kiteErr := createError(request, r)
			c.LocalKite.Log.Error(kiteErr.Error()) // let's log it too :)
			callFunc(nil, kiteErr)
		}
	}()

	// The request that will be constructed from incoming dnode message.
	request, callFunc = c.newRequest(method.name, args)
	if method.authenticate {
		if err := request.authenticate(); err != nil {
			callFunc(nil, createError(request, err))
			return
		}
	} else {
		// if not validated accept any username it sends, also useful for test
		// cases.
		request.Username = request.Client.Kite.Username
	}

	method.mu.Lock()
	if !method.initialized {
		method.preHandlers = append(method.preHandlers, c.LocalKite.preHandlers...)
		method.postHandlers = append(method.postHandlers, c.LocalKite.postHandlers...)
		method.finalFuncs = append(method.finalFuncs, c.LocalKite.finalFuncs...)
		method.initialized = true
	}
	method.mu.Unlock()

	// check if any throttling is enabled and then check token's available.
	// Tokens are filled per frequency of the initial bucket, so every request
	// is going to take one token from the bucket. If many requests come in (in
	// span time larger than the bucket's frequency), there will be no token's
	// available more so it will return a zero.
	if method.bucket != nil && method.bucket.TakeAvailable(1) == 0 {
		callFunc(nil, &Error{
			Type:      "requestLimitError",
			Message:   "The maximum request rate is exceeded.",
			RequestID: request.ID,
		})
		return
	}

	// Call the handler functions.
	result, err := method.ServeKite(request)

	callFunc(result, createError(request, err))
}

def process(self, metric):

        event = self._metric_to_riemann_event(metric)
        try:
            self.client.send_event(event)
        except Exception as e:
            self.log.error(
                "RiemannHandler: Error sending event to Riemann: %s", e)

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


Question:
Checks the existence of embedded items with link-relation type {@code rel}

@param rel the link-relation type
@return true, if item(s) exists, false otherwise

@since 2.0.0

public boolean hasItem(final String rel) {
        final String resolvedRel = curies.resolve(rel);
        return items != null && items.containsKey(resolvedRel);
    }

private function convertItemStatus(Shipping $shipping, $shippingStatusId)
    {
        foreach ($shipping->getItems() as $shippingItem) {
            // get item
            $item = $shippingItem->getItem();

            // set item status based on current shipping status
            switch ($shippingStatusId) {
                // created
                case ShippingStatusEntity::STATUS_CREATED:
                    // TODO: REMOVE PREVIOUS STATE
                    $this->itemManager->addStatus($item, Item::STATUS_CREATED);
                    break;
                // delivery note
                case ShippingStatusEntity::STATUS_DELIVERY_NOTE:
                    if ($this->isPartiallyItem($shippingItem, true)) {
                        $itemStatus = Item::STATUS_SHIPPING_NOTE_PARTIALLY;
                    } else {
                        $itemStatus = Item::STATUS_SHIPPING_NOTE;

                    }
                    $this->itemManager->addStatus($item, $itemStatus);
                    break;
                // shipped
                case ShippingStatusEntity::STATUS_SHIPPED:
                    if ($this->isPartiallyItem($shippingItem, false)) {
                        $itemStatus = Item::STATUS_SHIPPED_PARTIALLY;
                    } else {
                        $itemStatus = Item::STATUS_SHIPPED;

                    }
                    $this->itemManager->addStatus($item, $itemStatus);
                    break;
                case ShippingStatusEntity::STATUS_CANCELED:
                    // TODO: check  if still fully shipped
                    $this->itemManager->removeStatus($item, Item::STATUS_SHIPPED);
                    // TODO: check if partially shipped
                    break;
            }
        }
    }

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


Question: Return a future which will be completed when the message has a response

def send(self, message, timeout=None, tries=3, future=None, callback=None, raw=False):
        '''

        '''
        if future is None:
            future = tornado.concurrent.Future()
            future.tries = tries
            future.attempts = 0
            future.timeout = timeout
            # if a future wasn't passed in, we need to serialize the message
            message = self.serial.dumps(message)
        if callback is not None:
            def handle_future(future):
                response = future.result()
                self.io_loop.add_callback(callback, response)
            future.add_done_callback(handle_future)
        # Add this future to the mapping
        self.send_future_map[message] = future

        if self.opts.get('detect_mode') is True:
            timeout = 1

        if timeout is not None:
            send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message)
            self.send_timeout_map[message] = send_timeout

        if not self.send_queue:
            self.io_loop.spawn_callback(self._internal_send_recv)

        self.send_queue.append(message)

        return future

public static <T> void exceptionListener(CompletableFuture<T> completableFuture, Consumer<Throwable> exceptionListener) {
        completableFuture.whenComplete((r, ex) -> {
            if (ex != null) {
                Callbacks.invokeSafely(exceptionListener, ex, null);
            }
        });
    }

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


Question:
Get annotation metadata

@param $classes
@param $metadataCollection
@return array|\samsonframework\container\metadata\ClassMetadata[]

public function collectAnnotationMetadata($classes, $metadataCollection)
    {
        // Load annotation and parse classes
        new Injectable();
        new InjectArgument(['var' => 'type']);
        new Service(['value' => '']);

        $reader = new AnnotationReader();
        $resolver = new AnnotationResolver(
            new AnnotationClassResolver($reader),
            new AnnotationPropertyResolver($reader),
            new AnnotationMethodResolver($reader)
        );

        $annotationCollector = new AnnotationMetadataCollector($resolver);

        // Rewrite collection by entity name
        return $annotationCollector->collect($classes, $metadataCollection);
    }

public Map<String, MBeanAttributeInfo> getAttributeMetadata() {

        MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();

        Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();
        for (MBeanAttributeInfo attribute: attributeList) {
            attributeMap.put(attribute.getName(), attribute);
        }
        return attributeMap;
    }

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


Question: LIDB2617.11 added this method.  F88119 made method public

public void preInvokeMdbAfterActivate(EJSWrapperBase wrapper,
                                          EJSDeployedSupport s,
                                          Object eb, // d414873
                                          Object[] args) throws RemoteException {
        // Now perform preinvoke processing that must occur after
        // the bean is activated.
        preInvokeAfterActivate(wrapper, eb, s, args);

        // If there is a registered message endpoint collaborator, call it for preInvoke processing.
        MessageEndpointCollaborator meCollaborator = getEJBRuntime().getMessageEndpointCollaborator(wrapper.bmd);
        if (meCollaborator != null) {
            HashMap<String, Object> contextData = new HashMap<String, Object>();
            contextData.put(MessageEndpointCollaborator.KEY_ACTIVATION_SPEC_ID, wrapper.bmd.ivActivationSpecJndiName);
            contextData.put(MessageEndpointCollaborator.KEY_J2EE_NAME, wrapper.bmd.j2eeName);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Invoking MECollaborator " + meCollaborator + " for preInvoke processing with the following context data: " + contextData);
            }

            s.messageEndpointContext = meCollaborator.preInvoke(contextData);
        }

        // Normal path exit.
        if (TraceComponent.isAnyTracingEnabled()) {
            if (tc.isEntryEnabled()) {
                int methodId = s.methodId;
                EJBMethodInfoImpl methodInfo = s.methodInfo;
                ContainerTx containerTx = s.currentTx;
                Tr.exit(tc, "EJBpreInvoke(" + methodId + ":" +
                            methodInfo.getMethodName() + ") " +
                            " Invoking method '" + methodInfo.getMethodName() +
                            "' on bean '" + wrapper.getClass().getName() +
                            "(" + wrapper.beanId + ")" +
                            "', '" + containerTx + "', isGlobalTx=" +
                            (containerTx != null ? (containerTx.isTransactionGlobal() ? "true" : "false") : "Unknown"));
            }

            if (TEEJBInvocationInfo.isTraceEnabled())
                TEEJBInvocationInfo.tracePreInvokeEnds(s, wrapper);
        }
    }

def _private_notes(self, key, value):

    def _is_for_cds(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'CDS' in normalized_c_values

    def _is_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'HAL' in normalized_c_values

    def _is_not_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'NOT HAL' in normalized_c_values

    _private_notes = self.get('_private_notes', [])
    _export_to = self.get('_export_to', {})

    for value in force_list(value):
        if _is_for_cds(value):
            _export_to['CDS'] = True

        if _is_for_hal(value):
            _export_to['HAL'] = True
        elif _is_not_for_hal(value):
            _export_to['HAL'] = False

        source = force_single_element(value.get('9'))
        for _private_note in force_list(value.get('a')):
            _private_notes.append({
                'source': source,
                'value': _private_note,
            })

    self['_export_to'] = _export_to
    return _private_notes

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


Question: yaw angle angular_speed angle_mode

def cmd_condition_yaw(self, args):
        ''''''
        if ( len(args) != 3):
            print("Usage: yaw ANGLE ANGULAR_SPEED MODE:[0 absolute / 1 relative]")
            return

        if (len(args) == 3):
            angle = float(args[0])
            angular_speed = float(args[1])
            angle_mode = float(args[2])
            print("ANGLE %s" % (str(angle)))

            self.master.mav.command_long_send(
                self.settings.target_system,  # target_system
                mavutil.mavlink.MAV_COMP_ID_SYSTEM_CONTROL, # target_component
                mavutil.mavlink.MAV_CMD_CONDITION_YAW, # command
                0, # confirmation
                angle, # param1 (angle value)
                angular_speed, # param2 (angular speed value)
                0, # param3
                angle_mode, # param4 (mode: 0->absolute / 1->relative)
                0, # param5
                0, # param6
                0)

public function actionView($id)
    {
        $request = \Yii::$app->request;
        if ($request->getIsOptions()) {
            return $this->ResponseOptions($this->verbs()['view']);
        }
        $model = $this->findModel($id);

        return  ['model'=>$model,'items'=>$model->getItems(),];
    }

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


Question:
@param array $options

@return string

private function getFormat(array $options)
    {
        if (isset($options[self::PARAM_FORMAT])) {
            return $options[self::PARAM_FORMAT];
        } else {
            return $this->defaultFormat;
        }
    }

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

        return;
    }

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


Question:
Fill a region of a file with a given byte value.

@param fileChannel to fill
@param position    at which to start writing.
@param length      of the region to write.
@param value       to fill the region with.

public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value)
    {
        try
        {
            final byte[] filler;
            if (0 != value)
            {
                filler = new byte[BLOCK_SIZE];
                Arrays.fill(filler, value);
            }
            else
            {
                filler = FILLER;
            }

            final ByteBuffer byteBuffer = ByteBuffer.wrap(filler);
            fileChannel.position(position);

            final int blocks = (int)(length / BLOCK_SIZE);
            final int blockRemainder = (int)(length % BLOCK_SIZE);

            for (int i = 0; i < blocks; i++)
            {
                byteBuffer.position(0);
                fileChannel.write(byteBuffer);
            }

            if (blockRemainder > 0)
            {
                byteBuffer.position(0);
                byteBuffer.limit(blockRemainder);
                fileChannel.write(byteBuffer);
            }
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            log.severe("Binary content has been requested");

        String repository = request.getParameter("repository");
        String workspace = request.getParameter("workspace");
        String path = request.getParameter("path");
        String property = request.getParameter("property");

        Connector connector = (Connector) request.getSession().getAttribute("connector");
        try {
            Session session = connector.find(repository).session(workspace);
            Node node = session.getNode(path);

            Property p;
            try {
                p = node.getProperty(property);
            } catch (PathNotFoundException e) {
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                writer.write("");
                writer.write("
Content not found or recently removed
");
                writer.write("");
                return;
            }

            Binary binary = p.getBinary();

            InputStream in = binary.getStream();
            String contentType = node.getProperty("jcr:mimeType").getString();

            response.setContentType(contentType);

            int b;
            while ((b = in.read()) != -1) {
                response.getOutputStream().write(b);
            }

            log.severe("Sent binary content");
            binary.dispose();

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

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


Question:
Unmounts a rendered child.

NOTE: This is part of `updateChildren` and is here for readability.

@param {ReactComponent} child Component to unmount.
@private

function (child, node) {
	      var update = this.removeChild(child, node);
	      child._mountIndex = null;
	      return update;
	    }

function Resolve(context, model) {
        if (model == null) {
            // 清空context
            for (var prop in context) {
                var target = context[prop];
                if (target instanceof view_4.View) {
                    var propName = target.PropertyName();
                    if (propName) {
                        if (target instanceof text_3.TextView || target instanceof choice_1.ChoiceView) {
                            target.Clear();
                        }
                        else if (target instanceof list_2.ListView) {
                            target.SetData([]);
                        }
                        else {
                            console.warn(propName + " clear failed, missing clear method!");
                        }
                    }
                }
            }
            return;
        }
        for (var prop in context) {
            var target = context[prop];
            if (target instanceof view_4.View) {
                var propName = target.PropertyName();
                if (propName) {
                    var value = model[propName];
                    if (value) {
                        // 注入
                        if (target instanceof text_3.TextView || target instanceof choice_1.ChoiceView) {
                            target.SetValue(value);
                        }
                        else if (target instanceof list_2.ListView && $.isArray(value)) {
                            target.SetData(value);
                        }
                        else {
                            console.warn(propName + " resolve failed, control type is mismatching!");
                        }
                    }
                    else {
                        console.warn(propName + " resolve failed, value invalid!");
                    }
                }
            }
        }
    }

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


Question: // AllUnits implements PrecheckApplication.

func (s *precheckAppShim) AllUnits() ([]PrecheckUnit, error) {
	units, err := s.Application.AllUnits()
	if err != nil {
		return nil, errors.Trace(err)
	}
	out := make([]PrecheckUnit, 0, len(units))
	for _, unit := range units {
		out = append(out, unit)
	}
	return out, nil
}

public <T> void registerConverter(final Class<T> clazz, final CellConverterFactory<T> converterFactory) {
        ArgUtils.notNull(clazz, "clazz");
        ArgUtils.notNull(converterFactory, "converterFactory");

        converterFactoryMap.put(clazz, converterFactory);
    }

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


Question:
IPN handling function.
- Verify request with PayPal (if request from PayPal and to correct shop).

@return bool

public function requestValid()
    {
        $requestValid = true;

        $request = $this->getRequest();

        $ipnRequestVerifier = $this->getIPNRequestVerifier();
        $ipnRequestVerifier->setRequest($request);
        $ipnRequestVerifier->setShopOwner($this->getPayPalConfig()->getUserEmail());
        $requestCorrect = $ipnRequestVerifier->requestCorrect();

        if (!$requestCorrect) {
            $requestValid = false;

            $logger = $this->getLogger();
            $logger->setTitle("IPN VERIFICATION FAILURE BY PAYPAL");
            $logger->log($ipnRequestVerifier->getFailureMessage());
        }

        return $requestValid;
    }

private function parse($body)
    {
        $result = array();
        $data = json_decode($body);

        $response = is_array($data->response) ? new \stdClass : $data->response;
        if (null == $response) {
            $response = $data;
        }
        $response->errors = $data->errors;
        $response->test = isset($data->test) ? $data->test : $response->test;

        if ($data->successful == true) {
            if ((isset($response->authorized)
                && $response->authorized == true)
                || (isset($response->id)
                && $response->id !== null)
            ) {
                $response->authorization_id = isset($response->id)
                    ? $response->id
                    : $response->token;
            } else {
                $response->authorization_id = null;
            }

            $response->success = true;
        } else {
            $response->success = false;
            $response->authorization_id = null;
        }

        $response->message = isset($response->message) ? $response->message : $data->errors;

        return (array) $response;

    }

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


Question:
Check if any character inside the passed URL needs escaping.

@param sURL
The URL to be checked. May not be null.
@return true if any of the contained characters needs
escaping, false if the URL can be used as is.

public static boolean isCSSURLRequiringQuotes (@Nonnull final String sURL)
  {
    ValueEnforcer.notNull (sURL, "URL");

    for (final char c : sURL.toCharArray ())
      if (!isValidCSSURLChar (c))
        return true;
    return false;
  }

public static String replaceAllSpecialChracters(String toBeReplaced) {
	toBeReplaced = toBeReplaced.replaceAll("&", "&");
	toBeReplaced = toBeReplaced.replaceAll("<", "<");
	toBeReplaced = toBeReplaced.replaceAll(">", ">");
	toBeReplaced = toBeReplaced.replaceAll("\"", """);
	toBeReplaced = toBeReplaced.replaceAll("'", "'");
	// toBeReplaced = toBeReplaced.replace("^", "&circ");
	// toBeReplaced = toBeReplaced.replaceAll("0xb", "");
	int len = toBeReplaced.length();
	char[] temp = toBeReplaced.toCharArray();
	for (int i = 0; i < len; i++) {
	    char xCode = temp[i];
	    if ((xCode > '\u0000' && xCode <= '\u0020') || (xCode == '\u0026')
		    || (xCode == '\u0022') || (xCode == '\u02C6')
		    || (xCode == '\u201C') || (xCode == '\u201D')
		    || (xCode == '\u201E')) {
		String sub1 = toBeReplaced.substring(0, i);
		String sub2 = toBeReplaced.substring(i + 1, len);

		String replacement = "";
		if ((xCode > '\u0000' && xCode <= '\u0020'))
		    replacement = " ";
		if (xCode == '\u0026')
		    replacement = " ";
		if (xCode == '\u0022')
		    replacement = " ";
		if (xCode == '\u02C6')
		    replacement = " ";
		if (xCode == '\u201C')
		    replacement = " ";
		if (xCode == '\u201D')
		    replacement = " ";
		if (xCode == '\u201E')
		    replacement = " ";

		toBeReplaced = sub1 + replacement + sub2;
	    }
	    len = toBeReplaced.length();
	    temp = toBeReplaced.toCharArray();
	}

	return (toBeReplaced);
    }

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


Question:
Get short name.
@return ?string

public final function getShortName(): ?string
    {
        return ($this->name != null) ? substr($this->name, 0, -strlen(self::SERVICE_NAME_SUFFIX)) : null;
    }

function(str){
	var retstr = str;

	if( ! us.isUndefined(str) && str.length > 2 ){
	    var end = str.length -1;
	    if( str.charAt(0) == '"' && str.charAt(end) == '"' ){
		retstr = str.substr(1, end -1);
	    }
	}

	return retstr;
    }

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


Question: This gets called each time a "new" rule table is found.

private void initRuleTable(final int row,
            final int column,
            final String value) {
        preInitRuleTable( row, column, value );
        this._isInRuleTable = true;
        this._actions = new HashMap<Integer, ActionType>();
        this.sourceBuilders = new TreeSet<SourceBuilder>(Comparator.comparing( SourceBuilder::getColumn ));
        this._ruleStartColumn = column;
        this._ruleStartRow = row;
        this._ruleRow = row + LABEL_ROW + 1;

        // setup stuff for the rules to come.. (the order of these steps are
        // important !)
        this._currentRulePrefix = RuleSheetParserUtil.getRuleName( value );
        if (this.worksheetName != null) {
            this._currentRulePrefix += " " + worksheetName;
        }

        this._currentSequentialFlag = getFlagValue(SEQUENTIAL_FLAG, false);
        this._currentEscapeQuotesFlag = getFlagValue(ESCAPE_QUOTES_FLAG, true);
        this._currentNumericDisabledFlag = getFlagValue(NUMERIC_DISABLED_FLAG, false);

        this._currentSalience = getNumericValue( MAX_SALIENCE_TAG, this._currentSalience );
        this._minSalienceTag = getNumericValue(MIN_SALIENCE_TAG, this._minSalienceTag);

        String headCell = RuleSheetParserUtil.rc2name( this._ruleStartRow, this._ruleStartColumn );
        String ruleCell = RuleSheetParserUtil.rc2name( this._ruleRow, this._ruleStartColumn );
        this._currentRule = createNewRuleForRow( this._ruleRow, headCell, ruleCell );

        this._ruleList.add( this._currentRule );
        postInitRuleTable( row, column, value );

    }

func (session *Session) CreateTable(bean interface{}) error {
	v := rValue(bean)
	session.Statement.setRefValue(v)

	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	return session.createOneTable()
}

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


Question:
Create a new temporary Conversation

@param conversationMembers
@param ttl
@param callback

public void createTemporaryConversation(final List<String> conversationMembers, int ttl, final AVIMConversationCreatedCallback callback) {
    this.createConversation(conversationMembers, null, null, false, true, true, ttl, callback);
  }

function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}

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


Question: update tweeners. delta_seconds is time in seconds since last frame

def update(self, delta_seconds):
        """"""

        for obj in tuple(self.current_tweens):
            for tween in tuple(self.current_tweens[obj]):
                done = tween.update(delta_seconds)
                if done:
                    self.current_tweens[obj].remove(tween)
                    if tween.on_complete: tween.on_complete(tween.target)

            if not self.current_tweens[obj]:
                del self.current_tweens[obj]

        return self.current_tweens

public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int
            snapPreference) {
        switch (snapPreference) {
            case SNAP_TO_START:
                return boxStart - viewStart;
            case SNAP_TO_END:
                return boxEnd - viewEnd;
            case SNAP_TO_ANY:
                final int dtStart = boxStart - viewStart;
                if (dtStart > 0) {
                    return dtStart;
                }
                final int dtEnd = boxEnd - viewEnd;
                if (dtEnd < 0) {
                    return dtEnd;
                }
                break;
            default:
                throw new IllegalArgumentException("snap preference should be one of the"
                        + " constants defined in SmoothScroller, starting with SNAP_");
        }
        return 0;
    }

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


Question:
Builds Layer Menu from OPML String.
@access		public
@param		string		$opml			OPML String
@return

public function buildMenuFromOpml( $opml )
	{
		$list		= Alg_Tree_Menu_Converter::convertFromOpml( $opml, $this->rootLabel );
		return $this->buildMenuFromMenuList( $list );
	}

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question:
Adds an array of namespace paths. See {add_namespace}.

@param   array  the namespaces
@param   bool   whether to prepend the namespace to the search path
@return  void

public static function add_namespaces(array $namespaces, $prepend = false)
	{
		if ( ! $prepend)
		{
			static::$namespaces = array_merge(static::$namespaces, $namespaces);
		}
		else
		{
			static::$namespaces = $namespaces + static::$namespaces;
		}
	}

public function compile(CompilationContext $compilationContext)
    {
        /*
         * Set the method currently being compiled
         */
        $compilationContext->currentMethod = $this;

        /*
         * Initialize the method warm-up to null
         */
        $compilationContext->methodWarmUp = null;

        /**
         * Assign pre-made compilation passes.
         */
        $localContext = $this->localContext;
        $typeInference = $this->typeInference;
        $callGathererPass = $this->callGathererPass;

        /**
         * Initialization of parameters happens in a fictitious external branch.
         */
        $branch = new Branch();
        $branch->setType(Branch::TYPE_EXTERNAL);
        /**
         * BranchManager helps to create graphs of conditional/loop/root/jump branches.
         */
        $branchManager = new BranchManager();
        $branchManager->addBranch($branch);

        $compilationContext->branchManager = $branchManager;

        /**
         * Every method has its own symbol table.
         */
        $symbolTable = new SymbolTable($compilationContext);
        if ($localContext) {
            $symbolTable->setLocalContext($localContext);
        }

        if ($this->staticVariables) {
            foreach ($this->staticVariables as $var) {
                $localVar = clone $var;
                $localVar->setIsExternal(true);
                $localVar->setLocalOnly(true);
                $localVar->setType('variable');
                $symbolTable->addRawVariable($localVar);
            }
        }

        /**
         * Parameters has an additional extra mutation.
         */
        $parameters = $this->parameters;
        if ($localContext) {
            if (\is_object($parameters)) {
                foreach ($parameters->getParameters() as $parameter) {
                    $localContext->increaseMutations($parameter['name']);
                }
            }
        }

        /**
         * Cache Manager manages function calls, method calls and class entries caches.
         */
        $cacheManager = new CacheManager();
        $cacheManager->setGatherer($callGathererPass);

        $compilationContext->cacheManager = $cacheManager;
        $compilationContext->typeInference = $typeInference;
        $compilationContext->symbolTable = $symbolTable;

        $oldCodePrinter = $compilationContext->codePrinter;

        /**
         * Change the code printer to a single method instance.
         */
        $codePrinter = new CodePrinter();
        $compilationContext->codePrinter = $codePrinter;

        /*
         * Set an empty function cache
         */
        $compilationContext->functionCache = null;

        /*
         * Reset try/catch and loop counter
         */
        $compilationContext->insideCycle = 0;
        $compilationContext->insideTryCatch = 0;
        $compilationContext->currentTryCatch = 0;

        if (\is_object($parameters)) {
            /**
             * Round 1. Create variables in parameters in the symbol table.
             */
            $classCastChecks = [];
            $substituteVars = [];
            foreach ($parameters->getParameters() as $parameter) {
                /*
                 * Change dynamic variables to low level types
                 */
                if ($typeInference) {
                    if (isset($parameter['data-type'])) {
                        if ('variable' == $parameter['data-type']) {
                            $type = $typeInference->getInferedType($parameter['name']);
                            if (\is_string($type)) {
                                /* promote polymorphic parameters to low level types */
                            }
                        }
                    } else {
                        $type = $typeInference->getInferedType($parameter['name']);
                        if (\is_string($type)) {
                            /* promote polymorphic parameters to low level types */
                        }
                    }
                }

                $symbolParam = null;

                if (isset($parameter['data-type'])) {
                    switch ($parameter['data-type']) {
                        case 'object':
                        case 'callable':
                        case 'resource':
                        case 'variable':
                            $symbol = $symbolTable->addVariable($parameter['data-type'], $parameter['name'], $compilationContext);
                            /* TODO: Move this to the respective backend, which requires refactoring how this works */
                            if ($compilationContext->backend->isZE3()) {
                                $symbol->setIsDoublePointer(true);
                                $substituteVars[$parameter['name']] = $symbolTable->addVariable('variable', $parameter['name'].'_sub', $compilationContext);
                            }
                            break;

                        default:
                            $symbol = $symbolTable->addVariable($parameter['data-type'], $parameter['name'], $compilationContext);
                            $symbolParam = $symbolTable->addVariable('variable', $parameter['name'].'_param', $compilationContext);
                            /* TODO: Move this to the respective backend, which requires refactoring how this works */
                            if ($compilationContext->backend->isZE3()) {
                                $symbolParam->setIsDoublePointer(true);
                            }
                            if ('string' == $parameter['data-type'] || 'array' == $parameter['data-type']) {
                                $symbol->setMustInitNull(true);
                            }
                            break;
                    }
                } else {
                    $symbol = $symbolTable->addVariable('variable', $parameter['name'], $compilationContext);
                }

                /* ZE3 only */
                if (isset($substituteVars[$parameter['name']])) {
                    $substituteVar = $substituteVars[$parameter['name']];
                    $substituteVar->increaseUses();
                }

                /*
                 * Some parameters can be read-only
                 */
                if (isset($parameter['const']) && $parameter['const']) {
                    $symbol->setReadOnly(true);
                    if (\is_object($symbolParam)) {
                        $symbolParam->setReadOnly(true);
                    }
                }

                if (\is_object($symbolParam)) {
                    /*
                     * Parameters are marked as 'external'
                     */
                    $symbolParam->setIsExternal(true);

                    /*
                     * Assuming they're initialized
                     */
                    $symbolParam->setIsInitialized(true, $compilationContext);

                    /*
                     * Initialize auxiliary parameter zvals to null
                     */
                    $symbolParam->setMustInitNull(true);

                    /*
                     * Increase uses
                     */
                    $symbolParam->increaseUses();
                } else {
                    if (isset($parameter['default'])) {
                        if (isset($parameter['data-type'])) {
                            if ('variable' == $parameter['data-type']) {
                                $symbol->setMustInitNull(true);
                            }
                        } else {
                            $symbol->setMustInitNull(true);
                        }
                    }
                }

                /*
                 * Original node where the variable was declared
                 */
                $symbol->setOriginal($parameter);

                /*
                 * Parameters are marked as 'external'
                 */
                $symbol->setIsExternal(true);

                /*
                 * Assuming they're initialized
                 */
                $symbol->setIsInitialized(true, $compilationContext);

                /*
                 * Variables with class/type must be objects across the execution
                 */
                if (isset($parameter['cast'])) {
                    $symbol->setDynamicTypes('object');
                    $symbol->setClassTypes($compilationContext->getFullName($parameter['cast']['value']));
                    $classCastChecks[] = [$symbol, $parameter];
                } else {
                    if (isset($parameter['data-type'])) {
                        if ('variable' == $parameter['data-type']) {
                            $symbol->setDynamicTypes('undefined');
                        }
                    } else {
                        $symbol->setDynamicTypes('undefined');
                    }
                }
            }
        }

        $compilationContext->backend->onPreCompile($this, $compilationContext);

        /*
         * Compile the block of statements if any
         */
        if (\is_object($this->statements)) {
            if ($this->hasModifier('static')) {
                $compilationContext->staticContext = true;
            } else {
                $compilationContext->staticContext = false;
            }

            /*
             * Compile the statements block as a 'root' branch
             */
            $this->statements->compile($compilationContext, false, Branch::TYPE_ROOT);
        }

        /**
         * Initialize variable default values.
         */
        $initVarCode = $compilationContext->backend->initializeVariableDefaults($symbolTable->getVariables(), $compilationContext);

        /**
         * Fetch parameters from vm-top.
         */
        $initCode = '';
        $code = '';
        if (\is_object($parameters)) {
            /**
             * Round 2. Fetch the parameters in the method.
             */
            $params = [];
            $requiredParams = [];
            $optionalParams = [];
            $numberRequiredParams = 0;
            $numberOptionalParams = 0;
            foreach ($parameters->getParameters() as $parameter) {
                if (isset($parameter['data-type'])) {
                    $dataType = $parameter['data-type'];
                } else {
                    $dataType = 'variable';
                }

                switch ($dataType) {
                    case 'object':
                    case 'callable':
                    case 'resource':
                    case 'variable':
                        if (!$this->isInternal()) {
                            $params[] = '&'.$parameter['name'];
                        } else {
                            $params[] = $parameter['name'];
                        }
                        break;

                    default:
                        if (!$this->isInternal()) {
                            $params[] = '&'.$parameter['name'].'_param';
                        } else {
                            $params[] = $parameter['name'].'_param';
                        }
                        break;
                }

                if (isset($parameter['default'])) {
                    $optionalParams[] = $parameter;
                    ++$numberOptionalParams;
                } else {
                    $requiredParams[] = $parameter;
                    ++$numberRequiredParams;
                }
            }

            /**
             * Pass the write detector to the method statement block to check if the parameter
             * variable is modified so as do the proper separation.
             */
            $parametersToSeparate = [];
            if (\is_object($this->statements)) {
                /*
                 * If local context is not available
                 */
                if (!$localContext) {
                    $writeDetector = new WriteDetector();
                }

                foreach ($parameters->getParameters() as $parameter) {
                    if (isset($parameter['data-type'])) {
                        $dataType = $parameter['data-type'];
                    } else {
                        $dataType = 'variable';
                    }

                    switch ($dataType) {
                        case 'variable':
                        case 'string':
                        case 'array':
                        case 'resource':
                        case 'object':
                        case 'callable':
                            $name = $parameter['name'];
                            if (!$localContext) {
                                if ($writeDetector->detect($name, $this->statements->getStatements())) {
                                    $parametersToSeparate[$name] = true;
                                }
                            } else {
                                if ($localContext->getNumberOfMutations($name) > 1) {
                                    $parametersToSeparate[$name] = true;
                                }
                            }
                            break;
                    }
                }
            }

            /*
             * Initialize required parameters
             */
            foreach ($requiredParams as $parameter) {
                if (isset($parameter['mandatory'])) {
                    $mandatory = $parameter['mandatory'];
                } else {
                    $mandatory = 0;
                }

                if (isset($parameter['data-type'])) {
                    $dataType = $parameter['data-type'];
                } else {
                    $dataType = 'variable';
                }

                if ('variable' != $dataType) {
                    /*
                     * Assign value from zval to low level type
                     */
                    if ($mandatory) {
                        $initCode .= $this->checkStrictType($parameter, $compilationContext);
                    } else {
                        $initCode .= $this->assignZvalValue($parameter, $compilationContext);
                    }
                }

                switch ($dataType) {
                    case 'variable':
                    case 'resource':
                    case 'object':
                    case 'callable':
                        if (isset($parametersToSeparate[$parameter['name']])) {
                            $symbolTable->mustGrownStack(true);
                            $initCode .= "\t".'ZEPHIR_SEPARATE_PARAM('.$parameter['name'].');'.PHP_EOL;
                        }
                        break;
                }
            }

            /*
             * Initialize optional parameters
             */
            foreach ($optionalParams as $parameter) {
                if (isset($parameter['mandatory'])) {
                    $mandatory = $parameter['mandatory'];
                } else {
                    $mandatory = 0;
                }

                if (isset($parameter['data-type'])) {
                    $dataType = $parameter['data-type'];
                } else {
                    $dataType = 'variable';
                }

                switch ($dataType) {
                    case 'object':
                    case 'callable':
                    case 'resource':
                    case 'variable':
                        $name = $parameter['name'];
                        break;

                    default:
                        $name = $parameter['name'].'_param';
                        break;
                }

                /**
                 * Assign the default value according to the variable's type.
                 */
                $targetVar = $compilationContext->symbolTable->getVariableForWrite($name, $compilationContext);
                $initCode .= "\t".$compilationContext->backend->ifVariableValueUndefined($targetVar, $compilationContext, false, false).PHP_EOL;

                if ($compilationContext->backend->isZE3()) {
                    if ($targetVar->isDoublePointer() && isset($substituteVars[$parameter['name']])) {
                        $substituteVar = $substituteVars[$parameter['name']];
                        $initCode .= "\t\t".$targetVar->getName().' = &'.$substituteVar->getName().';'.PHP_EOL;
                    }
                }
                $initCode .= $this->assignDefaultValue($parameter, $compilationContext);

                if (isset($parametersToSeparate[$name]) || 'variable' != $dataType) {
                    $initCode .= "\t".'} else {'.PHP_EOL;
                    if (isset($parametersToSeparate[$name])) {
                        $initCode .= "\t\t".'ZEPHIR_SEPARATE_PARAM('.$name.');'.PHP_EOL;
                    } else {
                        if ($mandatory) {
                            $initCode .= $this->checkStrictType($parameter, $compilationContext, $mandatory);
                        } else {
                            $initCode .= "\t".$this->assignZvalValue($parameter, $compilationContext);
                        }
                    }
                }

                $initCode .= "\t".'}'.PHP_EOL;
            }

            /*
             * Fetch the parameters to zval pointers
             */
            $codePrinter->preOutputBlankLine();

            if (!$this->isInternal()) {
                $compilationContext->headersManager->add('kernel/memory');
                if ($symbolTable->getMustGrownStack()) {
                    $code .= "\t".'zephir_fetch_params(1, '.$numberRequiredParams.', '.$numberOptionalParams.', '.implode(', ', $params).');'.PHP_EOL;
                } else {
                    $code .= "\t".'zephir_fetch_params(0, '.$numberRequiredParams.', '.$numberOptionalParams.', '.implode(', ', $params).');'.PHP_EOL;
                }
            } else {
                foreach ($params as $param) {
                    /* TODO: Migrate all this code to codeprinter, get rid of temp code printer */
                    $tempCodePrinter = new CodePrinter();
                    $realCodePrinter = $compilationContext->codePrinter;
                    $compilationContext->codePrinter = $tempCodePrinter;
                    $paramVar = $compilationContext->symbolTable->getVariableForRead($param, $compilationContext);
                    $compilationContext->backend->assignZval($paramVar, $param.'_ext', $compilationContext);
                    $code .= "\t".$tempCodePrinter->getOutput().PHP_EOL;
                    $compilationContext->codePrinter = $realCodePrinter;
                }
            }
            $code .= PHP_EOL;
        }

        $code .= $initCode.$initVarCode;
        $codePrinter->preOutput($code);

        $compilationContext->headersManager->add('kernel/object');
        /*
         * Fetch used superglobals
         */
        foreach ($symbolTable->getVariables() as $name => $variable) {
            if ($variable->isSuperGlobal()) {
                $globalVar = $symbolTable->getVariable($name);
                $codePrinter->preOutput("\t".$compilationContext->backend->fetchGlobal($globalVar, $compilationContext, false));
            }
            if ($variable->isLocalSatic()) {
                $staticVar = $symbolTable->getVariable($name);

                $codePrinter->preOutput(sprintf(
                    "\t".'zephir_read_static_property_ce(%s%s, %s, SL("%s"), PH_NOISY_CC%s);',
                    $staticVar->isDoublePointer() ? '' : '&',
                    $staticVar->getName(),
                    $this->classDefinition->getClassEntry(),
                    $staticVar->getName(),
                    ''
                ));
            }
        }

        /*
         * Grow the stack if needed
         */
        if ($symbolTable->getMustGrownStack()) {
            $compilationContext->headersManager->add('kernel/memory');
            $codePrinter->preOutput("\t".'ZEPHIR_MM_GROW();');
        }

        /**
         * Check if there are unused variables.
         */
        $usedVariables = [];
        $classDefinition = $this->getClassDefinition();
        if ($classDefinition) {
            $completeName = $classDefinition->getCompleteName();
        } else {
            $completeName = '[unknown]';
        }

        foreach ($symbolTable->getVariables() as $variable) {
            if ($variable->getNumberUses() <= 0) {
                if (false == $variable->isExternal()) {
                    $compilationContext->logger->warning(
                        'Variable "'.$variable->getName().'" declared but not used in '.$completeName.'::'.$this->getName(),
                        ['unused-variable', $variable->getOriginal()]
                    );
                    continue;
                }
                $compilationContext->logger->warning(
                    'Variable "'.$variable->getName().'" declared but not used in '.$completeName.'::'.$this->getName(),
                    ['unused-variable-external', $variable->getOriginal()]
                );
            }

            if ('this_ptr' != $variable->getName() && 'return_value' != $variable->getName() && 'return_value_ptr' != $variable->getName()) {
                $type = $variable->getType();
                if (!isset($usedVariables[$type])) {
                    $usedVariables[$type] = [];
                }
                $usedVariables[$type][] = $variable;
            }
        }

        /*
         * Check if there are assigned but not used variables
         * Warn whenever a variable is unused aside from its declaration.
         */
        foreach ($symbolTable->getVariables() as $variable) {
            if (true == $variable->isExternal() || $variable->isTemporal()) {
                continue;
            }

            if ('this_ptr' == $variable->getName() || 'return_value' == $variable->getName() || 'return_value_ptr' == $variable->getName() || 'ZEPHIR_LAST_CALL_STATUS' == $variable->getName()) {
                continue;
            }

            if (!$variable->isUsed()) {
                $node = $variable->getLastUsedNode();
                if (\is_array($node)) {
                    $expression = isset($node['expr']) ? $node['expr'] : $node;
                    $compilationContext->logger->warning(
                        'Variable "'.$variable->getName().'" assigned but not used in '.$completeName.'::'.$this->getName(),
                        ['unused-variable', $expression]
                    );
                } else {
                    $compilationContext->logger->warning(
                        'Variable "'.$variable->getName().'" assigned but not used in '.$completeName.'::'.$this->getName(),
                        ['unused-variable', $variable->getOriginal()]
                    );
                }
            }
        }

        if (\count($usedVariables)) {
            $codePrinter->preOutputBlankLine();
        }

        /**
         * Generate the variable definition for variables used.
         */
        $initCode = "\t".implode(PHP_EOL."\t", $compilationContext->backend->declareVariables($this, $usedVariables, $compilationContext));
        if ($initCode) {
            $codePrinter->preOutput($initCode);
        }

        /*
         * Finalize the method compilation
         */
        if (\is_object($this->statements)) {
            /**
             * If the last statement is not a 'return' or 'throw' we need to
             * restore the memory stack if needed.
             */
            $lastType = $this->statements->getLastStatementType();

            if ('return' != $lastType && 'throw' != $lastType && !$this->hasChildReturnStatementType($this->statements->getLastStatement())) {
                if ($symbolTable->getMustGrownStack()) {
                    $compilationContext->headersManager->add('kernel/memory');
                    $codePrinter->output("\t".'ZEPHIR_MM_RESTORE();');
                }

                /*
                 * If a method has return-type hints we need to ensure the last statement is a 'return' statement
                 */
                if ($this->hasReturnTypes()) {
                    throw new CompilerException(
                        'Reached end of the method without returning a valid type specified in the return-type hints',
                        $this->expression['return-type']
                    );
                }
            }
        }

        $compilationContext->backend->onPostCompile($this, $compilationContext);

        /**
         * Remove macros that grow/restore the memory frame stack if it wasn't used.
         */
        $code = $this->removeMemoryStackReferences($symbolTable, $codePrinter->getOutput());

        /*
         * Restore the compilation context
         */
        $oldCodePrinter->output($code);
        $compilationContext->codePrinter = $oldCodePrinter;

        $compilationContext->branchManager = null;
        $compilationContext->cacheManager = null;
        $compilationContext->typeInference = null;

        $codePrinter->clear();

        return null;
    }

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


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

@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case XtextPackage.PARAMETER__NAME:
				setName((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question:
Set the value on the source entity. If at any point the chaining results in a null value. The chaining
should end.

@param toEntity
the entity on which the getter should operate.
@param newValue
the value to set.

public void setValue(Object toEntity, Object newValue) throws IllegalAccessException,
            InvocationTargetException
    {
        Object propertyValue = getter.invoke(toEntity);
        if (propertyValue != null)
            nestedWriter.setValue(propertyValue, newValue);
    }

private LogRecord doToModel(LogRecordDO logRecordDo) {
        LogRecord logRecord = new LogRecord();
        try {

            logRecord.setId(logRecordDo.getId());
            if (logRecordDo.getPipelineId() > 0 && logRecordDo.getChannelId() > 0) {
                try {
                    Channel channel = channelService.findByPipelineId(logRecordDo.getPipelineId());
                    logRecord.setChannel(channel);
                    for (Pipeline pipeline : channel.getPipelines()) {
                        if (pipeline.getId().equals(logRecordDo.getPipelineId())) {
                            logRecord.setPipeline(pipeline);
                        }
                    }
                } catch (Exception e) {
                    // 可能历史的log记录对应的channel/pipeline已经被删除了，直接忽略吧
                    Channel channel = new Channel();
                    channel.setId(0l);
                    logRecord.setChannel(channel);
                    Pipeline pipeline = new Pipeline();
                    pipeline.setId(0l);
                    logRecord.setPipeline(pipeline);
                }
            } else {
                Channel channel = new Channel();
                channel.setId(-1l);
                logRecord.setChannel(channel);
                Pipeline pipeline = new Pipeline();
                pipeline.setId(-1l);
                logRecord.setPipeline(pipeline);
            }

            logRecord.setTitle(logRecordDo.getTitle());
            logRecord.setNid(logRecordDo.getNid());
            logRecord.setMessage(logRecordDo.getMessage());
            logRecord.setGmtCreate(logRecordDo.getGmtCreate());
            logRecord.setGmtModified(logRecordDo.getGmtModified());

        } catch (Exception e) {
            logger.error("ERROR ## ");
            throw new ManagerException(e);
        }

        return logRecord;
    }

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


Question:
Given a vector v, compute the overlap with the weight matrix w and save
  the histogram of overlaps.

def plotOverlapHistogram(v, w, title, base="random"):

  overlaps = v.matmul(w.t())

  # Plot histogram of overlaps
  bins = np.linspace(float(overlaps.min()), float(overlaps.max()), 28)
  plt.hist(overlaps, bins, alpha=0.5, label='All cols')
  plt.legend(loc='upper right')
  plt.xlabel("Overlap scores")
  plt.ylabel("Frequency")
  plt.title(title)
  plt.savefig(base+"_1")
  plt.close()

  return overlaps

public function thumbprint(string $hash_algorithm): string
    {
        if (!\in_array($hash_algorithm, \hash_algos(), true)) {
            throw new \InvalidArgumentException(\sprintf('The hash algorithm "%s" is not supported.', $hash_algorithm));
        }

        $values = \array_intersect_key($this->values, \array_flip(['kty', 'n', 'e', 'crv', 'x', 'y', 'k']));
        \ksort($values);
        $input = \json_encode($values, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        return Base64Url::encode(\hash($hash_algorithm, $input, true));
    }

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


Question:
Get all token types that an address owns
        Returns {'tokens': [...]}

def GET_account_tokens(self, path_info, account_addr):

        if not check_account_address(account_addr):
            return self._reply_json({'error': 'Invalid address'}, status_code=400)

        blockstackd_url = get_blockstackd_url()
        res = blockstackd_client.get_account_tokens(account_addr, hostport=blockstackd_url)
        if json_is_error(res):
            log.error("Failed to load tokens for {}: {}".format(account_addr, res['error']))
            return self._reply_json({'error': 'Failed to load tokens for {}: {}'.format(account_addr, res['error'])}, status_code=res.get('http_status', 500))

        self._reply_json({'tokens': res})
        return

public void marshall(GetFederationTokenRequest getFederationTokenRequest, ProtocolMarshaller protocolMarshaller) {

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

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

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


Question:
Combines separate text lines from API response into one string with \n line endings.
Code relying on raw text can now parse it.

@param string|\stdClass|mixed $response

@return string Combined lines of text returned by API

protected function bbserver_recombine_response( $response ) {
		if ( $this->validate_response( $response ) ) {
			return $response;
		}
		$remote_info_file = '';
		if ( isset( $response->lines ) ) {
			foreach ( (array) $response->lines as $line ) {
				$remote_info_file .= $line->text . "\n";
			}
		}

		return $remote_info_file;
	}

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question: Updates the buffer capacity.

public Buffer capacity(long capacity) {
    if (capacity > maxCapacity) {
      throw new IllegalArgumentException("capacity cannot be greater than maximum capacity");
    } else if (capacity < this.capacity) {
      throw new IllegalArgumentException("capacity cannot be decreased");
    } else if (capacity != this.capacity) {
      // It's possible that the bytes could already meet the requirements of the capacity.
      if (offset(capacity) > bytes.size()) {
        bytes.resize(Memory.Util.toPow2(offset(capacity)));
      }
      this.capacity = capacity;
    }
    return this;
  }

def number_of_modified_bytes(buf, fuzzed_buf):

    count = 0
    for idx, b in enumerate(buf):
        if b != fuzzed_buf[idx]:
            count += 1
    return count

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


Question: // SetCollectionId sets the CollectionId field's value.

func (s *DeleteFacesInput) SetCollectionId(v string) *DeleteFacesInput {
	s.CollectionId = &v
	return s
}

protected List<ColumnDef> getIndexes() throws IOException
    {
        CfDef cfdef = getCfInfo(loadSignature).cfDef;
        List<ColumnDef> indexes = new ArrayList<ColumnDef>();
        for (ColumnDef cdef : cfdef.column_metadata)
        {
            if (cdef.index_type != null)
                indexes.add(cdef);
        }
        return indexes;
    }

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


Question:
Lookup template for given page.
@param page Page
@param templates Templates
@return The {@link TemplatePathInfo} instance or null for unknown template paths

public static TemplatePathInfo forPage(@NotNull Page page, @NotNull TemplatePathInfo @NotNull... templates) {
    if (page == null || templates == null) {
      return null;
    }
    String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
    return forTemplatePath(templatePath, templates);
  }

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question:
Determines whether the given $haystack contains any of the $needles. Alias for self::contains() with an
array of needles and the $all parameter set to false.

@see Str::contains()

public static function containsAny(string $haystack, array $needles, bool $strict = true, string $encoding = null) : bool
    {
        return static::contains($haystack, $needles, false, $strict, $encoding);
    }

public static function isUser(string $username): bool {
		$userdbname = setup::getValidation("username");
		if (R::findOne('user', ' ' . $userdbname . ' = ? ', [$username])) {
			return true;
		}

		return false;
	}

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


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

public static tmsessionaction get(nitro_service service, String name) throws Exception{
		tmsessionaction obj = new tmsessionaction();
		obj.set_name(name);
		tmsessionaction response = (tmsessionaction) obj.get_resource(service);
		return response;
	}

def __Get(self, path, request, headers):

        return synchronized_request.SynchronizedRequest(self,
                                                        request,
                                                        self._global_endpoint_manager,
                                                        self.connection_policy,
                                                        self._requests_session,
                                                        'GET',
                                                        path,
                                                        None,
                                                        None,
                                                        headers)

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


Question:
Handle an event that is generated by a person interacting with a button.  It may be a button press
    or a key press.

def __buttonEvent(event=None, buttons=None, virtual_event=None):

    # TODO: Replace globals with tkinter variables
    global boxRoot, __replyButtonText

    # Determine window location and save to global
    m = re.match("(\d+)x(\d+)([-+]\d+)([-+]\d+)", boxRoot.geometry())
    if not m:
        raise ValueError(
            "failed to parse geometry string: {}".format(boxRoot.geometry()))
    width, height, xoffset, yoffset = [int(s) for s in m.groups()]
    st.rootWindowPosition = '{0:+g}{1:+g}'.format(xoffset, yoffset)

    # print('{0}:{1}:{2}'.format(event, buttons, virtual_event))
    if virtual_event == 'cancel':
        for button_name, button in list(buttons.items()):
            if 'cancel_choice' in button:
                __replyButtonText = button['original_text']
        __replyButtonText = None
        boxRoot.quit()
        return

    if virtual_event == 'select':
        text = event.widget.config('text')[-1]
        if not isinstance(text, ut.str):
            text = ' '.join(text)
        for button_name, button in list(buttons.items()):
            if button['clean_text'] == text:
                __replyButtonText = button['original_text']
                boxRoot.quit()
                return

    # Hotkeys
    if buttons:
        for button_name, button in list(buttons.items()):
            hotkey_pressed = event.keysym
            if event.keysym != event.char:  # A special character
                hotkey_pressed = '<{}>'.format(event.keysym)
            if button['hotkey'] == hotkey_pressed:
                __replyButtonText = button_name
                boxRoot.quit()
                return

    print("Event not understood")

public T get(Computer c) {
        if(record==null || !record.data.containsKey(c)) {
            // if we don't have the data, schedule the check now
            triggerUpdate();
            return null;
        }
        return record.data.get(c);
    }

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


Question:
register a configuration class
        :param cls:
        :param name:
        :return:

def register_config(self, cls, name):

        self._configs.add(cls)
        self._config_names.add(name)

public function load($file, $type = null)
    {
        $path   = $this->locator->locate($file);
        $config = array();

        $result = parse_ini_file($path, true);
        if (false === $result || array() === $result) {
            throw new InvalidArgumentException(sprintf('The "%s" file is not valid.', $file));
        }

        if (isset($result['parameters']) && is_array($result['parameters'])) {
            $config['parameters'] = array();
            foreach ($result['parameters'] as $key => $value) {
                $config['parameters'][$key] = $value;
            }
        }
    }

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


Question:
// GetAWSCognitoUserPoolGroupWithName retrieves all AWSCognitoUserPoolGroup items from an AWS CloudFormation template
// whose logical ID matches the provided name. Returns an error if not found.

func (t *Template) GetAWSCognitoUserPoolGroupWithName(name string) (*resources.AWSCognitoUserPoolGroup, error) {
	if untyped, ok := t.Resources[name]; ok {
		switch resource := untyped.(type) {
		case *resources.AWSCognitoUserPoolGroup:
			return resource, nil
		}
	}
	return nil, fmt.Errorf("resource %q of type AWSCognitoUserPoolGroup not found", name)
}

func (c *OpenidConfigurationController) Show(ctx *app.ShowOpenidConfigurationContext) error {

	issuer := rest.AbsoluteURL(ctx.RequestData, "", nil)
	authorizationEndpoint := rest.AbsoluteURL(ctx.RequestData, client.AuthorizeAuthorizePath(), nil)
	tokenEndpoint := rest.AbsoluteURL(ctx.RequestData, client.ExchangeTokenPath(), nil)
	userinfoEndpoint := rest.AbsoluteURL(ctx.RequestData, client.ShowUserinfoPath(), nil)
	logoutEndpoint := rest.AbsoluteURL(ctx.RequestData, client.LogoutLogoutPath(), nil)
	jwksURI := rest.AbsoluteURL(ctx.RequestData, client.KeysTokenPath(), nil)

	authOpenIDConfiguration := &app.OpenIDConfiguration{
		// REQUIRED properties
		Issuer:                 &issuer,
		AuthorizationEndpoint:  &authorizationEndpoint,
		TokenEndpoint:          &tokenEndpoint,
		EndSessionEndpoint:     &logoutEndpoint,
		ResponseTypesSupported: []string{"code"},
		JwksURI:                &jwksURI,

		// subject_types_supported REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
		// A Subject Identifier is a locally unique and never reassigned identifier within the Issuer for the End-User, which is intended to be consumed by the Client.
		// http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
		// subject ==  identity
		SubjectTypesSupported: []string{"public"},
		// id_token_signing_alg_values_supported REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT [JWT].
		// The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
		IDTokenSigningAlgValuesSupported: []string{"RS256"},

		// RECOMMENDED properties
		UserinfoEndpoint: &userinfoEndpoint,
		ScopesSupported:  []string{"openid", "offline_access"},
		ClaimsSupported:  []string{"sub", "iss", "auth_time", "name", "given_name", "family_name", "preferred_username", "email"},

		// OPTIONAL properties
		GrantTypesSupported: []string{"authorization_code", "refresh_token", "client_credentials"},
		// client_secret_post for client_credentials grant_type
		// client_secre_jwt for authorizatoin_code grant_type
		TokenEndpointAuthMethodsSupported: []string{"client_secret_post", "client_secret_jwt"},
		// response_modes_supported
	}

	return ctx.OK(authOpenIDConfiguration)
}

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


Question:
Determine the location to map loaded data (e.g., weights)
    for a given target device (e.g. 'cuda').

def get_map_location(target_device, fallback_device='cpu'):

    map_location = torch.device(target_device)

    # The user wants to use CUDA but there is no CUDA device
    # available, thus fall back to CPU.
    if map_location.type == 'cuda' and not torch.cuda.is_available():
        warnings.warn(
            'Requested to load data to CUDA but no CUDA devices '
            'are available. Loading on device "{}" instead.'.format(
                fallback_device,
            ), DeviceWarning)
        map_location = torch.device(fallback_device)
    return map_location

func ResourceLocation(getter ResourceGetter, rt http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
	// Allow ID as "podname" or "podname:port" or "scheme:podname:port".
	// If port is not specified, try to use the first defined port on the pod.
	scheme, name, port, valid := utilnet.SplitSchemeNamePort(id)
	if !valid {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid pod request %q", id))
	}
	// TODO: if port is not a number but a "(container)/(portname)", do a name lookup.

	pod, err := getPod(getter, ctx, name)
	if err != nil {
		return nil, nil, err
	}

	// Try to figure out a port.
	if port == "" {
		for i := range pod.Spec.Containers {
			if len(pod.Spec.Containers[i].Ports) > 0 {
				port = fmt.Sprintf("%d", pod.Spec.Containers[i].Ports[0].ContainerPort)
				break
			}
		}
	}

	if err := proxyutil.IsProxyableIP(pod.Status.PodIP); err != nil {
		return nil, nil, errors.NewBadRequest(err.Error())
	}

	loc := &url.URL{
		Scheme: scheme,
	}
	if port == "" {
		loc.Host = pod.Status.PodIP
	} else {
		loc.Host = net.JoinHostPort(pod.Status.PodIP, port)
	}
	return loc, rt, nil
}

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