Question:
Create relationship

@param  mixed            $source
@param  DocumentHydrator $hydrator
@return AbstractRelationship

public function createRelationship($source, DocumentHydrator $hydrator): AbstractRelationship
    {
        if (! isset($source->data)) {
            return $this->processNoDataRelationship($source, $hydrator);
        }

        if (is_object($source->data)) {
            return $this->processSingleIdentifierRelationship($source, $hydrator);
        }

        if (is_array($source->data)) {
            return $this->processIdentifierCollectionRelationship($source, $hydrator);
        }

        throw new InvalidDocumentException('If data is present and is not null it must be an object or an array');
    }

def parse_profile_from_hcard(hcard: str, handle: str):

    from federation.entities.diaspora.entities import DiasporaProfile  # Circulars
    doc = html.fromstring(hcard)
    profile = DiasporaProfile(
        name=_get_element_text_or_none(doc, ".fn"),
        image_urls={
            "small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"),
            "medium": _get_element_attr_or_none(doc, ".entity_photo_medium .photo", "src"),
            "large": _get_element_attr_or_none(doc, ".entity_photo .photo", "src"),
        },
        public=True if _get_element_text_or_none(doc, ".searchable") == "true" else False,
        id=handle,
        handle=handle,
        guid=_get_element_text_or_none(doc, ".uid"),
        public_key=_get_element_text_or_none(doc, ".key"),
    )
    return profile

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


Question:
Common method for creating styles.

@param template the template that the map is part of
@param styleRef the style ref identifying the style
@param <T> the source type

protected final <T> StyleSupplier<T> createStyleSupplier(
            final Template template,
            final String styleRef) {
        return new StyleSupplier<T>() {
            @Override
            public Style load(
                    final MfClientHttpRequestFactory requestFactory,
                    final T featureSource) {
                final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser;
                return OptionalUtils.or(
                        () -> template.getStyle(styleRef),
                        () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef))
                        .orElse(template.getConfiguration().getDefaultStyle(NAME));
            }
        };
    }

def match(self, request, service):

		uri = self.normalize_uri(request.path())

		if request.session().protocol() not in self.protocols:
			return

		if request.method() not in self.methods:
			return

		if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
			return

		if self.ports and int(request.session().server_address().port()) not in self.ports:
			return

		match_obj = self.re_pattern.match(uri)

		if not match_obj:
			return

		presenter_action = self.action
		presenter_args = self.presenter_args.copy()

		for i in range(len(self.route_args)):
			if self.route_args[i] == 'action':
				presenter_action = match_obj.group(i + 1)
			else:
				presenter_args[self.route_args[i]] = match_obj.group(i + 1)

		return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args)

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


Question: Marshall the given parameter object.

public void marshall(ConnectCustomKeyStoreRequest connectCustomKeyStoreRequest, ProtocolMarshaller protocolMarshaller) {

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

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

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

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


Question:
Set those values needed for editing

@param int $orgId The id of the current organization
@return \Gems_Model_AppointmentModel

public function applyEditSettings($orgId = null)
    {
        $this->applyDetailSettings(false);

        $agenda = $this->loader->getAgenda();
        $empty  = $this->util->getTranslated()->getEmptyDropdownArray();

        $this->setIfExists('gap_id_organization', 'default', $orgId ?: $this->currentOrganization->getId());
        $this->setIfExists('gap_admission_time',  'elementClass', 'Date');
        $this->setIfExists('gap_discharge_time',  'elementClass', 'Date');
        $this->setIfExists('gap_status',          'required', true);
        $this->setIfExists('gap_comment',         'elementClass', 'Textarea', 'rows', 5);

        $this->setIfExists('gap_id_activity',     'multiOptions', $empty + $agenda->getActivities($orgId));
        $this->setIfExists('gap_id_procedure',    'multiOptions', $empty + $agenda->getProcedures($orgId));
        $this->setIfExists('gap_id_location',     'multiOptions', $empty + $agenda->getLocations($orgId));

        if ($this->currentUser->hasPrivilege('pr.episodes')) {
            $this->setIfExists('gap_id_episode', 'multiOptions', $empty);
            $this->addDependency('AppointmentCareEpisodeDependency');
        }
        return $this;
    }

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
(non-Javadoc)

@see javax.persistence.EntityManager#flush()

@Override
    public void flush()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "em.flush();\n" + toString());

        getEMInvocationInfo(true).flush();
    }

private static MBeanServer setQueryExpServer(QueryExp query, MBeanServer toSet) {
        // We assume the QueryExp is a QueryEval subclass or uses the QueryEval thread local
        // mechanism to store any existing MBeanServer. If that's not the case we have no
        // way to access the old mbeanserver to let us restore it
        MBeanServer result = QueryEval.getMBeanServer();
        query.setMBeanServer(toSet);
        return result;
    }

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


Question:
Retrieves the minimum value of a property

@return the minimum value of the property

public Optional<BigDecimal> getMin() {
        if (property instanceof BaseIntegerProperty) {
            BaseIntegerProperty integerProperty = (BaseIntegerProperty) property;
            return Optional.ofNullable(integerProperty.getMinimum() != null ? integerProperty.getMinimum() : null);
        } else if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty numericProperty = (AbstractNumericProperty) property;
            return Optional.ofNullable(numericProperty.getMinimum());
        }
        return Optional.empty();
    }

private function minFightersCheck()
    {
        $fighters = $this->getFighters();
        $areas = $this->settings->fightingAreas;
        $fighterType = $this->championship->category->isTeam
            ? trans_choice('laravel-tournaments::core.team', 2)
            : trans_choice('laravel-tournaments::core.competitor', 2);

        $minFighterCount = $fighters->count() / $areas;

        if ($this->settings->hasPreliminary && $fighters->count() / ($this->settings->preliminaryGroupSize * $areas) < 1) {
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
                'number' => $this->settings->preliminaryGroupSize * $areas,
                'fighter_type' => $fighterType,
            ]), 422);
        }

        if ($minFighterCount < ChampionshipSettings::MIN_COMPETITORS_BY_AREA) {
            throw new TreeGenerationException(trans('laravel-tournaments::core.min_competitor_required', [
                'number' => ChampionshipSettings::MIN_COMPETITORS_BY_AREA,
                'fighter_type' => $fighterType,
            ]), 422);
        }
    }

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


Question:
given any user defined wrapper instructions
build the wrapper data

@param   array   Array of any passed wrapper info
@param   array   Array of the inputs attributes
@return  array   two element array of tag / attr

public function getWrapper($wrapper, $attr)
    {
        $type = '';
        if (! empty($attr['type'])) {
            $type = ' ' . $attr['type'];

            if ((isset($attr['type']) && $attr['type'] == 'select') && in_array('multiple', $attr)) {
                $type .= ' multiselect';
            }
        }

        $defaults = array(
            'tag' => 'div',
            'class' => 'input' . $type
        );

        $wrapperAttr = array_merge(
            $defaults,
            $wrapper
        );

        // double check for the presence of a tag element
        $tag = $wrapperAttr['tag'];
        unset($wrapperAttr['tag']);

        return array(
            'tag' => $tag,
            'attr' => $wrapperAttr
        );
    }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question:
Returns on of the commands that belong to the query.

@param  string $id
@return mixed

protected function getCommandClass($id)
    {
        if (isset($this->commands[$id])) {
            return $this->commands[$id];
        }

        throw new Exception(sprintf("command %s not found in %s", $id, get_called_class()));
    }

protected function initialise_combined_feedback(question_definition $question,
            $questiondata, $withparts = false) {
        $question->correctfeedback = $questiondata->options->correctfeedback;
        $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
        $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
        $question->partiallycorrectfeedbackformat =
                $questiondata->options->partiallycorrectfeedbackformat;
        $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
        $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
        if ($withparts) {
            $question->shownumcorrect = $questiondata->options->shownumcorrect;
        }
    }

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


Question:
Removes an entity instance.

A removed entity will be removed from the filesystem at or before transaction commit
or as a result of the flush operation.

@param object $entity The entity instance to remove.

public function remove($entity)
    {
        if ( ! is_object($entity)) {
            throw new \InvalidArgumentException(gettype($entity));
        }
        $this->errorIfClosed();
        $this->unitOfWork->remove($entity);
    }

