Question:
Get city subnational.

@return [[@doctodo return_type:getCitySubnational]] [[@doctodo return_description:getCitySubnational]]

public function getCitySubnational()
    {
        $str = $this->city;
        if (!empty($this->subnational_division)) {
            $str .= ", " . $this->subnational_division;
        }

        return $str;
    }

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:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) INATEnginegetNetwork(request *INATEnginegetNetwork) (*INATEnginegetNetworkResponse, error) {
	response := new(INATEnginegetNetworkResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

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


Question:
@param array $arguments
@param \Closure $renderChildrenClosure
@param RenderingContextInterface $renderingContext

@return string the formatted amount

public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
    {
        preg_match_all(
            '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!',
            $renderChildrenClosure(),
            $matches
        );
        $ret = $matches[0];
        foreach ($ret as &$match) {
            $match = $match === strtoupper($match) ? strtolower($match) : lcfirst($match);
        }
        return implode('-', $ret);
    }

protected function create_navigation(\stdClass $tree) {
        if ($this->firstelement) {
            $html = \html_writer::start_tag('ul', ['class' => 'treeview parent block_tree list', 'id' => 'my-tree']);
            $this->firstelement = false;
        } else {
            $html = \html_writer::start_tag('ul', ['class' => 'parent', 'role' => 'group']);
        }
        foreach ($tree->children as $child) {
            if (isset($child->children)) {
                $html .= \html_writer::start_tag('li', ['class' => 'menu-item', 'role' => 'treeitem', 'aria-expanded' => 'false']);
                $html .= $child->name;
                $html .= $this->create_navigation($child);
            } else {
                $html .= \html_writer::start_tag('li', ['class' => 'item', 'role' => 'treeitem', 'aria-expanded' => 'false']);
                // Normal display.
                if (isset($child->datavar)) {
                    $html .= \html_writer::link('#', $child->name, ['data-var' => $child->datavar]);
                } else {
                    $html .= \html_writer::link($child->url, $child->name, ['target' => '_blank']);
                }
            }
            $html .= \html_writer::end_tag('li');
        }
        $html .= \html_writer::end_tag('ul');
        return $html;
    }

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


Question:
Join a belongs to relationship.

@param BelongsTo $relation

@return mixed

protected function joinBelongsTo(BelongsTo $relation)
    {
        return $this->instance->join(
            $relation->getRelated()->getTable(),
            $relation->getQualifiedOtherKeyName(),
            '=',
            $relation->getQualifiedForeignKey()
        );
    }

private function addWhereForSharing(QueryBuilder $qb, array $subjects, array $sids)
    {
        $where = '';
        $parameters = [];

        foreach ($subjects as $i => $subject) {
            $class = 'subject'.$i.'_class';
            $id = 'subject'.$i.'_id';
            $parameters[$class] = $subject->getType();
            $parameters[$id] = $subject->getIdentifier();
            $where .= '' === $where ? '' : ' OR ';
            $where .= sprintf('(s.subjectClass = :%s AND s.subjectId = :%s)', $class, $id);
        }

        $qb->where($where);

        foreach ($parameters as $key => $value) {
            $qb->setParameter($key, $value);
        }

        return $this->addWhereSecurityIdentitiesForSharing($qb, $sids);
    }

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


Question: Auto Generated Code

def firmware_download_output_cluster_output_rbridge_id(self, **kwargs):

        config = ET.Element("config")
        firmware_download = ET.Element("firmware_download")
        config = firmware_download
        output = ET.SubElement(firmware_download, "output")
        cluster_output = ET.SubElement(output, "cluster-output")
        rbridge_id = ET.SubElement(cluster_output, "rbridge-id")
        rbridge_id.text = kwargs.pop('rbridge_id')

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

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
Check to see if the user table exists and has records.

@return bool

protected function hasUsers()
    {
        try {
            $users = $this->app['users']->getUsers();
            if (empty($users)) {
                return false;
            }

            return true;
        } catch (TableNotFoundException $e) {
            return false;
        }
    }

public static function queryByBaseId( $baseId, $config = [] ) {

		$type	= isset( $config[ 'type' ] ) ? $config[ 'type' ] : self::TYPE_COMMENT;
		$status	= isset( $config[ 'status' ] ) ? $config[ 'status' ] : self::STATUS_APPROVED;

		return self::find()->where( [ 'baseId' => $baseId, 'type' => $type, 'status' => $status ] );
	}

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


Question:
Send the SMTP HELO command.
        Hostname to send for this command defaults to the FQDN of the local
        host.

        :raises SMTPHeloError: on unexpected server response code

async def helo(
        self, hostname: str = None, timeout: DefaultNumType = _default
    ) -> SMTPResponse:

        if hostname is None:
            hostname = self.source_address
        async with self._command_lock:
            response = await self.execute_command(
                b"HELO", hostname.encode("ascii"), timeout=timeout
            )
        self.last_helo_response = response

        if response.code != SMTPStatus.completed:
            raise SMTPHeloError(response.code, response.message)

        return response

public function render($request, Exception $exception)
    {
        $exception = $this->prepareException($exception);

        if ($exception instanceof HttpResponseException) {
            return $exception->getResponse();
        } elseif ($exception instanceof AuthenticationException) {
            return $this->unauthenticated($request, $exception);
        } elseif ($exception instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($exception, $request);
        } elseif ($this->isHttpException($exception) && $this->customErrorHtmlTemplateExists($exception)) {
            return $this->prepareResponse($request, $exception);
        }

        $flattened = FlattenException::create($exception);

        $code = $flattened->getStatusCode();
        $headers = $flattened->getHeaders();
        $response = $this->getContent($exception, $code, $request);

        // If it's already a response, return that.
        if (!$response instanceof BaseResponse) {
            $response = new Response($this->getContent($exception, $code, $request), $code, $headers);
        }

        return $response;
    }

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


Question:
Runs action

@param integer $id id of property group model

@return string
@throws \yii\web\NotFoundHttpException

public function run($id)
    {
        $propertyGroup = PropertyGroup::loadModel(
            $id,
            false,
            true,
            86400,
            new NotFoundHttpException("Property group with specified id not found")
        );

        $model = new Property();
        $model->setScenario('search');
        $params = Yii::$app->request->get();
        $dataProvider = $model->search($propertyGroup->id, $params);

        return $this->render([
            'propertyGroup' => $propertyGroup,
            'dataProvider' => $dataProvider,
            'model' => $model,
            'editPropertyGroupActionId' => $this->editPropertyGroupActionId,
            'listPropertyGroupsActionId' => $this->listPropertyGroupsActionId,
            'editPropertyActionId' => $this->editPropertyActionId,
        ]);
    }

public function create($payment, $paymentId = null)
    {
        if (isset($paymentId)) {
            return $this->client()->put($payment, 'payments/{paymentId}', ['paymentId' => $paymentId]);
        }

        return $this->client()->post($payment, 'payments');
    }

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


Question: Size and position that the window needs to be on the VR display.

def getWindowBounds(self):
        """"""

        fn = self.function_table.getWindowBounds
        pnX = c_int32()
        pnY = c_int32()
        pnWidth = c_uint32()
        pnHeight = c_uint32()
        fn(byref(pnX), byref(pnY), byref(pnWidth), byref(pnHeight))
        return pnX.value, pnY.value, pnWidth.value, pnHeight.value

func (service *VboxPortType) IMediumresize(request *IMediumresize) (*IMediumresizeResponse, error) {
	response := new(IMediumresizeResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

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


Question:
Control update. Should be invoked every frame
@param {number} frameTime Frame time

function (frameTime) {
        var target = this.target;

        var position = this.target.position;
        var xAxis = target.localTransform.x.normalize();
        var zAxis = target.localTransform.z.normalize();

        if (this.verticalMoveLock) {
            zAxis.y = 0;
            zAxis.normalize();
        }

        var speed = this.speed * frameTime / 20;

        if (this._moveForward) {
            // Opposite direction of z
            position.scaleAndAdd(zAxis, -speed);
        }
        if (this._moveBackward) {
            position.scaleAndAdd(zAxis, speed);
        }
        if (this._moveLeft) {
            position.scaleAndAdd(xAxis, -speed / 2);
        }
        if (this._moveRight) {
            position.scaleAndAdd(xAxis, speed / 2);
        }

        target.rotateAround(target.position, this.up, -this._offsetPitch * frameTime * Math.PI / 360);
        var xAxis = target.localTransform.x;
        target.rotateAround(target.position, xAxis, -this._offsetRoll * frameTime * Math.PI / 360);

        this._offsetRoll = this._offsetPitch = 0;
    }

def hardware_custom_profile_kap_custom_profile_bfd_l3_bfd_l3_hello_interval(self, **kwargs):

        config = ET.Element("config")
        hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
        custom_profile = ET.SubElement(hardware, "custom-profile")
        kap_custom_profile = ET.SubElement(custom_profile, "kap-custom-profile")
        name_key = ET.SubElement(kap_custom_profile, "name")
        name_key.text = kwargs.pop('name')
        bfd_l3 = ET.SubElement(kap_custom_profile, "bfd-l3")
        bfd_l3_hello_interval = ET.SubElement(bfd_l3, "bfd_l3_hello_interval")
        bfd_l3_hello_interval.text = kwargs.pop('bfd_l3_hello_interval')

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

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


Question:
// taintnodes walks the tree building a time-series of taint values for each
// agent id.

func (n *Node) taintnodes(all map[int][]TaintVal, tmax int) {
	for len(all[n.AgentId]) < tmax {
		all[n.AgentId] = append(all[n.AgentId], TaintVal{})
	}

	torec := false
	torec = torec || (n.Child1 == nil && n.Child2 == nil)
	torec = torec || (n.Child1 != nil && n.Time != n.Child1.Time)

	if torec {
		prev := all[n.AgentId][n.Time]
		qty := prev.Quantity + n.Quantity
		taintqty := prev.Taint*prev.Quantity + n.taintfrac*n.Quantity
		all[n.AgentId][n.Time] = TaintVal{
			Taint:    taintqty / qty,
			Quantity: qty,
		}

		// fill in blank times between this node and its next child
		if n.Child1 != nil {
			for t := n.Time + 1; t < n.Child1.Time; t++ {
				prev := all[n.AgentId][t]
				qty := prev.Quantity + n.Quantity
				taintqty := prev.Taint*prev.Quantity + n.taintfrac*n.Quantity
				all[n.AgentId][t] = TaintVal{
					Taint:    taintqty / qty,
					Quantity: qty,
				}
			}
		} else if n.Child1 == nil {
			// leaf node taint needs to be forward propogated through all blank times
			for i, prev := range all[n.AgentId][n.Time+1:] {
				t := i + n.Time + 1
				qty := prev.Quantity + n.Quantity
				taintqty := prev.Taint*prev.Quantity + n.taintfrac*n.Quantity
				all[n.AgentId][t] = TaintVal{
					Taint:    taintqty / qty,
					Quantity: qty,
				}
			}
		}
	}

	if n.Child1 != nil {
		n.Child1.taintnodes(all, tmax)
	}
	if n.Child2 != nil {
		n.Child2.taintnodes(all, tmax)
	}
}

def reporter(self):

        # Initialise variables
        combinedrow = ''
        reportdirset = set()
        # Populate a set of all the report directories to use. A standard analysis will only have a single report
        # directory, while pipeline analyses will have as many report directories as there are assembled samples
        for sample in self.metadata:
            # Ignore samples that lack a populated reportdir attribute
            if sample[self.analysistype].reportdir != 'NA':
                make_path(sample[self.analysistype].reportdir)
                # Add to the set - I probably could have used a counter here, but I decided against it
                reportdirset.add(sample[self.analysistype].reportdir)
        # Create a report for each sample from :self.resultprofile
        for sample in self.metadata:
            if sample[self.analysistype].reportdir != 'NA':
                if type(sample[self.analysistype].allelenames) == list:
                    # Populate the header with the appropriate data, including all the genes in the list of targets
                    row = 'Strain,Genus,SequenceType,Matches,{},\n' \
                        .format(','.join(sorted(sample[self.analysistype].allelenames)))
                    # Set the sequence counter to 0. This will be used when a sample has multiple best sequence types.
                    # The name of the sample will not be written on subsequent rows in order to make the report clearer
                    seqcount = 0
                    # Iterate through the best sequence types for the sample (only occurs if update profile is disabled)
                    for seqtype in self.resultprofile[sample.name]:
                        """
                        {
                            "OLF15230-1_2015-SEQ-0783": {
                                "1000004_CFIA": {
                                    "7": {
                                        "dnaE": {
                                            "47": "100.00"
                                        },
                                        "dtdS": {
                                            "19": "100.00"
                                        },
                                        "gyrB": {
                                            "359": "100.00"
                                        },
                                        "pntA": {
                                            "50": "100.00"
                                        },
                                        "pyrC": {
                                            "143": "100.00"
                                        },
                                        "recA": {
                                            "31": "100.00"
                                        },
                                        "tnaA": {
                                            "26": "100.00"
                                        }
                                    }
                                }
                            }
                        }
                        """
                        # Becomes
                        """
                        Strain,SequenceType,Matches,dnaE,gyrB,recA,dtdS,pntA,pyrC,tnaA
                        OLF15230-1_2015-SEQ-0783,1000004_CFIA,7,26 (100.00%),359 (100.00%),31 (100.00%),50 (100.00%),
                            19 (100.00%),47 (100.00%),143 (100.00%)
                        """
                        sample[self.analysistype].sequencetype = seqtype
                        # The number of matches to the profile
                        matches = list(self.resultprofile[sample.name][seqtype].keys())[0]
                        # If this is the first of one or more sequence types, include the sample name
                        if seqcount == 0:
                            row += '{},{},{},{},'.format(sample.name, sample.general.referencegenus, seqtype, matches)
                        # Otherwise, skip the sample name
                        else:
                            row += ',,{},{},'.format(seqtype, matches)
                        # Iterate through all the genes present in the analyses for the sample
                        for gene in sorted(sample[self.analysistype].allelenames):
                            # refallele = self.profiledata[self.analysistype][seqtype][gene]
                            refallele = sample[self.analysistype].profiledata[seqtype][gene]
                            # Set the allele and percent id from the dictionary's keys and values, respectively
                            allele = list(self.resultprofile[sample.name][seqtype][matches][gene].keys())[0]
                            percentid = list(self.resultprofile[sample.name][seqtype][matches][gene].values())[0]
                            if refallele and refallele != allele:
                                if 0 < float(percentid) < 100:
                                    row += '{} ({:.2f}%),'.format(allele, float(percentid))
                                else:
                                    row += '{} ({}),'.format(allele, refallele)
                            else:
                                # Add the allele and % id to the row (only add the percent identity if it is not 100%)
                                if 0 < float(percentid) < 100:
                                    row += '{} ({:.2f}%),'.format(allele, float(percentid))
                                else:
                                    row += '{},'.format(allele)
                            self.referenceprofile[sample.name][gene] = allele
                        # Add a newline
                        row += '\n'
                        # Increment the number of sequence types observed for the sample
                        seqcount += 1
                    combinedrow += row
                    # If the length of the # of report directories is greater than 1 (script is being run as part of
                    # the assembly pipeline) make a report for each sample
                    if self.pipeline:
                        # Open the report
                        with open('{}{}_{}.csv'.format(sample[self.analysistype].reportdir, sample.name,
                                                       self.analysistype), 'w') as report:
                            # Write the row to the report
                            report.write(row)
                dotter()
            # Create the report folder
            make_path(self.reportpath)
            # Create the report containing all the data from all samples
            if self.pipeline:
                with open('{}{}.csv'.format(self.reportpath, self.analysistype), 'w') \
                        as combinedreport:
                    # Write the results to this report
                    combinedreport.write(combinedrow)
            else:
                with open('{}{}_{:}.csv'.format(self.reportpath, self.analysistype, time.strftime("%Y.%m.%d.%H.%M.%S")),
                          'w') as combinedreport:
                    # Write the results to this report
                    combinedreport.write(combinedrow)
            # Remove the raw results csv
            [os.remove(rawresults) for rawresults in glob('{}*rawresults*'.format(self.reportpath))]

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


Question:
Register function

@api

@param string   $name
@param callable $func
@param array    $prototype

public function registerFunction($name, $func, $prototype = null)
    {
        $this->userFunctions[$this->normalizeName($name)] = [$func, $prototype];
    }

void createMethodBody(String classname, ExecutableElement methodElement, List<String> arguments, Writer writer) throws IOException {
		String methodName = getMethodName(methodElement);
		boolean ws = isWebsocketDataService(methodElement);
		String args = stringJoinAndDecorate(arguments, COMMA, new NothingDecorator());
		String keys = computeKeys(methodElement, arguments);
		createReturnOcelotPromiseFactory(classname, methodName, ws, args, keys, writer);
	}

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


Question: // Read reads a block of data from an inner stream and reports progress

func (rbp *requestBodyProgress) Read(p []byte) (n int, err error) {
	n, err = rbp.requestBody.Read(p)
	if err != nil {
		return
	}
	// Invokes the user's callback method to report progress
	position, err := rbp.requestBody.Seek(0, io.SeekCurrent)
	if err != nil {
		panic(err)
	}
	rbp.pr(position)
	return
}

public ByteBuffer getBuffer() {
        assert(isDirect == false);
        assert(buffer.b().hasArray());
        assert(!buffer.b().isDirect());
        buffer.b().flip();
        return buffer.b().asReadOnlyBuffer();
    }

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


Question:
Executes an SQL statement, returning a result set as a Statement object.

@return \Doctrine\DBAL\Driver\Statement

@throws DBALException

public function query()
    {
        $connection = $this->getWrappedConnection();

        $args = func_get_args();

        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($args[0]);
        }

        try {
            $statement = $connection->query(...$args);
        } catch (Throwable $ex) {
            throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $args[0]);
        }

        $statement->setFetchMode($this->defaultFetchMode);

        if ($logger) {
            $logger->stopQuery();
        }

        return $statement;
    }

public function disconnect()
    {
        if ($this->_connection) {
            try{
                $this->_connection->close();
            }catch(\Exception $e){

            }

        }

        $this->_db = $this->_connection = null;
    }

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


Question: Ensures that a value is a SetCell

def coerce(self, value):

        if hasattr(value, 'values') and hasattr(value, 'domain'):
            return value
        elif hasattr(value, '__iter__'):
            # if the values are consistent with the comparison's domains, then
            # copy them, otherwise, make a new domain with the values.
            if all(map(lambda x: x in self.domain, value)):
                return self._stem(self.domain, value)
            else:
                raise CellConstructionFailure("Cannot turn %s into a cell" % (value))
        elif value in self.domain:
            return self._stem(self.domain, [value])
        else:
            raise CellConstructionFailure("Cannot turn %s into a cell" % (value))

function cellref (ref) {
  if (R1C1.test(ref)) {
    return convertR1C1toA1(ref)
  }

  if (A1.test(ref)) {
    return convertA1toR1C1(ref)
  }

  throw new Error(`could not detect cell reference notation for ${ref}`)
}

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


Question: Build all dependencies of a package

def binary(self, name, flag):

        if self.meta.rsl_deps in ["on", "ON"] and "--resolve-off" not in flag:
            sys.setrecursionlimit(10000)
            dependencies = []
            requires = Requires(name, self.repo).get_deps()
            if requires:
                for req in requires:
                    status(0)
                    if req and req not in self.black:
                        dependencies.append(req)
                if dependencies:
                    self.dep_results.append(dependencies)
                    for dep in dependencies:
                        self.binary(dep, flag)
            return self.dep_results
        else:
            return []

func NewPackage(n string) *Env {
	return &Env{
		env:    make(map[string]reflect.Value),
		typ:    make(map[string]reflect.Type),
		parent: nil,
		name:   n,
	}
}

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


Question:
return url that sets the current filter to some value.

@param string $sValue

public function GetAddFilterURL($sValue)
    {
        // @todo: the sorting is lost here (#29269)
        $oActiveListfilter = TdbPkgShopListfilter::GetActiveInstance();
        $aURLData = $oActiveListfilter->GetCurrentFilterAsArray();
        $aURLData[TdbPkgShopListfilterItem::URL_PARAMETER_FILTER_DATA][$this->id] = $sValue;
        $aURLData[TdbPkgShopListfilter::URL_PARAMETER_IS_NEW_REQUEST] = '1';

        return $this->getActivePageService()->getLinkToActivePageRelative($aURLData);
    }

public QueryFilter withPage(int pageNumber, int amountPerPage) {
        parameters.put("page", pageNumber);
        parameters.put("per_page", amountPerPage);
        return this;
    }

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


Question:
// writeStaticData writes the endpoint-specific static data defines to the
// specified writer. This must be kept in sync with loader.ELFSubstitutions().

func (l *linuxDatapath) writeStaticData(fw io.Writer, e datapath.EndpointConfiguration) {
	fmt.Fprint(fw, defineIPv6("LXC_IP", e.IPv6Address()))
	fmt.Fprint(fw, defineIPv4("LXC_IPV4", e.IPv4Address()))

	fmt.Fprint(fw, defineMAC("NODE_MAC", e.GetNodeMAC()))
	fmt.Fprint(fw, defineUint32("LXC_ID", uint32(e.GetID())))

	secID := e.GetIdentity().Uint32()
	fmt.Fprintf(fw, defineUint32("SECLABEL", secID))
	fmt.Fprintf(fw, defineUint32("SECLABEL_NB", byteorder.HostToNetwork(secID).(uint32)))

	epID := uint16(e.GetID())
	fmt.Fprintf(fw, "#define POLICY_MAP %s\n", bpf.LocalMapName(policymap.MapName, epID))
	fmt.Fprintf(fw, "#define CALLS_MAP %s\n", bpf.LocalMapName("cilium_calls_", epID))
	fmt.Fprintf(fw, "#define CONFIG_MAP %s\n", bpf.LocalMapName(bpfconfig.MapNamePrefix, epID))
}

def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_message(self, **kwargs):

        config = ET.Element("config")
        logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
        config = logical_chassis_fwdl_status
        output = ET.SubElement(logical_chassis_fwdl_status, "output")
        cluster_fwdl_entries = ET.SubElement(output, "cluster-fwdl-entries")
        fwdl_entries = ET.SubElement(cluster_fwdl_entries, "fwdl-entries")
        message = ET.SubElement(fwdl_entries, "message")
        message.text = kwargs.pop('message')

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

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


Question:
Bootstraps a data service for the Gerrit REST / HTTP API.

For $instanceConfig documentation see self::getDataService.

@param array $instanceConfig
@return HTTPDataService

protected static function bootstrapHTTPDataService(array $instanceConfig)
    {
        $restClient = static::getHTTPClientInstance($instanceConfig);
        $dataService = new HTTPDataService($restClient, $instanceConfig['Instance']);

        return $dataService;
    }

public static function get($serv = '')
    {
        if ( is_null(static::$serv) || static::$serv !== $serv || is_null(static::$sync) ) {
            static::$serv = $serv;
            static::$sync = true;
            static::$instance = new \Yar_Client($serv);
        }

        return static::$instance;
    }

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


Question:
Get project from URL

@return DNProject

protected function getProject() {
		$projectName = $this->getRequest()->param('Project');
		return DNProject::get()->filter('Name', $projectName)->first();
	}

protected function findInPaths($name, array $paths)
    {
        foreach ($paths as $path) {
            foreach ($this->getPossibleViewFiles($name) as $fileName) {
                $viewPath = $path .DS .$fileName;

                if ($this->files->exists($viewPath)) {
                    return $viewPath;
                }
            }
        }

        throw new \InvalidArgumentException("View [$name] not found.");
    }

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


Question: // NewReader returns a Reader that reads from the specified Rope.

func NewReader(rope Rope) *Reader {
	// Put the leftmost path on the stack.
	var reader Reader
	if rope.node != nil {
		reader.stack = make([]*concat, 0, rope.node.depth())
		reader.pushSubtree(rope.node)
	}
	return &reader
}

public function getIterator()
    {
        $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod();
        foreach ($this->getResponseObject()->$resourcesGetMethod() as $element) {
            yield $element;
        }
    }

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


Question:
use zero initialization for better convergence, because it tends to oputut 0,
    and the label 0 stands for background, which may occupy most size of one image.

def init_from_fcnxs(ctx, fcnxs_symbol, fcnxs_args_from, fcnxs_auxs_from):

    fcnxs_args = fcnxs_args_from.copy()
    fcnxs_auxs = fcnxs_auxs_from.copy()
    for k,v in fcnxs_args.items():
        if(v.context != ctx):
            fcnxs_args[k] = mx.nd.zeros(v.shape, ctx)
            v.copyto(fcnxs_args[k])
    for k,v in fcnxs_auxs.items():
        if(v.context != ctx):
            fcnxs_auxs[k] = mx.nd.zeros(v.shape, ctx)
            v.copyto(fcnxs_auxs[k])
    data_shape=(1,3,500,500)
    arg_names = fcnxs_symbol.list_arguments()
    arg_shapes, _, _ = fcnxs_symbol.infer_shape(data=data_shape)
    rest_params = {}
    deconv_params = {}
    # this is fcn8s init from fcn16s
    if 'score_pool3_weight' in arg_names:
        rest_params = dict([(x[0], mx.nd.zeros(x[1], ctx)) for x in zip(arg_names, arg_shapes)
            if x[0] in ['score_pool3_bias', 'score_pool3_weight']])
        deconv_params = dict([(x[0], x[1]) for x in zip(arg_names, arg_shapes) if x[0] \
            in ["bigscore_weight", 'score4_weight']])
    # this is fcn16s init from fcn32s
    elif 'score_pool4_weight' in arg_names:
        rest_params = dict([(x[0], mx.nd.zeros(x[1], ctx)) for x in zip(arg_names, arg_shapes)
            if x[0] in ['score_pool4_weight', 'score_pool4_bias']])
        deconv_params = dict([(x[0], x[1]) for x in zip(arg_names, arg_shapes) if x[0] \
            in ["bigscore_weight", 'score2_weight']])
    # this is fcn32s init
    else:
        logging.error("you are init the fcn32s model, so you should use init_from_vgg16()")
        sys.exit()
    fcnxs_args.update(rest_params)
    for k, v in deconv_params.items():
        filt = upsample_filt(v[3])
        initw = np.zeros(v)
        initw[range(v[0]), range(v[1]), :, :] = filt  # becareful here is the slice assing
        fcnxs_args[k] = mx.nd.array(initw, ctx)
    return fcnxs_args, fcnxs_auxs

def property_on_depth_profile(lat, lon, depths, quantity_ID="DENSITY"):

    lon1 = np.array((lon,))
    lat1 = np.array((lat,))
    depths1 = np.array(depths)

    nlayers = len(l1_layer_decode)
    point_properties = np.empty_like(depths)

    layer_depths     = np.empty((nlayers))
    layer_properties = np.ones((nlayers+1)) * -99999.0  # if the point is not found it will end up in the overshoot !

    # should assert here that the three arrays are equal size

    for i in range(0, nlayers, 1 ):
        layer_depths[i], err = _interpolator.interpolate( np.radians(lon1), np.radians(lat1),
                                      _litho_data[i,l1_data_decode["DEPTH"]], order=1)
        layer_properties[i], err = _interpolator.interpolate( np.radians(lon1), np.radians(lat1),
                                      _litho_data[i,l1_data_decode[quantity_ID]], order=1)

    A = -layer_depths
    B = -depths1 * 1000.0
    C = np.searchsorted(A, B)

    point_properties = np.empty_like(depths)
    for i,layer in enumerate(C):

        point_properties[i] = layer_properties[layer]

    return C, point_properties

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


Question: Returns an java object read from the specified ResultSet column.

public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)
            throws SQLException
    {
        return getObjectFromColumn(rs, null, jdbcType, null, columnId);
    }

public static void setOutput(JobConf job, String tableName, String... fieldNames) {
    job.setOutputFormat(DBOutputFormat.class);
    job.setReduceSpeculativeExecution(false);

    DBConfiguration dbConf = new DBConfiguration(job);

    dbConf.setOutputTableName(tableName);
    dbConf.setOutputFieldNames(fieldNames);
  }

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


Question:
Get title

@return string

protected function getTitle()
    {
        $console = $this->console;

        $title = sprintf(
            "%s\n%s\n%s\n",
            str_repeat(
                '-',
                $console->getWidth()
            ),
            "Humus PHPUnit Module for Zend Framework 2\n"
            . "Author: Sascha-Oliver Prolic",
            str_repeat(
                '-',
                $console->getWidth()
            )
        );

        return $console->colorize($title, ColorInterface::RED);
    }

public ResultResponseUtil status(IReturnCode iReturnCode) {
        this.setCode(iReturnCode.getCode());
        this.setMsg(iReturnCode.getMsg());
        return this;
    }

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


Question:
@param array     $input
@param Message[] $messages

@return void

protected function validate(array $input, array &$messages)
    {
        if (!call_user_func_array($this->validationCallback, [$input, &$messages])) {
            if ($this->messageId) {
                $messages[] = new Message($this->messageId, $this->messageParameters);
            }
        }
    }

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

            $response = curl_exec($ch);

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

                throw  $e;
            }

            curl_close($ch);

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

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