public function post()
    {
        $request = $this->getDI()->get('request');
        // supply everything the request object could possibly need to fulfill the request
        $post = $request->getJson($this->getControllerName('singular'), $this->getModel());

        if (!$post) {
            throw new HTTPException('There was an error adding new record.  Missing POST data.', 400, [
                'dev' => 'Invalid data posted to the server',
                'code' => '568136818916816555'
            ]);
        }

        if(method_exists($this->model, "getBlockColumns")) {
            // filter out any block columns from the posted data
            $blockFields = $this->model->getBlockColumns();
            foreach ($blockFields as $key => $value) {
                unset($post->$value);
            }
        }

        $post = $this->beforeSave($post);
        // This record only must be created
        $id = $this->entity->save($post);
        $this->afterSave($post, $id);

        // now fetch the record so we can return it
        $result = $this->entity->findFirst($id);

        if ($result->countResults() == 0) {
            // This is bad. Throw a 500. Responses should always be objects.
            throw new HTTPException('There was an error retrieving the newly created record.', 500, [
                'dev' => 'The resource you requested is not available after it was just created',
                'code' => '1238510381861'
            ]);
        } else {
            return $result;
        }
    }

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


Question:
returns the ASCII value of $char - ASCII value of 'a'

@param string $char
@return int

private function getCharIndex(string $char): int {
        if (\strlen($char) > 1) $char = \substr($char, 0, 1);
        return \ord($char) - \ord('a');
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question:
Give information about the scanned annotations related to route definition.

@return array

public function getRouteDefinitionsDetail()
    {
        $paths = array();
        foreach ($this->getEndpointsInClasses($this->getReader()) as $endpoint) {
            /* @var \Collective\Annotations\Routing\Annotations\MethodEndpoint $endpoint */
            foreach ($endpoint->toRouteDefinitionDetail() as $path) {
                $paths[] = $path;
            }
        }

        return $paths;
    }

def navigate(store_id, category_id, node_id)
      response = api_get("Stores.egg", "Navigation", "#{store_id}/#{category_id}/#{node_id}")
      categories = JSON.parse(response.body)
    end

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


Question:
// TryWriteSymbol attempts to encode the next symbol using the contents of the
// bit buffer alone. It reports whether it succeeded.
//
// This method is designed to be inlined for performance reasons.

func (pw *Writer) TryWriteSymbol(sym uint, pe *Encoder) bool {
	chunk := pe.chunks[uint32(sym)&pe.chunkMask]
	nb := uint(chunk & countMask)
	if 64-pw.numBits < nb {
		return false
	}
	pw.bufBits |= uint64(chunk>>countBits) << pw.numBits
	pw.numBits += nb
	return true
}

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question: active formatting elements

void pushActiveFormattingElements(Element in) {
        int numSeen = 0;
        for (int pos = formattingElements.size() -1; pos >= 0; pos--) {
            Element el = formattingElements.get(pos);
            if (el == null) // marker
                break;

            if (isSameFormattingElement(in, el))
                numSeen++;

            if (numSeen == 3) {
                formattingElements.remove(pos);
                break;
            }
        }
        formattingElements.add(in);
    }

private function getHtmlTagForMark(MarkInterface $mark): string
    {
        $type = $mark->getType();
        $tags = [
            'bold' => 'strong',
            'code' => 'code',
            'italic' => 'em',
            'underline' => 'u',
        ];

        return $tags[$type] ?? 'span';
    }

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


Question:
解析字体信息相关节点

@param {XMLDocument} xmlDoc XML文档对象
@param {Object} ttf ttf对象
@return {Object} ttf对象

function parseFont(xmlDoc, ttf) {

            var metaNode = xmlDoc.getElementsByTagName('metadata')[0];
            var fontNode = xmlDoc.getElementsByTagName('font')[0];
            var fontFaceNode = xmlDoc.getElementsByTagName('font-face')[0];

            if (metaNode && metaNode.textContent) {
                ttf.metadata = string.decodeHTML(metaNode.textContent.trim());
            }

            // 解析font，如果有font节点说明是svg格式字体文件
            if (fontNode) {
                ttf.id = fontNode.getAttribute('id') || '';
                ttf.hhea.advanceWidthMax = +(fontNode.getAttribute('horiz-adv-x') || 0);
                ttf.from = 'svgfont';
            }

            if (fontFaceNode) {
                var OS2 = ttf['OS/2'];
                ttf.name.fontFamily = fontFaceNode.getAttribute('font-family') || '';
                OS2.usWeightClass = +(fontFaceNode.getAttribute('font-weight') || 0);
                ttf.head.unitsPerEm = +(fontFaceNode.getAttribute('units-per-em') || 0);

                // 解析panose, eg: 2 0 6 3 0 0 0 0 0 0
                var panose = (fontFaceNode.getAttribute('panose-1') || '').split(' ');
                [
                    'bFamilyType', 'bSerifStyle', 'bWeight', 'bProportion', 'bContrast',
                    'bStrokeVariation', 'bArmStyle', 'bLetterform', 'bMidline', 'bXHeight'
                ].forEach(function (name, i) {
                    OS2[name] = +(panose[i] || 0);
                });

                ttf.hhea.ascent = +(fontFaceNode.getAttribute('ascent') || 0);
                ttf.hhea.descent = +(fontFaceNode.getAttribute('descent') || 0);
                OS2.bXHeight = +(fontFaceNode.getAttribute('x-height') || 0);

                // 解析bounding
                var box = (fontFaceNode.getAttribute('bbox') || '').split(' ');
                ['xMin', 'yMin', 'xMax', 'yMax'].forEach(function (name, i) {
                    ttf.head[name] = +(box[i] || '');
                });

                ttf.post.underlineThickness = +(fontFaceNode.getAttribute('underline-thickness') || 0);
                ttf.post.underlinePosition = +(fontFaceNode.getAttribute('underline-position') || 0);

                // unicode range
                var unicodeRange = fontFaceNode.getAttribute('unicode-range');
                if (unicodeRange) {
                    unicodeRange.replace(/u\+([0-9A-Z]+)(\-[0-9A-Z]+)?/i, function ($0, a, b) {
                        OS2.usFirstCharIndex = Number('0x' + a);
                        OS2.usLastCharIndex = b ? Number('0x' + b.slice(1)) : 0xFFFFFFFF;
                    });
                }
            }

            return ttf;
        }

private synchronized Collection<IResult> valuesToParameters(Process process, ValueMap<Output, OWLValue> values) throws NotYetImplementedException, OWLTranslationException
    {
        if (values.isEmpty())
        {
            return null;
        }
        Collection<IResult> parameters = new ArrayList<IResult>();
        Iterator<Entry<Output, OWLValue>> valuesIterator = values.iterator();
        while (valuesIterator.hasNext())
        {
            Entry<Output, OWLValue> valuesEntry = valuesIterator.next();
            final OWLSParameter parameter
                    = new OWLSParameter(
                            process.getOntology(),
                            valuesEntry.getKey().getName(),
                            valuesEntry.getValue());
            parameters.add(new IOutputValue()
            {
                @Override
                public IOutput getOutput()
                {
                    try
                    {
                        return output(parameter.name());
                    } catch (ModelException ex)
                    {
                        return null;
                    }
                }

                @Override
                public Object object() throws ModelException
                {
                    return parameter.object();
                }

                @Override
                public ISemanticIdentifier getSemanticAnnotation()
                {
                    return parameter.getSemanticAnnotation();
                }

                @Override
                public ISubject value() throws ModelException
                {
                    if (null != functionalityGrounding)
                    {
                        return functionalityGrounding.createOutput(parameter.object(), OWLSAtomicService.this).value();
                    }
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        return parameters;
    }

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


Question:
Add a row to the data set.
@param columnValues Column values forming a row.
@return The data set instance (for chained calls).
@throws InvalidOperationException if this data set is read-only.
@see #rows(Object[][])
@see #add(DataSet)
@see #isReadOnly()

@SafeVarargs
  public final DataSet row(Object... columnValues) {
    checkIfNotReadOnly();
    if (columnValues.length != source.getColumnCount()) {
      throw new InvalidOperationException(source.getColumnCount() +
          " columns expected, not " + columnValues.length + ".");
    }
    addRow(new Row(columnValues));
    return this;
  }

@Override
	protected List<OUT> executeOnCollections(List<IN1> inputData1, List<IN2> inputData2, RuntimeContext ctx, ExecutionConfig executionConfig) throws Exception {
		CrossFunction<IN1, IN2, OUT> function = this.userFunction.getUserCodeObject();

		FunctionUtils.setFunctionRuntimeContext(function, ctx);
		FunctionUtils.openFunction(function, this.parameters);

		ArrayList<OUT> result = new ArrayList<OUT>(inputData1.size() * inputData2.size());

		TypeSerializer<IN1> inSerializer1 = getOperatorInfo().getFirstInputType().createSerializer(executionConfig);
		TypeSerializer<IN2> inSerializer2 = getOperatorInfo().getSecondInputType().createSerializer(executionConfig);
		TypeSerializer<OUT> outSerializer = getOperatorInfo().getOutputType().createSerializer(executionConfig);

		for (IN1 element1 : inputData1) {
			for (IN2 element2 : inputData2) {
				IN1 copy1 = inSerializer1.copy(element1);
				IN2 copy2 = inSerializer2.copy(element2);
				OUT o = function.cross(copy1, copy2);
				result.add(outSerializer.copy(o));
			}
		}

		FunctionUtils.closeFunction(function);
		return result;
	}

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


Question:
Convert an OCRA crypto function description into a CryptoFunction
       instance

       :param crypto_function_description:
       :returns:
           the CryptoFunction object
       :rtype: CryptoFunction

def str2cryptofunction(crypto_function_description):
    '''

    '''
    s = crypto_function_description.split('-')
    if len(s) != 3:
        raise ValueError('CryptoFunction description must be triplet separated by -')
    if s[0] != HOTP:
        raise ValueError('Unknown CryptoFunction kind %s' % s[0])
    algo = str2hashalgo(s[1])
    try:
        truncation_length = int(s[2])
        if truncation_length < 0 or truncation_length > 10:
            raise ValueError()
    except ValueError:
        raise ValueError('Invalid truncation length %s' % s[2])
    return CryptoFunction(algo, truncation_length)

public void marshall(CodeContentDescription codeContentDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(codeContentDescription.getTextContent(), TEXTCONTENT_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getCodeMD5(), CODEMD5_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getCodeSize(), CODESIZE_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getS3ApplicationCodeLocationDescription(), S3APPLICATIONCODELOCATIONDESCRIPTION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Adds a style element with $css to $document.

This method is protected to allow overriding.

@see https://github.com/jjriv/emogrifier/issues/103

@param \DOMDocument $document
@param string $css

@return void

protected function addStyleElementToDocument(\DOMDocument $document, $css)
    {
        $styleElement = $document->createElement('style', $css);
        $styleAttribute = $document->createAttribute('type');
        $styleAttribute->value = 'text/css';
        $styleElement->appendChild($styleAttribute);

        $bodyElement = $this->getBodyElement($document);
        $bodyElement->appendChild($styleElement);
    }

def buildcss(app, buildpath, imagefile):
    """"""
    # set default values
    div = 'body'
    repeat = 'repeat-y'
    position = 'center'
    attachment = 'scroll'

    if app.config.sphinxmark_div != 'default':
        div = app.config.sphinxmark_div

    if app.config.sphinxmark_repeat is False:
        repeat = 'no-repeat'

    if app.config.sphinxmark_fixed is True:
        attachment = 'fixed'

    border = app.config.sphinxmark_border
    if border == 'left' or border == 'right':
        css = template('border', div=div, image=imagefile, side=border)
    else:
        css = template('watermark', div=div, image=imagefile, repeat=repeat,
                       position=position, attachment=attachment)
    LOG.debug('[sphinxmark] Template: ' + css)
    cssname = 'sphinxmark.css'
    cssfile = os.path.join(buildpath, cssname)

    with open(cssfile, 'w') as f:
        f.write(css)

    return(cssname)

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


Question:
Private method to get the list of the translatable fields of a given entity.

@param $className string The class to look mapping infos for.
@return array an array containing the list of the translatable fields associated to their type.

private function getTranslatableFields($className)
    {
        // Here we use reflection to get the class
        $reflectionClass = new \ReflectionClass($className);
        $translatableFields = array();
        // and its entities
        $reflectionProperties = $reflectionClass->getProperties();
        foreach ($reflectionProperties as $reflectionProperty) {
            // We use the annotation reader to get the properties annotated with the "Translatable" annotation
            $propertyAnnotation = $this->annotationReader->getPropertyAnnotation($reflectionProperty, 'Gedmo\Mapping\Annotation\Translatable');
            if ($propertyAnnotation) {
                // In this case we have to get the property name and its type in the mapping annotation
                $mappingAnnotation = $this->annotationReader->getPropertyAnnotation($reflectionProperty, 'Doctrine\ORM\Mapping\Column');
                $translatableFields[$reflectionProperty->getName()] = $mappingAnnotation->type;
            }
        }
        return $translatableFields;
    }

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

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

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

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

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

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


Question:
Function that provides matrix product interface with PSD matrix.

    Args:
      vector: the vector to be multiplied with matrix H

    Returns:
      result_product: Matrix product of H and vector

def get_h_product(self, vector, dtype=None):

    # Computing the product of matrix_h with beta (input vector)
    # At first layer, h is simply diagonal
    if dtype is None:
      dtype = self.nn_dtype
    beta = tf.cast(vector, self.nn_dtype)
    h_beta_rows = []
    for i in range(self.nn_params.num_hidden_layers):
      # Split beta of this block into [gamma, delta]
      gamma = beta[self.dual_index[i]:self.dual_index[i + 1]]
      delta = beta[self.dual_index[i + 1]:self.dual_index[i + 2]]

      # Expanding the product with diagonal matrices
      if i == 0:
        h_beta_rows.append(
            tf.multiply(2 * self.lambda_lu[i], gamma) -
            self.nn_params.forward_pass(
                tf.multiply(self.lambda_quad[i + 1], delta),
                i,
                is_transpose=True))
      else:
        h_beta_rows[i] = (h_beta_rows[i] +
                          tf.multiply(self.lambda_quad[i] +
                                      self.lambda_lu[i], gamma) -
                          self.nn_params.forward_pass(
                              tf.multiply(self.lambda_quad[i+1], delta),
                              i, is_transpose=True))

      new_row = (
          tf.multiply(self.lambda_quad[i + 1] + self.lambda_lu[i + 1], delta) -
          tf.multiply(self.lambda_quad[i + 1],
                      self.nn_params.forward_pass(gamma, i)))
      h_beta_rows.append(new_row)

    # Last boundary case
    h_beta_rows[self.nn_params.num_hidden_layers] = (
        h_beta_rows[self.nn_params.num_hidden_layers] +
        tf.multiply((self.lambda_quad[self.nn_params.num_hidden_layers] +
                     self.lambda_lu[self.nn_params.num_hidden_layers]),
                    delta))

    h_beta = tf.concat(h_beta_rows, axis=0)
    return tf.cast(h_beta, dtype)

func setBlendFunc(cmp pixel.ComposeMethod) {
	switch cmp {
	case pixel.ComposeOver:
		glhf.BlendFunc(glhf.One, glhf.OneMinusSrcAlpha)
	case pixel.ComposeIn:
		glhf.BlendFunc(glhf.DstAlpha, glhf.Zero)
	case pixel.ComposeOut:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.Zero)
	case pixel.ComposeAtop:
		glhf.BlendFunc(glhf.DstAlpha, glhf.OneMinusSrcAlpha)
	case pixel.ComposeRover:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.One)
	case pixel.ComposeRin:
		glhf.BlendFunc(glhf.Zero, glhf.SrcAlpha)
	case pixel.ComposeRout:
		glhf.BlendFunc(glhf.Zero, glhf.OneMinusSrcAlpha)
	case pixel.ComposeRatop:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.SrcAlpha)
	case pixel.ComposeXor:
		glhf.BlendFunc(glhf.OneMinusDstAlpha, glhf.OneMinusSrcAlpha)
	case pixel.ComposePlus:
		glhf.BlendFunc(glhf.One, glhf.One)
	case pixel.ComposeCopy:
		glhf.BlendFunc(glhf.One, glhf.Zero)
	default:
		panic(errors.New("Canvas: invalid compose method"))
	}
}

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


Question:
Drop table

@param table
@param keyspace

@When("^I drop a Cassandra table named '(.+?)' using keyspace '(.+?)'$")
    public void dropTableWithData(String table, String keyspace) {
        try {
            commonspec.getCassandraClient().useKeyspace(keyspace);
            commonspec.getCassandraClient().dropTable(table);
        } catch (Exception e) {
            commonspec.getLogger().debug("Exception captured");
            commonspec.getLogger().debug(e.toString());
            commonspec.getExceptions().add(e);
        }
    }

def put(self, template_name):
        """"""
        self.reqparse.add_argument('template', type=str, required=True)
        args = self.reqparse.parse_args()

        template = db.Template.find_one(template_name=template_name)

        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)

        changes = diff(template.template, args['template'])
        template.template = args['template']
        template.is_modified = True

        db.session.add(template)
        db.session.commit()
        auditlog(
            event='template.update',
            actor=session['user'].username,
            data={
                'template_name': template_name,
                'template_changes': changes
            }
        )

        return self.make_response('Template {} has been updated'.format(template_name))

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


Question:
Checks whether the elment causes a visual line break
(<br> or block elements)

function _isLineBreakOrBlockElement(element) {
      if (_isLineBreak(element)) {
        return true;
      }

      if (wysihtml5.dom.getStyle("display").from(element) === "block") {
        return true;
      }

      return false;
    }

function partNode(node){
      if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
        node.currentText = node.firstChild.nodeValue;
        return !/[\n\t\r]/.test(node.currentText);
      }
      return false;
    }

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


Question:
Adds the commerce address to the database. Also notifies the appropriate model listeners.

@param commerceAddress the commerce address
@return the commerce address that was added

@Indexable(type = IndexableType.REINDEX)
	@Override
	public CommerceAddress addCommerceAddress(CommerceAddress commerceAddress) {
		commerceAddress.setNew(true);

		return commerceAddressPersistence.update(commerceAddress);
	}

public function store(Request $request)
	{
		$this->authorize('blog',  Auth::user());

    	$this->validate($request, Post::storeRules());

    	$this->validate($request, Category::storeRules());
    	$this->validate($request, Tag::storeRules());

    	\DB::transaction(function () use ($request){
    		$post = Post::create(Post::storeAttributes($request));

    		$categories = explode(',', $request->categories);
    		// remove empty items from array
    		$categories = array_filter($categories);
    		// trim all the items in array
    		$categories =array_map('trim', $categories);

    		$post->saveCategories($categories);

    		$tags = explode(',', $request->tags);

    		// remove empty items from array
    		$tags = array_filter($tags);
    		// trim all the items in array
    		$tags =array_map('trim', $tags);

    		$post->saveTags($tags);

    	});

    	return redirect(route('blog'));
	}

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


final protected function loadSubModel($model)
    {
        if (is_file($this->validSubModels[ $model ])) {
            $className = '\\' . get_called_class() . '\\' . ucfirst($model);
            $className = str_replace('\Base\\Model', '\Models', $className);

            if (class_exists($className)) {
                $this->{$model} = new $className();
            }
        }

        return $this->{$model};
    }

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


@Override
	public void setup(AbstractInvokable parent) {
		@SuppressWarnings("unchecked")
		final ReduceFunction<IT> red = BatchTask.instantiateUserCode(this.config, userCodeClassLoader, ReduceFunction.class);
		this.reducer = red;
		FunctionUtils.setFunctionRuntimeContext(red, getUdfRuntimeContext());

		TypeSerializerFactory<IT> serializerFactory = this.config.getInputSerializer(0, userCodeClassLoader);
		this.serializer = serializerFactory.getSerializer();

		if (LOG.isDebugEnabled()) {
			LOG.debug("ChainedAllReduceDriver object reuse: " + (this.objectReuseEnabled ? "ENABLED" : "DISABLED") + ".");
		}
	}

public static byte[] decode( byte[] source, int off, int len )
    {
        int    len34   = len * 3 / 4;
        byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
        int    outBuffPosn = 0;

        byte[] b4        = new byte[4];
        int    b4Posn    = 0;
        int    i         = 0;
        byte   sbiCrop   = 0;
        byte   sbiDecode = 0;
        for( i = 0; i < len; i++ )
        {
            sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
            sbiDecode = DECODABET[ sbiCrop ];

            if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
            {
                if( sbiDecode >= EQUALS_SIGN_ENC )
                {
                    b4[ b4Posn++ ] = sbiCrop;
                    if( b4Posn > 3 )
                    {
                        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
                        b4Posn = 0;

                        // If that was the equals sign, break out of 'for' loop
                        if( sbiCrop == EQUALS_SIGN )
                            break;
                    }   // end if: quartet built

                }   // end if: equals sign or better

            }   // end if: white space, equals sign or better
            else
            {
				LoggerFactory.getDefaultLogger().error( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
                return null;
            }   // end else:
        }   // each input character

        byte[] out = new byte[ outBuffPosn ];
        System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
        return out;
    }

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


Question:
口語から日時を返します
判別できない場合はtoDatetimeへ処理を委譲し結果を返します
@param  {String} value
@param  {Date}   now     既定値: 現在の日時
@return {Date}   date

function parse (value, now) {
  now = now ? this.toDate(now) : new Date();
  if (!now) {
    return null;
  }
  // 営業日計算
  if (value.indexOf('営業日') !== -1) {
    value = suji(value);
    var matches = value.match(BIZ);
    if (matches) {
      return this.addBiz(now, matches[1] * (matches[2] === '前' ? -1 : 1));
    } else {
      return null;
    }
  // そのほか
  } else {
    return parseFn(value, this.startMonth, this._startWeek, now) ||
           toDatetimeFn(value, this.startMonth);
  }
}

protected function convertParam($platform, $param, $type = null)
    {
        if (is_object($param)) {
            if (!method_exists($param, '__toString')) {
                if ($param instanceof DateTimeInterface) {
                    $param = $param->format('Y-m-d H:i:s');
                } elseif (Type::hasType($type)) {
                    $type  = Type::getType($type);
                    $param = $type->convertToDatabaseValue($param, $platform);
                } else {
                    throw new Exception('Given query param is an instance of ' . get_class($param) . ' and could not be converted to a string');
                }
            }
        } elseif (is_array($param)) {
            if ($this->isNestedArray($param)) {
                $param = json_encode($param, JSON_UNESCAPED_UNICODE);
            } else {
                $param = implode(
                    ', ',
                    array_map(
                        function ($part) {
                            return '"' . (string) $part . '"';
                        },
                        $param
                    )
                );

                return '(' . $param . ')';
            }
        } else {
            $param = e($param);
        }

        return '"' . (string) $param . '"';
    }

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


Question:
Substitute sub-expressions both on the lhs and rhs

        Args:
            var_map (dict): Dictionary with entries of the form
                ``{expr: substitution}``

def substitute(self, var_map, cont=False, tag=None):

        return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)

def detect_builtin_shadowing_locals(self, function_or_modifier):

        results = []
        for local in function_or_modifier.variables:
            if self.is_builtin_symbol(local.name):
                results.append((self.SHADOWING_LOCAL_VARIABLE, local, function_or_modifier))
        return results

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


Question:
Creates the wrapper which contains the menu item and the adjacent label
for displaying the occurred events

@param menuItemButton
the menu item
@param notificationLabel
the label for displaying the occurred events
@return Component of type CssLayout

private static Component buildLabelWrapper(final ValoMenuItemButton menuItemButton,
            final Component notificationLabel) {
        final CssLayout dashboardWrapper = new CssLayout(menuItemButton);
        dashboardWrapper.addStyleName("labelwrapper");
        dashboardWrapper.addStyleName(ValoTheme.MENU_ITEM);
        notificationLabel.addStyleName(ValoTheme.MENU_BADGE);
        notificationLabel.setWidthUndefined();
        notificationLabel.setVisible(false);
        notificationLabel.setId(UIComponentIdProvider.NOTIFICATION_MENU_ID + menuItemButton.getCaption().toLowerCase());
        dashboardWrapper.addComponent(notificationLabel);
        return dashboardWrapper;
    }

private void initComponents()//GEN-BEGIN:initComponents
    {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        lblEnabled = new javax.swing.JLabel();
        cbEnabled = new javax.swing.JCheckBox();
        lblDisabledByParent = new javax.swing.JLabel();
        cbDisabledByParent = new javax.swing.JCheckBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblSchemaName = new javax.swing.JLabel();
        tfSchemaName = new javax.swing.JTextField();

        setLayout(new java.awt.GridBagLayout());

        addComponentListener(new java.awt.event.ComponentAdapter()
        {
            public void componentShown(java.awt.event.ComponentEvent evt)
            {
                formComponentShown(evt);
            }
            public void componentHidden(java.awt.event.ComponentEvent evt)
            {
                formComponentHidden(evt);
            }
        });

        addHierarchyListener(new java.awt.event.HierarchyListener()
        {
            public void hierarchyChanged(java.awt.event.HierarchyEvent evt)
            {
                formHierarchyChanged(evt);
            }
        });

        jPanel1.setLayout(new java.awt.GridLayout(4, 2));

        lblEnabled.setText("enabled");
        lblEnabled.setDisplayedMnemonic('e');
        jPanel1.add(lblEnabled);

        cbEnabled.setMnemonic('e');
        cbEnabled.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cbEnabledActionPerformed(evt);
            }
        });

        jPanel1.add(cbEnabled);

        lblDisabledByParent.setText("disabled by Parent:");
        jPanel1.add(lblDisabledByParent);

        cbDisabledByParent.setEnabled(false);
        cbDisabledByParent.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cbDisabledByParentActionPerformed(evt);
            }
        });

        jPanel1.add(cbDisabledByParent);

        jPanel1.add(jLabel4);

        jPanel1.add(jLabel3);

        lblSchemaName.setText("Schema Name:");
        lblSchemaName.setLabelFor(tfSchemaName);
        jPanel1.add(lblSchemaName);

        tfSchemaName.setEditable(false);
        tfSchemaName.setText("jTextField1");
        tfSchemaName.setBorder(null);
        jPanel1.add(tfSchemaName);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        add(jPanel1, gridBagConstraints);

    }

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