Question:
// GetTopMenus returns the list of additional top menu entries.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-top-menus

func (s *ConfigService) GetTopMenus() (*[]TopMenuEntryInfo, *Response, error) {
	u := "config/server/top-menus"

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	v := new([]TopMenuEntryInfo)
	resp, err := s.client.Do(req, v)
	if err != nil {
		return nil, resp, err
	}

	return v, resp, err
}

def get_branches(self, local=True, remote_branches=True):
        """"""

        if not self.repo.remotes:
            remote_branches = False

        branches = []

        if remote_branches:

            # Remote refs.
            try:
                for b in self.remote.refs:
                    name = '/'.join(b.name.split('/')[1:])

                    if name not in legit_settings.forbidden_branches:
                        branches.append(Branch(name, is_published=True))
            except (IndexError, AssertionError):
                pass

        if local:

            # Local refs.
            for b in [h.name for h in self.repo.heads]:

                if (not remote_branches) or (b not in [br.name for br in branches]):
                    if b not in legit_settings.forbidden_branches:
                        branches.append(Branch(b, is_published=False))

        return sorted(branches, key=attrgetter('name'))

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


Question:
@param string $pattern

@throws ViewException
@return array

public function getPrerequisites(string $pattern = ViewInterface::pattern): array {

		// by default, the $pattern for this method matches the one
		// for the applyTemplate() method above, and both match the
		// public constant from the ViewInterface.  you can change the
		// pattern, but they'd better be the same, or you'll get funky
		// results.

		preg_match_all($pattern, $this->content, $matches);

		// the $matches array should have two indices.  the first is the
		// actual matched text which, by default, includes the dollar sign
		// that identifies template variables.  but, the second index is
		// the parenthetical match, which is the word following the dollar
		// sign.  so, all we want to do is send back that array but without
		// any duplicates as follows.

		return array_unique($matches[1]);
	}