Question:
@param array $array

@return Product

protected function doCreateObject(array $array)
    {
        $this->data    = $array;
        $this->product = new Product($this->data);
        $this->setBrands()
             ->setFunctionalNames()
             ->setPromotions()
             ->setProductsToPromotions()
             ->setOptions()
             ->setAttributes()
             ->setMedia();

        return $this->product;
    }

public function getSearchProduct()
    {
        if ($this->_oSearchProduct === null) {
            $this->_oSearchProduct = false;
            $sSearchArtNum = $this->getSearchProductArtNr();

            foreach ($this->getProductList() as $oProduct) {
                if ($oProduct->oxarticles__oxartnum->value == $sSearchArtNum) {
                    $this->_oSearchProduct = $oProduct;
                    break;
                }
            }
        }

        return $this->_oSearchProduct;
    }

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


Question:
Getter Method for valueField.

If no value is provided it will auto matically return the primary key of the derived model class.

@return string The primary key from `modelClass`.

public function getValueField()
    {
        if ($this->_valueField === null) {
            $class = $this->modelClass;
            $this->_valueField = implode("", $class::primaryKey());
        }

        return $this->_valueField;
    }

public static <V> Optional<V> associated(Associator associator,
            Class<V> type, Serializable id) {
        return associator.associated(new TypedIdKey<>(type, id), type);
    }

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


Question:
Set the value for this function.
Note that if value is null an {@link ND4JIllegalStateException}
will be thrown.
@param target the target field
@param value the value to set

public void setValueFor(Field target, Object value) {
        if(value == null && target.getType().isPrimitive()) {
            throw new ND4JIllegalStateException("Unable to set primitive field " + target + " of type " + target.getClass()
                    + " using null value!");
        }

        if(value != null) {
            value = ensureProperType(target, value);
        }

        if(isConfigProperties()){
            String propertyName = configFieldName();
            if(propertyName == null)
                propertyName = "config";
            Field f = null;
            Class<?> currClass = getClass();
            try{
                f = currClass.getDeclaredField(propertyName);
            } catch (NoSuchFieldException e){
                //OK, try superclass
            }
            while(f == null && currClass.getSuperclass() != null){
                currClass = currClass.getSuperclass();
                try{
                    f = currClass.getDeclaredField(propertyName);
                } catch (NoSuchFieldException e){
                    //OK, try superclass
                }
            }

            if(f == null){
                throw new IllegalStateException("Could not find field \"" + propertyName + "\" for class " + getClass().getName());
            }

            try {
                f.setAccessible(true);
                Object o = f.get(this);
                if(o == null){
                    //Null config class - try to create one...
                    Class<?> c = f.getType();
                    try {
                        o = c.newInstance();
                    } catch (InstantiationException e){
                        throw new RuntimeException("Error creating new instance of configuration object type " + c.getName(), e);
                    }
                    f.set(this, o);
                }
                target.set(o, value);
            } catch (IllegalAccessException e){
                throw new RuntimeException("Error setting configuration field \"" + propertyName + "\" for config field \"" + propertyName
                    + "\" on class " + getClass().getName());
            }

        } else {
            try {
                target.set(this,value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Error setting property for function " + getClass().getName(), e);
            }
        }
    }

func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.Flag) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		res, isNull, err = sf.EvalString(sf.GetCtx(), row)
	}

	if isNull || err != nil {
		d.SetValue(nil)
		return d, err
	}
	d.SetValue(res)
	return
}

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


Question:
Sign the request by adding some special request headers

@param Event $event The current event

public function signRequest(Event $event) {
        $command = $event['command'];

        switch ($command->getName()) {
            case 'AddImage':
            case 'DeleteImage':
            case 'ReplaceMetadata':
            case 'EditMetadata':
            case 'DeleteMetadata':
            case 'GenerateShortUrl':
            case 'EditResourceGroup':
            case 'DeleteResourceGroup':
            case 'EditPublicKey':
            case 'DeletePublicKey':
            case 'AddAccessControlRules':
            case 'DeleteAccessControlRule':
                // Add the auth headers
                $this->addAuthenticationHeaders($command->getRequest());
                break;
        }
    }

public function build(): SetRequestInterceptionRequest
	{
		$instance = new SetRequestInterceptionRequest();
		if ($this->patterns === null) {
			throw new BuilderException('Property [patterns] is required.');
		}
		$instance->patterns = $this->patterns;
		return $instance;
	}

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


Question:
Format argument in called method

@param mixed $arg

protected static function _formatCalledArgument($arg)
        {
            $out = '';
            if (is_object($arg)) {
                $out .= sprintf("&%s#%s#", get_class($arg), spl_object_hash($arg));

            } else if (is_resource($arg)) {
                $out .= '#[' . get_resource_type($arg) . ']';
            } else if (Arrays::isArray($arg)) {
                $isAssociative = false;
                $args = array();
                foreach ($arg as $k => $v) {
                    if (!is_numeric($k)) {
                        $isAssociative = true;
                    }
                    $args[$k] = static::_formatCalledArgument($v);
                }
                if ($isAssociative) {
                    $arr = array();
                    foreach ($args as $k => $v) {
                        $arr[] = static::_formatCalledArgument($k) . ' => ' . $v;
                    }
                    $out .= 'array(' . join(', ', $arr) . ')';
                } else {
                    $out .= 'array(' . join(', ', $args) . ')';
                }
            } else if (is_null($arg)) {
                $out .= 'NULL';
            } else if (is_numeric($arg) || is_float($arg)) {
                $out .= $arg;
            } else if (is_string($arg)) {
                if (strlen($arg) > static::$argLength) {
                    $arg = substr($arg, 0, static::$argLength) . "...";
                }
                $arg = strtr($arg, array("\t" => '\t', "\r" => '\r', "\n" => '\n', "'" => '\\\''));
                $out .= "'" . $arg . "'";
            } else if (is_bool($arg)) {
                $out .= $arg === true ? 'true' : 'false';
            }

            return $out;
        }

func (s *JobParameters) SetFormat(v string) *JobParameters {
	s.Format = &v
	return s
}

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


Question: // Create a transaction to copy archived block devices into public repository

func (r Virtual_Guest_Block_Device_Template_Group) CreatePublicArchiveTransaction(groupName *string, summary *string, note *string, locations []datatypes.Location) (resp int, err error) {
	params := []interface{}{
		groupName,
		summary,
		note,
		locations,
	}
	err = r.Session.DoRequest("SoftLayer_Virtual_Guest_Block_Device_Template_Group", "createPublicArchiveTransaction", params, &r.Options, &resp)
	return
}

func (in *RevisionHistory) DeepCopyInto(out *RevisionHistory) {
	*out = *in
	in.DeployedAt.DeepCopyInto(&out.DeployedAt)
	in.Source.DeepCopyInto(&out.Source)
	return
}

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


Question: Compile type schema: plain type matching

def _compile_type(self, schema):

        # Prepare self
        self.compiled_type = const.COMPILED_TYPE.TYPE
        self.name = get_type_name(schema)

        # Error partials
        err_type = self.Invalid(_(u'Wrong type'), self.name)

        # Type check function
        if six.PY2 and schema is basestring:
            # Relaxed rule for Python2 basestring
            typecheck = lambda v: isinstance(v, schema)
        else:
            # Strict type check for everything else
            typecheck = lambda v: type(v) == schema

        # Matcher
        if self.matcher:
            def match_type(v):
                return typecheck(v), v
            return match_type

        # Validator
        def validate_type(v):
            # Type check
            if not typecheck(v):
                # expected=<type>, provided=<type>
                raise err_type(get_type_name(type(v)))
            # Fine
            return v

        return validate_type

public static <K, V> Flux<K> scan(RedisKeyReactiveCommands<K, V> commands) {
        return scan(commands, Optional.empty());
    }

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


Question: // Put is specified in the StorageWriter interface.

func (stor *maas1Storage) Put(name string, r io.Reader, length int64) error {
	name = stor.prefixWithPrivateNamespace(name)
	data, err := ioutil.ReadAll(io.LimitReader(r, length))
	if err != nil {
		return err
	}
	params := url.Values{"filename": {name}}
	files := map[string][]byte{"file": data}
	_, err = stor.maasClient.CallPostFiles("add", params, files)
	return err
}

func (p *TCompactProtocol) WriteListBegin(elemType TType, size int) error {
	_, err := p.writeCollectionBegin(elemType, size)
	return NewTProtocolException(err)
}

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


Question: // MatchAny returns true if any of the RefSpec match with the given ReferenceName.