public function parseTrace(\Imi\Log\Record $record)
    {
        $result = [];
        $trace = $record->getTrace();
        if($this->traceMinimum)
        {
            $trace = App::getBean(TraceMinimum::class)->parse($trace);
        }
        foreach($trace as $index => $vars)
        {
            $vars['call'] = $this->getTraceCall($vars);
            $vars['index'] = $index;
            $line = $this->traceFormat;
            foreach($vars as $name => $value)
            {
                if(is_scalar($value))
                {
                    $line = str_replace('{' . $name . '}', (string)$value, $line);
                }
            }
            $result[] = $line;
        }
        return implode(PHP_EOL, $result);
    }

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


Question:
Find a single row by ID.

@param mixed $id

@return array|null

private function findById($id, bool $includeData = true) : ?array
    {
        [$idField] = $fields = $this->getFields();

        if (! $includeData) {
            $key = array_search(static::DATA_FIELD, $fields);
            unset($fields[$key]);
        }

        $statement = $this->sqlite->prepare(sprintf(
            'SELECT %s FROM %s WHERE %s = :id LIMIT 1',
            implode(',', $fields),
            $this->table,
            $idField
        ));

        $statement->bindValue(':id', $id, SQLITE3_TEXT);

        $item = $statement->execute()->fetchArray(SQLITE3_ASSOC);

        if ($item === false) {
            return null;
        }

        if ($this->isExpired($item)) {
            $this->doDelete($id);

            return null;
        }

        return $item;
    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

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


Question:
// BasePath sets the internal path provided to handlers requiring
// a base path for http calls. This is useful for hosted solutions
// that need to provided absolute paths to assets.

func BasePath(basePath string) option {
	return func(c *sass) error {
		c.httpPath = basePath
		// FIXME: remove from context
		c.ctx.HTTPPath = basePath
		return nil
	}
}

public function findAsset($url)
    {
        if (empty($url)) {
            return false;
        }

        $this->asset = $this->processUrl($url);

        if ($this->asset === false) {
            return false;
        }

        // check main assets dir
        $mainAsset = $this->findMainAsset(
            $this->docRoot . DS . $this->assetDir . DS . $this->asset['asset']
        );
        if ($mainAsset !== false) {
            return $mainAsset;
        }

        // check the set theme
        $themeAsset = $this->findThemeAsset(
            $this->asset['folder'],
            $this->assetDir . DS . $this->asset['asset']
        );
        if ($themeAsset !== false) {
            return $themeAsset;
        }

        // get the last "fallback" directory
        return $this->findFallbackAsset(
            $this->assetDir . DS . $this->asset['asset'],
            $this->Folder
        );
    }

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


Question: // UpdateDisks mocks base method

func (m *MockInstance) UpdateDisks(arg0 manifest.Manifest, arg1 ui.Stage) ([]disk.Disk, error) {
	ret := m.ctrl.Call(m, "UpdateDisks", arg0, arg1)
	ret0, _ := ret[0].([]disk.Disk)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

public static disk_adapter[] get(nitro_service client) throws Exception
	{
		disk_adapter resource = new disk_adapter();
		resource.validate("get");
		return (disk_adapter[]) resource.get_resources(client);
	}

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


Question:
one-dimensional arrays having shape [N],
    row and column matrices having shape [1 N] and
    [N 1] correspondingly, and their generalizations
    having shape [1 1 ... N ... 1 1 1].
    Scalars have shape [1 1 ... 1].
    Empty arrays dont count

def isvector_or_scalar(a):

    try:
        return a.size and a.ndim-a.shape.count(1) <= 1
    except:
        return False

def load_scalars(filename, strict_type_checks=True):

    # Parse the scalar definitions from the YAML file.
    scalars = None
    try:
        with open(filename, 'r') as f:
            scalars = yaml.safe_load(f)
    except IOError as e:
        raise ParserError('Error opening ' + filename + ': ' + e.message)
    except ValueError as e:
        raise ParserError('Error parsing scalars in {}: {}'
                          '.\nSee: {}'.format(filename, e.message, BASE_DOC_URL))

    scalar_list = []

    # Scalars are defined in a fixed two-level hierarchy within the definition file.
    # The first level contains the category name, while the second level contains the
    # probe name (e.g. "category.name: probe: ...").
    for category_name in scalars:
        category = scalars[category_name]

        # Make sure that the category has at least one probe in it.
        if not category or len(category) == 0:
            raise ParserError('Category "{}" must have at least one probe in it' +
                              '.\nSee: {}'.format(category_name, BASE_DOC_URL))

        for probe_name in category:
            # We found a scalar type. Go ahead and parse it.
            scalar_info = category[probe_name]
            scalar_list.append(
                ScalarType(category_name, probe_name, scalar_info, strict_type_checks))

    return scalar_list

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


Question:
短文本相似度接口
短文本相似度接口用来判断两个文本的相似度得分。

@param text1 - 待比较文本1（GBK编码），最大512字节*
@param text2 - 待比较文本2（GBK编码），最大512字节
@param options - 可选参数对象，key: value都为string类型
options - options列表:
model 默认为"BOW"，可选"BOW"、"CNN"与"GRNN"
@return JSONObject

public JSONObject simnet(String text1, String text2, HashMap<String, Object> options) {
        AipRequest request = new AipRequest();
        preOperation(request);

        request.addBody("text_1", text1);

        request.addBody("text_2", text2);

        if (options != null) {
            request.addBody(options);
        }
        request.setUri(NlpConsts.SIMNET);
        request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
        request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
        request.setBodyFormat(EBodyFormat.RAW_JSON);
        postOperation(request);
        return requestServer(request);
    }

def post_file(api_method, file, parameters = {})
      parameters.merge!({"token" => @token})

      body = {}
      body.merge!({:method => api_method})
      body.merge!({:params => parameters})

      # Brightcove requires that the JSON-RPC call absolutely
      # be the first part of a multi-part POST like create_video.
      if RUBY_VERSION >= '1.9'
        payload = {}
      else
        payload = OrderedHash.new
      end

      payload[:json] = body.to_json
      payload[:file] = File.new(file, 'rb')

      execution_payload = {
        :method => :post,
        :url => @write_api_url,
        :payload => payload,
        :content_type => :json,
        :accept => :json,
        :multipart => true
      }

      execution_payload[:timeout] = @timeout if @timeout
      execution_payload[:open_timeout] = @open_timeout if @open_timeout

      response = RestClient::Request.execute(execution_payload)

      JSON.parse(response)
    end

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


Question:
Méthode pour contrôler que l'utilisateur doit ou ne doit pas changer son mot de passe.

Si l'utilisateur doit changer son mot de passe, on le redirige vers la page qui gère ça.

@return  void

protected function checkUserRequireReset($controller) {

        $user = $this->getContainer()->get('user')->load();

        if ($user->requireReset) {

            /*
             * Par défaut, c'est la page d'édition du profil qui est utilisée.
             * Cette page permet de changer plus que le mot de passe et peut ne pas être le comportement désiré.
             * On peut surcharger la page qui gère la remise à zero en changeant la configuration.
             */
            $classname = $this->get('controller_prefix') . $this->get('reset_password.controller');

            if ($classname !== null && !($controller instanceof $classname)) {

                $text = $this->getContainer()->get('language')->getText();

                // On redirige vers la page.
                $this->enqueueMessage($text->translate('APP_GLOBAL_PASSWORD_RESET_REQUIRED'), 'notice');
                $this->redirect("/".$this->get('reset_password.uri'));

            }

        }
    }

public function save(ServerRequestInterface $request): ResponseInterface
    {
        $username  = $request->getParsedBody()['username'];
        $real_name = $request->getParsedBody()['real_name'];
        $email     = $request->getParsedBody()['email'];
        $password  = $request->getParsedBody()['password'];

        $errors = false;
        if ($this->user_service->findByUserName($username)) {
            FlashMessages::addMessage(I18N::translate('Duplicate username. A user with that username already exists. Please choose another username.'));
            $errors = true;
        }

        if ($this->user_service->findByEmail($email)) {
            FlashMessages::addMessage(I18N::translate('Duplicate email address. A user with that email already exists.'));
            $errors = true;
        }

        if ($errors) {
            $url = route('admin-users-create', [
                'email'     => $email,
                'real_name' => $real_name,
                'username'  => $username,
            ]);

            return redirect($url);
        }

        $new_user = $this->user_service->create($username, $real_name, $email, $password)
            ->setPreference('verified', '1')
            ->setPreference('language', WT_LOCALE)
            ->setPreference('timezone', Site::getPreference('TIMEZONE'))
            ->setPreference('reg_timestamp', date('U'))
            ->setPreference('sessiontime', '0');

        Log::addAuthenticationLog('User ->' . $username . '<- created');

        $url = route('admin-users-edit', [
            'user_id' => $new_user->id(),
        ]);

        return redirect($url);
    }

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


Question:
Given a bunch of TimePeriods, return a TimePeriod that most closely
        contains them.

def get_containing_period(cls, *periods):
        """"""

        if any(not isinstance(period, TimePeriod) for period in periods):
            raise TypeError("periods must all be TimePeriods: {}".format(periods))

        latest = datetime.datetime.min
        earliest = datetime.datetime.max

        for period in periods:
            # the best we can do to conain None is None!
            if period._latest is None:
                latest = None
            elif latest is not None and period._latest > latest:
                latest = period._latest

            if period._earliest is None:
                earliest = None
            elif earliest is not None and period._earliest < earliest:
                earliest = period._earliest

        return TimePeriod(earliest, latest)

public static <T extends ImageBase<T>, II extends ImageGray<II>>
	DescribeRegionPoint<T,BrightFeature> surfColorStable(ConfigSurfDescribe.Stability config, ImageType<T> imageType) {

		Class bandType = imageType.getImageClass();
		Class<II> integralType = GIntegralImageOps.getIntegralType(bandType);

		DescribePointSurf<II> alg = FactoryDescribePointAlgs.surfStability( config, integralType);

		if( imageType.getFamily() == ImageType.Family.PLANAR) {
			DescribePointSurfPlanar<II> color = FactoryDescribePointAlgs.surfColor( alg,imageType.getNumBands());

			return new SurfPlanar_to_DescribeRegionPoint(color,bandType,integralType);
		} else {
			throw new IllegalArgumentException("Unknown image type");
		}
	}

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


Question:
Read the information out of the given JSON object to fill
the values of the document.<p>

@param json the JSON object with the information about this document
@param rootPath the current path the home division

public void fromJSON(JSONObject json, String rootPath) {

        try {
            // language versions
            if (json.has(JSON_LANGUAGES)) {
                JSONArray jsonLanguages = json.getJSONArray(JSON_LANGUAGES);
                for (int i = 0; i < jsonLanguages.length(); i++) {
                    JSONObject jsonLang = (JSONObject)jsonLanguages.get(i);

                    CmsDocumentDependency lang = new CmsDocumentDependency(null, jsonLang.getString(JSON_PATH));
                    lang.fromJSON(jsonLang, rootPath);
                    addVariant(lang);
                }
            }

            // attachments
            if (json.has(JSON_ATTACHMENTS)) {
                JSONArray jsonAttachments = json.getJSONArray(JSON_ATTACHMENTS);
                for (int i = 0; i < jsonAttachments.length(); i++) {
                    try {
                        JSONObject jsonAttachment = (JSONObject)jsonAttachments.get(i);

                        CmsDocumentDependency att = new CmsDocumentDependency(
                            null,
                            jsonAttachment.getString(JSON_PATH));
                        att.fromJSON(jsonAttachment, rootPath);

                        // language versions of attachment
                        if (jsonAttachment.has(JSON_LANGUAGES)) {
                            JSONArray jsonAttLanguages = jsonAttachment.getJSONArray(JSON_LANGUAGES);
                            for (int j = 0; j < jsonAttLanguages.length(); j++) {
                                JSONObject jsonAttLanguage = (JSONObject)jsonAttLanguages.get(j);

                                CmsDocumentDependency attLang = new CmsDocumentDependency(
                                    null,
                                    jsonAttLanguage.getString(JSON_PATH));
                                attLang.fromJSON(jsonAttLanguage, rootPath);
                                att.addVariant(attLang);
                            }
                        }
                        addAttachment(att);
                    } catch (Exception e) {
                        LOG.error(e);
                    }
                }
            }
        } catch (Exception ex) {
            if (LOG.isErrorEnabled()) {
                LOG.error(ex.getLocalizedMessage(), ex);
            }
        }
    }

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:
Save this file.

        :param filename: the file to which to save the .sav file
        :type filename: str
        :param callback: a progress callback function
        :type callback: function

def save(self, filename, callback=_noop_callback):

        with open(filename, 'wb') as fp:
            self._save(fp, callback)

def _wrap_callback_parse_time_info(subscription, on_data, message):

    if message.type == message.REPLY:
        time_response = web_pb2.TimeSubscriptionResponse()
        time_response.ParseFromString(message.reply.data)
        time = parse_isostring(time_response.timeInfo.currentTimeUTC)
        #pylint: disable=protected-access
        subscription._process(time)
        if on_data:
            on_data(time)
    elif message.type == message.DATA:
        if message.data.type == yamcs_pb2.TIME_INFO:
            time_message = getattr(message.data, 'timeInfo')
            time = parse_isostring(time_message.currentTimeUTC)
            #pylint: disable=protected-access
            subscription._process(time)
            if on_data:
                on_data(time)

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


Question:
Remove from list the last object being equal to value

@param list Array of objects comparable to value
@param value
@return {*} Array of deleted item or false

function removeValueFromList(list, value) {
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i] == value) {
            return list.splice(i, 1); // remove from array
        }
    }
    return false;
}

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

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


Question:
Try to get type of a value

@param mixed $value A value needed to guess type

@return string Possible type of a value

static function guessType($value)
    {
        $map = array(
            "float"=>"number",
            "double"=>"number",
            "int"=>"number",
            "integer"=>"number",
            "bool"=>"number",
            "numeric"=>"number",
            "string"=>"string",
        );

        $type = strtolower(gettype($value));
        foreach ($map as $key=>$value) {
            if (strpos($type, $key)!==false) {
                return $value;
            }
        }
        return "unknown";
    }

def install_money_getter attribute, options={}

      define_method :"#{attribute}_with_exchange_typecasting" do
        currency = evaluate_money_option(options[:currency]) if options[:currency]

        test_for_currency_error(currency, attribute)

        time     = evaluate_money_option(options[:at]) if options[:at]

        if value = send(:"#{attribute}_without_exchange_typecasting")
          Exchange::Money.new(value) do |c|
            c.currency = currency
            c.time     = time if time
          end
        end
      end
      exchange_typecasting_alias_method_chain attribute

    end

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


Question: Analogous to :any:`sqlite3.Cursor.fetchmany`

def fetchmany(self, *args, **kwargs):
        """"""

        with self:
            return self._cursor.fetchmany(*args, **kwargs)

func (fmd *FakeMysqlDaemon) CheckSuperQueryList() error {
	if fmd.ExpectedExecuteSuperQueryCurrent != len(fmd.ExpectedExecuteSuperQueryList) {
		return fmt.Errorf("SuperQueryList wasn't consumed, saw %v queries, was expecting %v", fmd.ExpectedExecuteSuperQueryCurrent, len(fmd.ExpectedExecuteSuperQueryList))
	}
	return nil
}

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