func MatchAny(l []RefSpec, n plumbing.ReferenceName) bool {
	for _, r := range l {
		if r.Match(n) {
			return true
		}
	}

	return false
}

func (m *MockManager) Find(arg0 string) (release.Release, bool) {
	ret := m.ctrl.Call(m, "Find", arg0)
	ret0, _ := ret[0].(release.Release)
	ret1, _ := ret[1].(bool)
	return ret0, ret1
}

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


Question: // Group groups components based on their group ids

func (r ComponentReferences) Group() (refs []ComponentReferences) {
	sorted := make(GroupedComponentReferences, len(r))
	copy(sorted, r)
	sort.Sort(sorted)
	groupID := -1
	for _, ref := range sorted {
		if ref.Input().GroupID != groupID {
			refs = append(refs, ComponentReferences{})
		}
		groupID = ref.Input().GroupID
		refs[len(refs)-1] = append(refs[len(refs)-1], ref)
	}
	return
}

public function build(array $items, $currentUri)
    {
        foreach ($items as $item) {
            if ($item->isDivider()) {
                continue;
            }

            $this->buildItem($item, $currentUri);
        }

        return $items;
    }

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


Question:
// Update can be used to update an ownership with new ownership information. It
// takes into account who is trying to change the ownership values

func (o *Ownership) Update(newownerInfo *Ownership, user *auth.UserInfo) error {
	if user == nil {
		// There is no auth, just copy the whole thing
		*o = *newownerInfo
	} else {
		// Auth is enabled

		// Only the owner, user with access type admin,
		// or admin can change the group
		if user.Username != o.Owner &&
			!o.IsAdminByUser(user) &&
			!o.IsPermitted(user, Ownership_Admin) {
			return status.Error(codes.PermissionDenied,
				"Only owner or those with admin access type can update volume acls")
		}

		// Only the admin can change the owner
		if newownerInfo.HasAnOwner() {
			if o.IsAdminByUser(user) {
				o.Owner = newownerInfo.Owner
			} else {
				return status.Error(codes.PermissionDenied,
					"Only the administrator can change the owner of the resource")
			}
		}
		o.Acls = newownerInfo.GetAcls()
	}
	return nil
}

func (m *ReplicaSetControllerRefManager) ReleaseReplicaSet(replicaSet *apps.ReplicaSet) error {
	klog.V(2).Infof("patching ReplicaSet %s_%s to remove its controllerRef to %s/%s:%s",
		replicaSet.Namespace, replicaSet.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.Controller.GetName())
	deleteOwnerRefPatch := fmt.Sprintf(`{"metadata":{"ownerReferences":[{"$patch":"delete","uid":"%s"}],"uid":"%s"}}`, m.Controller.GetUID(), replicaSet.UID)
	err := m.rsControl.PatchReplicaSet(replicaSet.Namespace, replicaSet.Name, []byte(deleteOwnerRefPatch))
	if err != nil {
		if errors.IsNotFound(err) {
			// If the ReplicaSet no longer exists, ignore it.
			return nil
		}
		if errors.IsInvalid(err) {
			// Invalid error will be returned in two cases: 1. the ReplicaSet
			// has no owner reference, 2. the uid of the ReplicaSet doesn't
			// match, which means the ReplicaSet is deleted and then recreated.
			// In both cases, the error can be ignored.
			return nil
		}
	}
	return err
}

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


Question:
Set filename

@param  mixed $value
@param  bool $overwrite [optional] Default overwrite is true
@param  string $separator [optional] Default separator is an underscore '_'
@return void

public function setFilename($value, $overwrite = true, $separator = '_')
    {
        // recast to string if $value is array
        if (is_array($value)) {
            $value = implode($separator, $value);
        }

        // trim unneeded values
        $value = trim($value, $separator);

        // remove all spaces
        $value = preg_replace('/\s+/', $separator, $value);

        // if value is empty, stop here
        if (empty($value)) {
            return;
        }

        // decode value + lowercase the string
        $value = strtolower($this->decode($value));

        // urlize this part
        $value = Transliterator::urlize($value);

        // overwrite filename or add to filename using a prefix in between
        $this->filename = ($overwrite) ?
            $value : $this->filename . $separator . $value;
    }

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

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

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

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

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

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


Question: // Do mocks base method

func (m *MockHTTPClient) Do(arg0 *http.Request) (*http.Response, error) {
	ret := m.ctrl.Call(m, "Do", arg0)
	ret0, _ := ret[0].(*http.Response)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

public function dispatch(
        MetaboxModel $metabox,
        MetaboxFactory $factory,
        HookFactory $hook
    ) {
        $this->metabox = $metabox;
        $this->factory = $factory;
        $this->hook = $hook;
    }

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


Question:
Deserialize a new InputVenueMessageContent from a given dictionary.

        :return: new InputVenueMessageContent instance.
        :rtype: InputVenueMessageContent

def from_array(array):

        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['latitude'] = float(array.get('latitude'))
        data['longitude'] = float(array.get('longitude'))
        data['title'] = u(array.get('title'))
        data['address'] = u(array.get('address'))
        data['foursquare_id'] = u(array.get('foursquare_id')) if array.get('foursquare_id') is not None else None
        data['foursquare_type'] = u(array.get('foursquare_type')) if array.get('foursquare_type') is not None else None

        instance = InputVenueMessageContent(**data)
        instance._raw = array
        return instance

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_port_type = ET.SubElement(fcoe_intf_list, "fcoe-intf-port-type")
        fcoe_intf_port_type.text = kwargs.pop('fcoe_intf_port_type')

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

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


Question:
Save a modified option.

@since 0.1.0

@param Option $option Option to save.

@return bool Whether saving was successful.

public function save(Option $option): bool
    {
        $key = $option->getKey();

        if (! $this->has($key)) {
            throw UnknownOptionKey::fromKey($key);
        }

        $this->values[$key] = $option->sanitize();

        return $this->persist();
    }

public function permissionSave(Permission $permission)
    {
        if ($permission->permission_id) {
            $query = "
                UPDATE
                    auth_permission
                SET
                    `name` = :name, description = :description, updated_on = " . $this->sql_time_func . "
                WHERE
                    permission_id = :permission_id
            ";
        } else {
            $query = "
                INSERT INTO
                    auth_permission (`name`, description, updated_on, added_on)
                VALUES
                    (:name, :description, " . $this->sql_time_func . ", " . $this->sql_time_func . ")
            ";
        }
        $cur = $this->db->prepare($query);
        $cur->bindParam(":name", $permission->name, PDO::PARAM_STR, 32);
        $cur->bindParam(":description", $permission->description, PDO::PARAM_STR);
        if ($permission->permission_id) {
            $cur->bindParam(":permission_id", $permission->permission_id, PDO::PARAM_INT);
        }
        $this->db->beginTransaction();
        try {
            $cur->execute();
            if (!$permission->permission_id) {
                $permission->permission_id = $this->db->lastInsertId();
            }
            $this->db->commit();
        } catch (PDOException $db_err) {
            $this->db->rollBack();
            if ($this->logger) {
                $this->logger->error("Failed to create/update permission", ['exception' => $db_err]);
            }
            return false;
        }
        return true;
    }

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


Question:
Load HTML document from a string

@param  string  $data
@param  boolean $storeContent
@param  string  $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
@return Zend_Search_Lucene_Document_Html

public static function loadHTML($data, $storeContent = false, $defaultEncoding = '')
    {
        return new Zend_Search_Lucene_Document_Html($data, false, $storeContent, $defaultEncoding);
    }

def set_encoding (parsobj, attrs):

    charset = attrs.get_true('charset', u'')
    if charset:
        # <meta charset="utf-8">
        # eg. in http://cn.dolphin-browser.com/activity/Dolphinjump
        charset = charset.encode('ascii', 'ignore').lower()
    elif attrs.get_true('http-equiv', u'').lower() == u"content-type":
        # <meta http-equiv="content-type" content="text/html;charset="utf-8">
        charset = attrs.get_true('content', u'')
        charset = charset.encode('ascii', 'ignore').lower()
        charset = get_ctype_charset(charset)
    if charset and charset in SUPPORTED_CHARSETS:
        parsobj.encoding = charset

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


Question:
Returns true if the string starts with $pattern.

@param  string  $pattern
@return boolean

public function startsWith($pattern)
  {
    return (substr($this->string, 0, strlen($pattern)) == $pattern) ? TRUE : FALSE;
  }

public static ExecutionPath parse(String pathString) {
        pathString = pathString == null ? "" : pathString;
        pathString = pathString.trim();
        StringTokenizer st = new StringTokenizer(pathString, "/[]", true);
        ExecutionPath path = ExecutionPath.rootPath();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if ("/".equals(token)) {
                assertTrue(st.hasMoreTokens(), mkErrMsg(), pathString);
                path = path.segment(st.nextToken());
            } else if ("[".equals(token)) {
                assertTrue(st.countTokens() >= 2, mkErrMsg(), pathString);
                path = path.segment(Integer.parseInt(st.nextToken()));
                String closingBrace = st.nextToken();
                assertTrue(closingBrace.equals("]"), mkErrMsg(), pathString);
            } else {
                throw new AssertException(format(mkErrMsg(), pathString));
            }
        }
        return path;
    }

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Sysctl.