Question: // Watch a single key for modifications

func (s *MockStore) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error) {
	return nil, ErrNotImplemented
}

func (meta MetaData) Update(other MetaData) {
	for name, tab := range other {

		if meta[name] == nil {
			meta[name] = make(map[string]interface{})
		}

		for key, value := range tab {
			meta[name][key] = value
		}
	}
}

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


Question:
If the given uuid is null, this returns null, otherwise a JobMasterId that
corresponds to the UUID, via {@link #JobMasterId(UUID)}.

public static JobMasterId fromUuidOrNull(@Nullable UUID uuid) {
		return  uuid == null ? null : new JobMasterId(uuid);
	}

public function build(ResultSpec $result): string
    {
        $response = [];
        $units = $result->getResults();

        foreach ($units as $unit) {
            /** @var AbstractResult $unit */
            if ($unit instanceof Result) {
                /** @var Result $unit */
                $response[] = [
                    'jsonrpc' => '2.0',
                    'result' => $this->preBuild($unit->getResult()),
                    'id'     => $unit->getId()
                ];
            } elseif ($unit instanceof Error) {
                /** @var Error $unit */
                $baseException = $unit->getBaseException();
                $response[] = [
                    'jsonrpc' => '2.0',
                    'error' => [
                        'code'    => $baseException->getJsonRpcCode(),
                        'message' => $this->getErrorMessage($baseException->getJsonRpcCode()),
                        'data'    => $baseException->getJsonRpcData()
                    ],
                    'id' => $unit->getId()
                ];
            }
        }

        if (empty($response)) {
            return '';
        }

        if ($result->isSingleResult()) {
            return json_encode($response[0]);
        }

        return json_encode($response);
    }

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


Question: Set character set of this document.

def characterSet(self, charset: str) -> None:
        """"""
        charset_node = self._find_charset_node() or Meta(parent=self.head)
        charset_node.setAttribute('charset', charset)

def type_string text, options={}
      shift_key_down = nil

      text.each_char do |char|
        key_to_press = KEY_PRESS_CHARS[char]
        unless key_to_press.nil?
          key_press key_to_press
        else
          key_needs_shift = SHIFTED_CHARS.include? char

          if shift_key_down.nil? || shift_key_down != key_needs_shift
            if key_needs_shift
              key_down :shift
            else
              key_up :shift
            end
          end

          type char
          shift_key_down = key_needs_shift
        end
      end
      wait options
    end

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


Question: Recursively reading the categories

protected function getCategoryLevel($parentCategoryId, \Category $parentCategory=null, \DmsLoaderParams $params)
  {
    $arrCategories = array();
    $objCategory = $this->Database->prepare("SELECT * FROM tl_dms_categories WHERE pid = ? ORDER BY sorting")
                    ->execute($parentCategoryId);

    $category = null;
    while ($objCategory->next())
    {
      $category = $this->buildCategory($objCategory);
      $category->parentCategory = $parentCategory;
      $category->subCategories = $this->getCategoryLevel($category->id, $category, $params);
      if ($params->loadAccessRights)
      {
        $category->accessRights = $this->getAccessRights($category, $params);
      }
      if ($params->loadDocuments)
      {
        $category->documents = $this->getDocuments($category, $params);
      }
      $arrCategories[$category->id] = $category;
    }

    return $arrCategories;
  }

func NewConcat(Variable node.Node, Expression node.Node) *Concat {
	return &Concat{
		FreeFloating: nil,
		Left:         Variable,
		Right:        Expression,
	}
}

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


Question:
Adds a GET route to the collection.

@param string $pattern
@param string $handler
@param array  $requirements
@param array  $defaults

@return void

public function get($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('GET', $pattern, $handler, $requirements, $defaults);
    }

public function formatParameters($parameters)
    {
        $parameters = Arr::wrap($parameters);

        foreach ($parameters as $key => $parameter) {
            if ($parameter instanceof UrlRoutable) {
                $parameters[$key] = $parameter->getRouteKey();
            }
        }

        return $parameters;
    }

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


Question: Helper function to format results in coGroupByKeyTuple.

public static String formatCoGbkResults(
      String name, Iterable<String> emails, Iterable<String> phones) {

    List<String> emailsList = new ArrayList<>();
    for (String elem : emails) {
      emailsList.add("'" + elem + "'");
    }
    Collections.sort(emailsList);
    String emailsStr = "[" + String.join(", ", emailsList) + "]";

    List<String> phonesList = new ArrayList<>();
    for (String elem : phones) {
      phonesList.add("'" + elem + "'");
    }
    Collections.sort(phonesList);
    String phonesStr = "[" + String.join(", ", phonesList) + "]";

    return name + "; " + emailsStr + "; " + phonesStr;
  }

def pretty_print(rows, keyword, domain):

    if isinstance(rows, dict):
        pretty_print_domain(rows, keyword, domain)
    elif isinstance(rows, list):
        pretty_print_zones(rows)

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


Question: Method to get current optimizer's parameter value

def get_param(self):

        cycle_progress = self.event_index / self.cycle_size
        return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress))

protected String[] getParameterNameQualifiers() {
        String[] nameQualifiersCopy = new String[_nameQualifiers.length];
        System.arraycopy(_nameQualifiers, 0, nameQualifiersCopy, 0, _nameQualifiers.length);
        return nameQualifiersCopy;
    }

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


Question:
Compare a generated source distribution with list of files in a VCS.

    Returns True if the manifest is fine.

def check_manifest(source_tree='.', create=False, update=False,
                   python=sys.executable):

    all_ok = True
    if os.path.sep in python:
        python = os.path.abspath(python)
    with cd(source_tree):
        if not is_package():
            raise Failure('This is not a Python project (no setup.py).')
        read_config()
        read_manifest()
        info_begin("listing source files under version control")
        all_source_files = sorted(get_vcs_files())
        source_files = strip_sdist_extras(all_source_files)
        info_continue(": %d files and directories" % len(source_files))
        if not all_source_files:
            raise Failure('There are no files added to version control!')
        info_begin("building an sdist")
        with mkdtemp('-sdist') as tempdir:
            run([python, 'setup.py', 'sdist', '-d', tempdir])
            sdist_filename = get_one_file_in(tempdir)
            info_continue(": %s" % os.path.basename(sdist_filename))
            sdist_files = sorted(normalize_names(strip_sdist_extras(
                strip_toplevel_name(get_archive_file_list(sdist_filename)))))
            info_continue(": %d files and directories" % len(sdist_files))
            version = extract_version_from_filename(sdist_filename)
        existing_source_files = list(filter(os.path.exists, all_source_files))
        missing_source_files = sorted(set(all_source_files) - set(existing_source_files))
        if missing_source_files:
            warning("some files listed as being under source control are missing:\n%s"
                    % format_list(missing_source_files))
        info_begin("copying source files to a temporary directory")
        with mkdtemp('-sources') as tempsourcedir:
            copy_files(existing_source_files, tempsourcedir)
            if os.path.exists('MANIFEST.in') and 'MANIFEST.in' not in source_files:
                # See https://github.com/mgedmin/check-manifest/issues/7
                # if do this, we will emit a warning about MANIFEST.in not
                # being in source control, if we don't do this, the user
                # gets confused about their new manifest rules being
                # ignored.
                copy_files(['MANIFEST.in'], tempsourcedir)
            if 'setup.py' not in source_files:
                # See https://github.com/mgedmin/check-manifest/issues/46
                # if do this, we will emit a warning about setup.py not
                # being in source control, if we don't do this, the user
                # gets a scary error
                copy_files(['setup.py'], tempsourcedir)
            info_begin("building a clean sdist")
            with cd(tempsourcedir):
                with mkdtemp('-sdist') as tempdir:
                    os.environ['SETUPTOOLS_SCM_PRETEND_VERSION'] = version
                    run([python, 'setup.py', 'sdist', '-d', tempdir])
                    sdist_filename = get_one_file_in(tempdir)
                    info_continue(": %s" % os.path.basename(sdist_filename))
                    clean_sdist_files = sorted(normalize_names(strip_sdist_extras(
                        strip_toplevel_name(get_archive_file_list(sdist_filename)))))
                    info_continue(": %d files and directories" % len(clean_sdist_files))
        missing_from_manifest = set(source_files) - set(clean_sdist_files)
        missing_from_VCS = set(sdist_files + clean_sdist_files) - set(source_files)
        if not missing_from_manifest and not missing_from_VCS:
            info("lists of files in version control and sdist match")
        else:
            error("lists of files in version control and sdist do not match!\n%s"
                  % format_missing(missing_from_VCS, missing_from_manifest,
                                   "VCS", "sdist"))
            suggestions, unknowns = find_suggestions(missing_from_manifest)
            user_asked_for_help = update or (create and not
                                                os.path.exists('MANIFEST.in'))
            if 'MANIFEST.in' not in existing_source_files:
                if suggestions and not user_asked_for_help:
                    info("no MANIFEST.in found; you can run 'check-manifest -c' to create one")
                else:
                    info("no MANIFEST.in found")
            if suggestions:
                info("suggested MANIFEST.in rules:\n%s"
                     % format_list(suggestions))
                if user_asked_for_help:
                    existed = os.path.exists('MANIFEST.in')
                    with open('MANIFEST.in', 'a') as f:
                        if not existed:
                            info("creating MANIFEST.in")
                        else:
                            info("updating MANIFEST.in")
                            f.write('\n# added by check_manifest.py\n')
                        f.write('\n'.join(suggestions) + '\n')
                    if unknowns:
                        info("don't know how to come up with rules matching\n%s"
                             % format_list(unknowns))
            elif user_asked_for_help:
                info("don't know how to come up with rules"
                     " matching any of the files, sorry!")
            all_ok = False
        bad_ideas = find_bad_ideas(all_source_files)
        filtered_bad_ideas = [bad_idea for bad_idea in bad_ideas
                              if not file_matches(bad_idea, IGNORE_BAD_IDEAS)]
        if filtered_bad_ideas:
            warning("you have %s in source control!\nthat's a bad idea:"
                    " auto-generated files should not be versioned"
                    % filtered_bad_ideas[0])
            if len(filtered_bad_ideas) > 1:
                warning("this also applies to the following:\n%s"
                        % format_list(filtered_bad_ideas[1:]))
            all_ok = False
    return all_ok