func (in *Sysctl) DeepCopy() *Sysctl {
	if in == nil {
		return nil
	}
	out := new(Sysctl)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


private void menuFileMenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_menuFileMenuSelected
    final TabTitle title = this.getFocusedTab();
    updateMenuItemsForProvider(title == null ? null : title.getProvider());
  }

public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) {
        int newOps = 0;

        if ((ops & SelectionKey.OP_READ) != 0)
            newOps |= PollArrayWrapper.POLLIN;
        if ((ops & SelectionKey.OP_WRITE) != 0)
            newOps |= PollArrayWrapper.POLLOUT;
        if ((ops & SelectionKey.OP_CONNECT) != 0)
            newOps |= PollArrayWrapper.POLLIN;
        sk.selector.putEventOps(sk, newOps);
    }

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


Question:
//GetClipboardString returns the contents of the system clipboard, if it
//contains or is convertible to a UTF-8 encoded string.
//
//This function may only be called from the main thread. See
//https://code.google.com/p/go-wiki/wiki/LockOSThread

func (w *Window) GetClipboardString() (string, error) {
	cs := C.glfwGetClipboardString(w.data)
	if cs == nil {
		return "", errors.New("Can't get clipboard string.")
	}

	return C.GoString(cs), nil
}

def copy_file(self, path, prefixed_path, source_storage):

        args = (path, prefixed_path, source_storage)
        if settings.threads:
            self.tasks.append(args)
        else:
            self.do_copy_file(args)

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


Question:
Scan and populate {@link HBaseData} collection using scanned results.

@param columnFamily
column family.
@param results
results.
@param scanner
result scanner.
@return collection of scanned results.
@throws IOException

private List<HBaseData> scanResults(final String columnFamily, List<HBaseData> results) throws IOException
    {
        HBaseData data = null;

        if (fetchSize == null)
        {
            for (Result result : scanner)
            {
                List<KeyValue> values = result.list();
                for (KeyValue value : values)
                {
                    data = new HBaseData(columnFamily != null ? columnFamily : new String(value.getFamily()),
                            value.getRow());
                    break;
                }
                data.setColumns(values);
                if (results == null)
                {
                    results = new ArrayList<HBaseData>();
                }
                results.add(data);
            }

            scanner = null;
            resultsIter = null;
        }
        return results;
    }

public static INDArray col2im(INDArray col, int sH, int sW, int ph, int pW, int kH, int kW) {
        if (col.rank() != 6)
            throw new IllegalArgumentException("col2im input array must be rank 6");

        INDArray output = Nd4j.create(col.dataType(), new long[]{col.size(0), col.size(1), kH, kW});

        val cfg = Conv2DConfig.builder()
                .sH(sH)
                .sW(sW)
                .dH(1)
                .dW(1)
                .kH(kH)
                .kW(kW)
                .pH(ph)
                .pW(pW)
                .build();

        Col2Im col2Im = Col2Im.builder()
                .inputArrays(new INDArray[]{col})
                .outputs(new INDArray[]{output})
                .conv2DConfig(cfg)
                .build();

        Nd4j.getExecutioner().execAndReturn(col2Im);
        return col2Im.outputArguments()[0];
    }

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


Question:
Queries to the database to convert the given EPSG SRID to the corresponding Oracle SRID.

@param srid
the EPSG SRID.
@param database
the database instance.
@return the corresponding Oracle SRID.

public static String loadOracleSrid(final String srid, final Database database) {
      final String oracleSrid;
      final JdbcConnection jdbcConnection = (JdbcConnection) database.getConnection();
      final Connection connection = jdbcConnection.getUnderlyingConnection();
      Statement statement = null;
      try {
         statement = connection.createStatement();
         final ResultSet resultSet = statement.executeQuery("SELECT " + EPSG_TO_ORACLE_FUNCTION
               + "(" + srid + ") FROM dual");
         resultSet.next();
         oracleSrid = resultSet.getString(1);
      } catch (final SQLException e) {
         throw new UnexpectedLiquibaseException("Failed to find the Oracle SRID for EPSG:" + srid,
               e);
      } finally {
         try {
            statement.close();
         } catch (final SQLException ignore) {
         }
      }
      return oracleSrid;
   }

def transform_sqlvm_group_output(result):
    '''

    '''
    from collections import OrderedDict
    from msrestazure.tools import parse_resource_id
    try:
        resource_group = getattr(result, 'resource_group', None) or parse_resource_id(result.id)['resource_group']
        wsfc_object = format_wsfc_domain_profile(result.wsfc_domain_profile)
        # Create a dictionary with the relevant parameters
        output = OrderedDict([('id', result.id),
                              ('location', result.location),
                              ('name', result.name),
                              ('provisioningState', result.provisioning_state),
                              ('sqlImageOffer', result.sql_image_offer),
                              ('sqlImageSku', result.sql_image_sku),
                              ('resourceGroup', resource_group),
                              ('wsfcDomainProfile', wsfc_object),
                              ('tags', result.tags)])
        return output
    except AttributeError:
        # Return the response object if the formating fails
        return result

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


Question:
TODO: grab db, ttl, uri from parent
def parent=(a) @parent = a end
def parent(a=nil) @parent = a if a; @parent end

def index(i=nil, &blk)
      @index = i || blk if i || !blk.nil?
      @index ||= Familia.index
      @index
    end

private Node getParent(Node n) {
        if (n.y_s == null) {
            return null;
        }
        Node c = n.y_s;
        if (c.o_c == n) {
            return c;
        }
        Node p1 = c.y_s;
        if (p1 != null && p1.o_c == n) {
            return p1;
        }
        return c;
    }

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


Question:
Get a set of tables and gsis and their configuration keys

    :returns: set -- A set of tuples (table_name, table_conf_key)

def get_tables_and_gsis():

    table_names = set()
    configured_tables = get_configured_tables()
    not_used_tables = set(configured_tables)

    # Add regexp table names
    for table_instance in list_tables():
        for key_name in configured_tables:
            try:
                if re.match(key_name, table_instance.table_name):
                    logger.debug("Table {0} match with config key {1}".format(
                        table_instance.table_name, key_name))

                    # Notify users about regexps that match multiple tables
                    if table_instance.table_name in [x[0] for x in table_names]:
                        logger.warning(
                            'Table {0} matches more than one regexp in config, '
                            'skipping this match: "{1}"'.format(
                                table_instance.table_name, key_name))
                    else:
                        table_names.add(
                            (
                                table_instance.table_name,
                                key_name
                            ))
                        not_used_tables.discard(key_name)
                else:
                    logger.debug(
                        "Table {0} did not match with config key {1}".format(
                            table_instance.table_name, key_name))
            except re.error:
                logger.error('Invalid regular expression: "{0}"'.format(
                    key_name))
                sys.exit(1)

    if not_used_tables:
        logger.warning(
            'No tables matching the following configured '
            'tables found: {0}'.format(', '.join(not_used_tables)))

    return sorted(table_names)

def search(query, team=None):

    if team is None:
        team = _find_logged_in_team()

    if team is not None:
        session = _get_session(team)
        response = session.get("%s/api/search/" % get_registry_url(team), params=dict(q=query))
        print("* Packages in team %s" % team)
        packages = response.json()['packages']
        for pkg in packages:
            print(("%s:" % team) + ("%(owner)s/%(name)s" % pkg))
        if len(packages) == 0:
            print("(No results)")
        print("* Packages in public cloud")

    public_session = _get_session(None)
    response = public_session.get("%s/api/search/" % get_registry_url(None), params=dict(q=query))
    packages = response.json()['packages']
    for pkg in packages:
        print("%(owner)s/%(name)s" % pkg)
    if len(packages) == 0:
        print("(No results)")

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


Question: Get an array of channels in the site.

public function channels()
    {
        $url = $this->getURL('channels');

        $headers = [
            'body' => [
                'private' => $this->privateKey
            ]
        ];

        $response = $this->processRequest($url, $headers, 'get');

        return $response;
    }

protected function getMatchedSiteAccess()
    {
        if (isset($this->matchedSiteAccess)) {
            return $this->matchedSiteAccess;
        }

        preg_match(
            "@{$this->regex}@",
            $this->element,
            $match
        );

        $this->matchedSiteAccess = isset($match[$this->itemNumber]) ? $match[$this->itemNumber] : false;

        return $this->matchedSiteAccess;
    }

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