def ensure():

        LOGGER.debug('checking repository')
        if not os.path.exists('.git'):
            LOGGER.error('This command is meant to be ran in a Git repository.')
            sys.exit(-1)
        LOGGER.debug('repository OK')

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


Question: Return cached class write methods to avoid each time use reflect

public static Map<String, Method> getClassWriteMethods(Class<?> clazz) {
		Map<String, Method> writeMethods = classWriteMethods.get(clazz);
		if (writeMethods == null) {
			cacheReadWriteMethodsAndBoxField(clazz);
			return classWriteMethods.get(clazz);
		} else
			return writeMethods;
	}

public static <T> T readKryo(File file) {
    try {
      byte[] bytes = CompressionUtil.decodeBZRaw(Files.readAllBytes(file.toPath()));
      Input input = new Input(buffer.get(), 0, bytes.length);
      return (T) new KryoReflectionFactorySupport().readClassAndObject(input);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

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


Question:
@param \PhpSpec\Loader\Suite $suite
@param string                $locator
@param integer|null          $line

@return Suite

public function load(Suite $suite,$locator, $line = null)
    {
        foreach ($this->manager->locateResources($locator) as $resource) {
            $this->importResource($suite,$resource,$line);
        }
    }

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:
// Delete ensures that the provided serviceName is deleted.
// Failing to delete a non-existent service is considered a success.

func Delete(serviceName string, logger *logrus.Logger) error {
	session := spartaAWS.NewSession(logger)
	awsCloudFormation := cloudformation.New(session)

	exists, err := spartaCF.StackExists(serviceName, session, logger)
	if nil != err {
		return err
	}
	logger.WithFields(logrus.Fields{
		"Exists": exists,
		"Name":   serviceName,
	}).Info("Stack existence check")

	if exists {

		params := &cloudformation.DeleteStackInput{
			StackName: aws.String(serviceName),
		}
		resp, err := awsCloudFormation.DeleteStack(params)
		if nil != resp {
			logger.WithFields(logrus.Fields{
				"Response": resp,
			}).Info("Delete request submitted")
		}
		return err
	}
	logger.Info("Stack does not exist")
	return nil
}

func NewDashboardHandler(mappingService platform.UserResourceMappingService, labelService platform.LabelService, userService platform.UserService) *DashboardHandler {
	h := &DashboardHandler{
		Router:                     NewRouter(),
		Logger:                     zap.NewNop(),
		UserResourceMappingService: mappingService,
		LabelService:               labelService,
		UserService:                userService,
	}

	h.HandlerFunc("POST", dashboardsPath, h.handlePostDashboard)
	h.HandlerFunc("GET", dashboardsPath, h.handleGetDashboards)
	h.HandlerFunc("GET", dashboardsIDPath, h.handleGetDashboard)
	h.HandlerFunc("GET", dashboardsIDLogPath, h.handleGetDashboardLog)
	h.HandlerFunc("DELETE", dashboardsIDPath, h.handleDeleteDashboard)
	h.HandlerFunc("PATCH", dashboardsIDPath, h.handlePatchDashboard)

	h.HandlerFunc("PUT", dashboardsIDCellsPath, h.handlePutDashboardCells)
	h.HandlerFunc("POST", dashboardsIDCellsPath, h.handlePostDashboardCell)
	h.HandlerFunc("DELETE", dashboardsIDCellsIDPath, h.handleDeleteDashboardCell)
	h.HandlerFunc("PATCH", dashboardsIDCellsIDPath, h.handlePatchDashboardCell)

	h.HandlerFunc("GET", dashboardsIDCellsIDViewPath, h.handleGetDashboardCellView)
	h.HandlerFunc("PATCH", dashboardsIDCellsIDViewPath, h.handlePatchDashboardCellView)

	h.HandlerFunc("POST", dashboardsIDMembersPath, newPostMemberHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Member))
	h.HandlerFunc("GET", dashboardsIDMembersPath, newGetMembersHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Member))
	h.HandlerFunc("DELETE", dashboardsIDMembersIDPath, newDeleteMemberHandler(h.UserResourceMappingService, platform.Member))

	h.HandlerFunc("POST", dashboardsIDOwnersPath, newPostMemberHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Owner))
	h.HandlerFunc("GET", dashboardsIDOwnersPath, newGetMembersHandler(h.UserResourceMappingService, h.UserService, platform.DashboardsResource, platform.Owner))
	h.HandlerFunc("DELETE", dashboardsIDOwnersIDPath, newDeleteMemberHandler(h.UserResourceMappingService, platform.Owner))

	h.HandlerFunc("GET", dashboardsIDLabelsPath, newGetLabelsHandler(h.LabelService))
	h.HandlerFunc("POST", dashboardsIDLabelsPath, newPostLabelHandler(h.LabelService))
	h.HandlerFunc("DELETE", dashboardsIDLabelsNamePath, newDeleteLabelHandler(h.LabelService))
	h.HandlerFunc("PATCH", dashboardsIDLabelsNamePath, newPatchLabelHandler(h.LabelService))

	return h
}

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


Question:
get delivery corresponding to a result
@param $deliveryResultIdentifier
@return mixed

public function getDelivery($deliveryResultIdentifier)
    {
        $sql = 'SELECT ' . self::DELIVERY_COLUMN . ' FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
        $params = array($deliveryResultIdentifier);
        return $this->getPersistence()->query($sql, $params)->fetchColumn();
    }

protected function _ensureTrackData()
    {
        if (! isset($this->_respTrackData['gtr_code'], $this->_respTrackData['gtr_name'])) {
            $select = $this->db->select();
            $select->from('gems__tracks')
                ->where('gtr_id_track = ?', $this->_respTrackData['gr2t_id_track']);

            if ($trackData = $this->db->fetchRow($select)) {
                $this->_respTrackData = $this->_respTrackData + $trackData;
            } else {
                $trackId = $this->_respTrackId;
                throw new \Gems_Exception("Track data missing for respondent track $trackId.");
            }
        }
    }

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


Question:
Setup the appropriate field to manage tagging for a belongs_many_many
relationship.

public function createReverseTagField($name) {
        $belongs_many_many = $this->owner->config()->belongs_many_many;
        if (!isset($belongs_many_many[$name]))
        {
            return null;
        }
        $className = $belongs_many_many[$name];
        $s = singleton(($className === 'SiteTree') ? 'Page' : $className);
        $visibleName = $s->plural_name();
        $field = null;
        if ($className::has_extension('Hierarchy'))
        {
            $field = TreeMultiselectField::create($name, 'Tagged '.$visibleName, $className);
        }
        else
        {
            $records = array();
            foreach ($className::get() as $record)
            {
                if ($record->canView())
                {
                    $records[] = $record;
                }
            }
            $field = ListboxField::create($name, 'Tagged '.$visibleName, $className::get()->map()->toArray())->setMultiple(true);
        }
        if ($field)
        {
            $field->setRightTitle($visibleName.' ('.$className.') using this tag');
        }
        return $field;
    }

public function dissociate()
    {
        $morphKey  = $this->morphKey;
        $morphType = $this->morphType;

        $this->parent->setAttr($morphKey, null);
        $this->parent->setAttr($morphType, null);
        $this->parent->save();

        return $this->parent->setRelation($this->relation, null);
    }

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


Question:
Filter items by the given key value pair.

@param string $key
@param mixed $value
@param bool $strict

@return static

public function where($key, $value, $strict = true)
    {
        return $this->filter(function ($item) use ($key, $value, $strict) {
            return $strict ? ArrayHelper::getValue($item, $key) === $value
                : ArrayHelper::getValue($item, $key) == $value;
        });
    }

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:
@from https://github.com/nette/latte/blob/master/src/Latte/Macros/CoreMacros.php#L253-L263

@param \Latte\MacroNode $node
@param \Latte\PhpWriter $writer
@param string $iterate

private function createIterator(MacroNode $node, PhpWriter $writer, $iterate)
	{
		if ($node->modifiers !== '|noiterator' && preg_match('#\W(\$iterator|include|require|get_defined_vars)\W#', $this->getCompiler()->expandTokens($node->content))) {
			$node->openingCode = '<?php $iterations = 0; foreach ($iterator = $_l->its[] = new Latte\Runtime\CachingIterator('. $iterate. ') as '. $writer->formatArgs(). ') { ?>';
			$node->closingCode = '<?php $iterations++; } array_pop($_l->its); $iterator = end($_l->its) ?>';
		} else {
			$node->openingCode = '<?php $iterations = 0; foreach ('. $iterate. ' as ' . $writer->formatArgs() . ') { ?>';
			$node->closingCode = '<?php $iterations++; } ?>';
		}
	}

public function getCookies($format = self::COOKIES_FLAT)
    {
        if (!\in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) {
            throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', [self::COOKIES_FLAT, self::COOKIES_ARRAY])));
        }

        if (self::COOKIES_ARRAY === $format) {
            return $this->cookies;
        }

        $flattenedCookies = [];
        foreach ($this->cookies as $path) {
            foreach ($path as $cookies) {
                foreach ($cookies as $cookie) {
                    $flattenedCookies[] = $cookie;
                }
            }
        }

        return $flattenedCookies;
    }

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


Question:
Sets the pygments lexer from mime type.

        :param mime: mime type
        :param options: optional addtional options.

def set_lexer_from_mime_type(self, mime, **options):

        self._lexer = get_lexer_for_mimetype(mime, **options)
        _logger().debug('lexer for mimetype (%s): %r', mime, self._lexer)

private function load_command_config_file($file, $prefix) {

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

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

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

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

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

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

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

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


Question: / tweak the form - depending on existing data

function definition_after_data() {
        global $CFG;

        $mform =& $this->_form;

        $courseid = $mform->getElementValue('courseid');

        if ($id = $mform->getElementValue('id')) {
            $scale = grade_scale::fetch(array('id'=>$id));
            $used = $scale->is_used();

            if ($used) {
                $mform->hardFreeze('scale');
            }

            if (empty($courseid)) {
                $mform->hardFreeze('standard');

            } else if (!has_capability('moodle/course:managescales', context_system::instance())) {
                //if they dont have managescales at system level the shouldnt be allowed to make scales standard (or not standard)
                $mform->hardFreeze('standard');

            } else if ($used and !empty($scale->courseid)) {
                $mform->hardFreeze('standard');
            }

            $usedstr = $scale->is_used() ? get_string('yes') : get_string('no');
            $used_el =& $mform->getElement('used');
            $used_el->setValue($usedstr);

        } else {
            $mform->removeElement('used');
            if (empty($courseid) or !has_capability('moodle/course:managescales', context_system::instance())) {
                $mform->hardFreeze('standard');
            }
        }
    }

def _run_formula(self, variable, population, period):

        formula = variable.get_formula(period)
        if formula is None:
            return None

        if self.trace:
            parameters_at = self.trace_parameters_at_instant
        else:
            parameters_at = self.tax_benefit_system.get_parameters_at_instant

        if formula.__code__.co_argcount == 2:
            array = formula(population, period)
        else:
            array = formula(population, period, parameters_at)

        self._check_formula_result(array, variable, population, period)
        return array

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


Question:
// GetServiceNetworkTier returns the network tier of GCP load balancer
// which should be assembled, and an error if the specified tier is not
// supported.

func GetServiceNetworkTier(service *v1.Service) (cloud.NetworkTier, error) {
	l, ok := service.Annotations[NetworkTierAnnotationKey]
	if !ok {
		return cloud.NetworkTierDefault, nil
	}

	v := cloud.NetworkTier(l)
	switch v {
	case cloud.NetworkTierStandard:
		fallthrough
	case cloud.NetworkTierPremium:
		return v, nil
	default:
		return cloud.NetworkTierDefault, fmt.Errorf("unsupported network tier: %q", v)
	}
}

func Dissect(dissect bool, data []byte) {
	if dissect {
		dissectLock.Lock()
		defer dissectLock.Unlock()

		initParser()
		parser.DecodeLayers(data, &cache.decoded)

		for _, typ := range cache.decoded {
			switch typ {
			case layers.LayerTypeEthernet:
				fmt.Println(gopacket.LayerString(&cache.eth))
			case layers.LayerTypeIPv4:
				fmt.Println(gopacket.LayerString(&cache.ip4))
			case layers.LayerTypeIPv6:
				fmt.Println(gopacket.LayerString(&cache.ip6))
			case layers.LayerTypeTCP:
				fmt.Println(gopacket.LayerString(&cache.tcp))
			case layers.LayerTypeUDP:
				fmt.Println(gopacket.LayerString(&cache.udp))
			case layers.LayerTypeICMPv4:
				fmt.Println(gopacket.LayerString(&cache.icmp4))
			case layers.LayerTypeICMPv6:
				fmt.Println(gopacket.LayerString(&cache.icmp6))
			default:
				fmt.Println("Unknown layer")
			}
		}
		if parser.Truncated {
			fmt.Println("  Packet has been truncated")
		}

	} else {
		fmt.Print(hex.Dump(data))
	}
}

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


Question: // Input sets the value of a form field.

func (self *Form) Input(name, value string) *Form {
	if _, ok := self.fields[name]; ok {
		self.fields.Set(name, value)
	}
	return self
}

public static CodedInput newInstance(final byte[] buf, final int off,
            final int len)
    {
        return new CodedInput(buf, off, len, false);
    }

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


Question:
Invoice the customer for the given amount.

@param string $description
@param int $amount
@param array $options

@return bool|StripeInvoice

@throws Card

public function invoiceFor($description, $amount, array $options = [])
    {
        if (!$this->stripe_id) {
            throw new InvalidArgumentException('User is not a customer. See the createAsStripeCustomer method.');
        }

        $options = array_merge([
            'customer' => $this->stripe_id,
            'amount' => $amount,
            'currency' => $this->preferredCurrency(),
            'description' => $description,
        ], $options);

        StripeInvoiceItem::create(
            $options, ['api_key' => $this->getStripeKey()]
        );

        return $this->invoice();
    }

def parse_record(self, node):

        if self.current_simulation == None:
            self.raise_error('<Record> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<Record> must specify a quantity.')

        scale = node.lattrib.get('scale', None)
        color  = node.lattrib.get('color', None)
        id  = node.lattrib.get('id', None)

        self.current_simulation.add_record(Record(quantity, scale, color, id))

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


Question: // Produce writes to stdout or stderr.

func (prod *StatsdMetrics) Produce(workers *sync.WaitGroup) {
	prod.AddMainWorker(workers)
	prod.TickerMessageControlLoop(prod.bufferMessage, prod.flushFrequency, prod.sendBatchOnTimeOut)
}

func (sdw *SplitDiffWorker) Run(ctx context.Context) error {
	resetVars()
	err := sdw.run(ctx)

	sdw.SetState(WorkerStateCleanUp)
	cerr := sdw.cleaner.CleanUp(sdw.wr)
	if cerr != nil {
		if err != nil {
			sdw.wr.Logger().Errorf2(cerr, "CleanUp failed in addition to job error")
		} else {
			err = cerr
		}
	}
	if err != nil {
		sdw.wr.Logger().Errorf2(err, "Run() error")
		sdw.SetState(WorkerStateError)
		return err
	}
	sdw.SetState(WorkerStateDone)
	return nil
}

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


Question: // IndexSortF is similar to IndexSort but with funcs as the input.

func IndexSortF(Len int, Less func(i, j int) bool) []int {
	indexes := make([]int, Len)
	for i := range indexes {
		indexes[i] = i
	}
	sort.Sort(InterfaceStruct{
		LenF: func() int {
			return Len
		},
		LessF: func(i, j int) bool {
			return Less(indexes[i], indexes[j])
		},
		SwapF: func(i, j int) {
			indexes[i], indexes[j] = indexes[j], indexes[i]
		},
	})
	return indexes
}

public function visitFilter(FilterInterface $filter)
    {
        if ($filter instanceof DummyFilter) {
            $type = 'dummy';
        } elseif ($filter instanceof SelectFilter) {
            $type = 'select';
        } elseif ($filter instanceof SearchFilter) {
            $type = 'search';
        } elseif ($filter instanceof SortFilter) {
            $type = 'sort';
        } elseif ($filter instanceof PaginationFilter) {
            $type = "{$filter->getType()}-pagination";
        } elseif (method_exists($filter, 'getType') === true) {
            $type = $filter->getType();
        } else {
            $type = 'dummy';
        }
        $template = "filter/$type.twig";

        return $this
            ->loadTemplate($template)
            ->render(
                [
                    "id" => $filter->getId(),
                    "options" => $filter->getOptions(),
                ]
            );
    }

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


Question:
Array values generator for powers from zero to upper power. Useful to cast
    as list/tuple and for numpy/scipy integration (be careful: numpy use the
    reversed from the output of this function used as input to a list or a
    tuple constructor).

def values(self):

    if self._data:
      for key in xrange(self.order + 1):
        yield self[key]

def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
        '''
        '''
        return cls._binary_op(x, y, tf.pow, tf.float32)

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


Question: Replace Param File Read from File Method

def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):

        # Set file extension property
        self.fileExtension = extension

        # Open file and parse into a data structure
        with open(path, 'r') as f:
            for line in f:
                sline = line.strip().split()
                if len(sline) == 1:
                    self.numParameters = sline[0]
                else:
                    # Create GSSHAPY TargetParameter object
                    target = TargetParameter(targetVariable=sline[0],
                                             varFormat=sline[1])

                    # Associate TargetParameter with ReplaceParamFile
                    target.replaceParamFile = self

@Override
    public void updateArrayFile(DataWriter writer, long position) throws IOException {
        writer.writeInt(position, val);
    }

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