Question:
Returns list of locale formats for ISO formatting.

@param string|null $locale current locale used if null

@return array

public function getIsoFormats($locale = null)
    {
        return [
            'LT' => $this->getTranslationMessage('formats.LT', $locale, 'h:mm A'),
            'LTS' => $this->getTranslationMessage('formats.LTS', $locale, 'h:mm:ss A'),
            'L' => $this->getTranslationMessage('formats.L', $locale, 'MM/DD/YYYY'),
            'LL' => $this->getTranslationMessage('formats.LL', $locale, 'MMMM D, YYYY'),
            'LLL' => $this->getTranslationMessage('formats.LLL', $locale, 'MMMM D, YYYY h:mm A'),
            'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'),
        ];
    }

protected function buildPostTypeData($singular, $plural, $args)
    {
        $singular = ucwords($singular);
        $plural   = ucwords($plural);

        $labels = [
            'name'               => __($plural, LARAPRESS_TEXTDOMAIN),
            'singular_name'      => __($singular, LARAPRESS_TEXTDOMAIN),
            'add_new'            => __('Add New', LARAPRESS_TEXTDOMAIN),
            'add_new_item'       => __('Add New ' . $singular, LARAPRESS_TEXTDOMAIN),
            'edit_item'          => __('Edit ' . $singular, LARAPRESS_TEXTDOMAIN),
            'new_item'           => __('New ' . $singular, LARAPRESS_TEXTDOMAIN),
            'all_items'          => __('All ' . $plural, LARAPRESS_TEXTDOMAIN),
            'view_item'          => __('View ' . $singular, LARAPRESS_TEXTDOMAIN),
            'search_items'       => __('Search ' . $singular, LARAPRESS_TEXTDOMAIN),
            'not_found'          => __('No ' . strtolower($singular) . ' found', LARAPRESS_TEXTDOMAIN),
            'not_found_in_trash' => __('No ' . strtolower($singular) . ' found in trash', LARAPRESS_TEXTDOMAIN),
            'parent_item_colon'  => '',
            'menu_name'          => __($plural, LARAPRESS_TEXTDOMAIN)
        ];

        return array_merge(
            [
                'label'         => __($plural, LARAPRESS_TEXTDOMAIN),
                'labels'        => $labels,
                'description'   => '',
                'public'        => true,
                'menu_position' => 20,
                'has_archive'   => true
            ],
            $args
        );
    }

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


Question:
Executes analysis module for integer underflow and integer overflow.

        :param state: Statespace to analyse
        :return: Found issues

def execute(self, state: GlobalState):

        address = _get_address_from_state(state)
        has_overflow = self._overflow_cache.get(address, False)
        has_underflow = self._underflow_cache.get(address, False)
        if has_overflow or has_underflow:
            return
        opcode = state.get_current_instruction()["opcode"]
        funcs = {
            "ADD": [self._handle_add],
            "SUB": [self._handle_sub],
            "MUL": [self._handle_mul],
            "SSTORE": [self._handle_sstore],
            "JUMPI": [self._handle_jumpi],
            "RETURN": [self._handle_return, self._handle_transaction_end],
            "STOP": [self._handle_transaction_end],
            "EXP": [self._handle_exp],
        }
        for func in funcs[opcode]:
            func(state)

protected function _checkPaymentStatus( $value )
	{
		$temp = (int) $value;

		if( $temp < MShop_Order_Item_Abstract::PAY_UNFINISHED || $temp > MShop_Order_Item_Abstract::PAY_RECEIVED ) {
			throw new MShop_Order_Exception( sprintf( 'Order payment status "%1$s" not within allowed range', $value ) );
		}
	}

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


Question:
Returns values for authentication related special attributes.

@param ServerRequestInterface $request PSR7 Request object
@param string                 $name    Attribute Name

@return array Array of attribute values

public function getAttributeByName(Request $request, string $name): array
    {
        $matches = \array_filter($this->getReleasedAttributes($request), function ($key) use ($name) {
            return \strtoupper($name) == \strtoupper($key);
        }, ARRAY_FILTER_USE_KEY);
        if (empty($matches)) {
            return [];
        } else {
            return \current($matches);
        }
    }

private function set_iri($iri)
    {
        static $cache;
        if (!$cache)
        {
            $cache = array();
        }

        if ($iri === null)
        {
            return true;
        }
        elseif (isset($cache[$iri]))
        {
            list($this->scheme,
                 $this->iuserinfo,
                 $this->ihost,
                 $this->port,
                 $this->ipath,
                 $this->iquery,
                 $this->ifragment,
                 $return) = $cache[$iri];
            return $return;
        }
        else
        {
            $parsed = $this->parse_iri((string) $iri);

            $return = $this->set_scheme($parsed['scheme'])
                && $this->set_authority($parsed['authority'])
                && $this->set_path($parsed['path'])
                && $this->set_query($parsed['query'])
                && $this->set_fragment($parsed['fragment']);

            $cache[$iri] = array($this->scheme,
                                 $this->iuserinfo,
                                 $this->ihost,
                                 $this->port,
                                 $this->ipath,
                                 $this->iquery,
                                 $this->ifragment,
                                 $return);
            return $return;
        }
    }

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


Question:
Adds a new menu item at the given item.

        :param      newItem | <QTreeWidgetItem>
                    atItem  | <QTreeWidgetItem>

def addMenuItem( self, newItem, atItem ):

        tree = self.uiMenuTREE

        if ( not atItem ):
            tree.addTopLevelItem(newItem)

        elif ( atItem.data(0, Qt.UserRole) == 'menu' ):
            atItem.addChild(newItem)

        elif ( atItem.parent() ):
            index = atItem.parent().indexOfChild(atItem)
            atItem.parent().insertChild(index + 1, newItem)

        else:
            index = tree.indexOfTopLevelItem(atItem)
            tree.insertTopLevelItem(index + 1, newItem)

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

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


Question:
Register the install command class.

@return void

protected function registerInstallCommand()
    {
        $this->app->singleton('command.appinstall', function (Container $app) {
            $events = $app['events'];

            return new AppInstall($events);
        });
    }

func (cfg *centOSCloudConfig) AddPackageCommands(
	packageProxySettings proxy.Settings,
	packageMirror string,
	addUpdateScripts bool,
	addUpgradeScripts bool,
) {
	addPackageCommandsCommon(
		cfg,
		packageProxySettings,
		packageMirror,
		addUpdateScripts,
		addUpgradeScripts,
		cfg.series,
	)
}

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


Question:
Sets the discriminator maps on AbstractCharacteristics entity mappings.

@param LoadClassMetadataEventArgs $eventArgs

public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $metadata = $eventArgs->getClassMetadata();

        if ($metadata->getName() === self::ROOT_CHARACTERISTICS_CLASS) {
            $metadata->setDiscriminatorMap($this->characteristicsClassesMap);
        }
    }

public static function create($adapter, array $config = []): self
    {
        if (!isset(self::$adapterMap[$adapter])) {
            throw new DriverNotFoundException(sprintf(
                'Adapter "%s" not found. You should use one of: %s',
                $adapter,
                implode(', ', self::$adapterMap)
            ));
        }

        $class = self::$adapterMap[$adapter];

        return new self(new $class($config));
    }

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


Question: Converts an ISO 8601 time zone into the number of minutes offset from UTC

function normalizeIso8601TimeZone(value) {
    if (value === 'Z') {
      return 0;
    }

    var regex = /^([+-])(\d\d):?(\d\d)$/;
    var matches = regex.exec(value);
    if (matches === null) {
      return NaN;
    } else {
      var multiplicationFactor = (matches[1] === '+') ? 1 : -1;
      var hour = parseInt(matches[2], 10);
      var minute = parseInt(matches[3], 10);

      return multiplicationFactor * ((hour * 60) + minute);
    }
  }

def CopyToDateTimeString(self):

    if (self._timestamp is None or self._timestamp < self._INT64_MIN or
        self._timestamp > self._INT64_MAX):
      return None

    return super(JavaTime, self).CopyToDateTimeString()

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


Question:
// Add will add the data to the Bloom filter. It returns the filter to allow
// for chaining.

func (c *CountingBloomFilter) Add(data []byte) Filter {
	lower, upper := hashKernel(data, c.hash)

	// Set the K bits.
	for i := uint(0); i < c.k; i++ {
		c.buckets.Increment((uint(lower)+uint(upper)*i)%c.m, 1)
	}

	c.count++
	return c
}

def append(self, node):
        """"""
        if node.parent == self.key and not self.elapsed_time:
            self.children.append(node)
        else:
            # Recursive call
            for child in self.children:
                if not child.elapsed_time:
                    child.append(node)

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