Question: This function takes the url parameters and uses them to populate a Filter object

public static Filter populateFilter(final EntityManager entityManager, final Map<String, String> paramMap, final String filterName,
            final String tagPrefix, final String groupTagPrefix, final String categoryInternalPrefix, final String categoryExternalPrefix,
            final String localePrefix, final IFieldFilter fieldFilter) {
        // attempt to get the filter id from the url
        Integer filterId = null;
        if (paramMap.containsKey(filterName)) {
            final String filterQueryParam = paramMap.get(filterName);

            try {
                filterId = Integer.parseInt(filterQueryParam);
            } catch (final Exception ex) {
                // filter value was not an integer
                filterId = null;

                log.debug("The filter ID URL query parameter was not an integer. Got " + filterQueryParam + ". Probably a malformed URL.",
                        ex);
            }
        }

        Filter filter = null;

        /* First attempt to populate the filter from a filterID variable */
        if (filterId != null) {
            filter = entityManager.find(Filter.class, filterId);
        }

        /* If that fails, use the other URL params */
        if (filter == null) {
            filter = new Filter();

            for (final String key : paramMap.keySet()) {
                final boolean tagVar = tagPrefix != null && key.startsWith(tagPrefix);
                final boolean groupTagVar = groupTagPrefix != null && key.startsWith(groupTagPrefix);
                final boolean catIntVar = categoryInternalPrefix != null && key.startsWith(categoryInternalPrefix);
                final boolean catExtVar = categoryExternalPrefix != null && key.startsWith(categoryExternalPrefix);
                final boolean localeVar = localePrefix != null && key.matches("^" + localePrefix + "\\d*$");
                final String state = paramMap.get(key);

                // add the filter category states
                if (catIntVar || catExtVar) {
                    /*
                     * get the category and project id data from the variable name
                     */
                    final String catProjDetails = catIntVar ? key.replaceFirst(categoryInternalPrefix, "") : key.replaceFirst(
                            categoryExternalPrefix, "");
                    // split the category and project id out of the data
                    final String[] catProjID = catProjDetails.split("-");

                    /*
                     * some validity checks. make sure we have one or two strings after the split.
                     */
                    if (catProjID.length != 1 && catProjID.length != 2) continue;

                    // try to get the category and project ids
                    Integer catID = null;
                    Integer projID = null;
                    try {
                        catID = Integer.parseInt(catProjID[0]);

                        /*
                         * if the array has just one element, we have only specified the category. in this case the project is
                         * the common project
                         */
                        if (catProjID.length == 2) projID = Integer.parseInt(catProjID[1]);
                    } catch (final Exception ex) {
                        log.debug("Was expecting an integer. Got " + catProjID[0] + ". Probably a malformed URL.", ex);
                        continue;
                    }

                    // at this point we have found a url variable that
                    // contains a catgeory and project id

                    final Category category = entityManager.find(Category.class, catID);
                    final Project project = projID != null ? entityManager.find(Project.class, projID) : null;

                    Integer dbState;

                    if (catIntVar) {
                        if (state.equals(CommonFilterConstants.AND_LOGIC)) dbState = CommonFilterConstants.CATEGORY_INTERNAL_AND_STATE;
                        else dbState = CommonFilterConstants.CATEGORY_INTERNAL_OR_STATE;
                    } else {
                        if (state.equals(CommonFilterConstants.AND_LOGIC)) dbState = CommonFilterConstants.CATEGORY_EXTERNAL_AND_STATE;
                        else dbState = CommonFilterConstants.CATEGORY_EXTERNAL_OR_STATE;
                    }

                    final FilterCategory filterCategory = new FilterCategory();
                    filterCategory.setFilter(filter);
                    filterCategory.setProject(project);
                    filterCategory.setCategory(category);
                    filterCategory.setCategoryState(dbState);

                    filter.getFilterCategories().add(filterCategory);
                }

                // add the filter tag states
                else if (tagVar) {
                    try {
                        final Integer tagId = Integer.parseInt(key.replaceFirst(tagPrefix, ""));
                        final Integer intState = Integer.parseInt(state);

                        // get the Tag object that the tag id represents
                        final Tag tag = entityManager.getReference(Tag.class, tagId);

                        if (tag != null) {
                            final FilterTag filterTag = new FilterTag();
                            filterTag.setTag(tag);
                            filterTag.setTagState(intState);
                            filterTag.setFilter(filter);
                            filter.getFilterTags().add(filterTag);
                        }
                    } catch (final Exception ex) {
                        log.debug("Probably an invalid tag query parameter. Parameter: " + key + " Value: " + state, ex);
                    }
                } else if (groupTagVar) {
                    final Integer tagId = Integer.parseInt(key.replaceFirst(groupTagPrefix, ""));
                    // final Integer intState = Integer.parseInt(state);

                    // get the Tag object that the tag id represents
                    final Tag tag = entityManager.getReference(Tag.class, tagId);

                    if (tag != null) {
                        final FilterTag filterTag = new FilterTag();
                        filterTag.setTag(tag);
                        filterTag.setTagState(CommonFilterConstants.GROUP_TAG_STATE);
                        filterTag.setFilter(filter);
                        filter.getFilterTags().add(filterTag);
                    }
                } else if (localeVar) {
                    try {
                        final String localeName = state.replaceAll("\\d", "");
                        final Integer intState = Integer.parseInt(state.replaceAll("[^\\d]", ""));

                        final FilterLocale filterLocale = new FilterLocale();
                        filterLocale.setLocaleName(localeName);
                        filterLocale.setLocaleState(intState);
                        filterLocale.setFilter(filter);
                        filter.getFilterLocales().add(filterLocale);
                    } catch (final Exception ex) {
                        log.debug("Probably an invalid locale query parameter. Parameter: " + key + " Value: " + state, ex);
                    }
                }

                // add the filter field states
                else {
                    if (fieldFilter.hasFieldName(key)) {
                        final FilterField filterField = new FilterField();
                        filterField.setFilter(filter);
                        filterField.setField(key);
                        filterField.setValue(state);
                        filterField.setDescription(fieldFilter.getFieldDesc(key));
                        filter.getFilterFields().add(filterField);
                    }
                }

            }

        }

        return filter;
    }

func NewCompareFilter(compareOp CompareType, comparatorObj Comparator) *CompareFilter {
	op := pb.CompareType(compareOp)
	obj, err := comparatorObj.ConstructPBComparator()
	if err != nil {
		panic(err)
	}
	return &CompareFilter{
		CompareOp:  &op,
		Comparator: obj,
	}
}

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


Question: Lint the verilog code.

def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
    """"""

    exit_code = SCons(project_dir).lint({
        'all': all,
        'top': top,
        'nostyle': nostyle,
        'nowarn': nowarn,
        'warn': warn
    })
    ctx.exit(exit_code)

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

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


Question: // Updates *astPtr to point to a deep clone of what it originally pointed at.

func clone(astPtr *Node) {
	node := *astPtr
	if node == nil {
		return
	}

	switch node := node.(type) {
	case *Apply:
		r := new(Apply)
		*astPtr = r
		*r = *node
		clone(&r.Target)
		r.Arguments.Positional = append(make(Nodes, 0), r.Arguments.Positional...)
		for i := range r.Arguments.Positional {
			clone(&r.Arguments.Positional[i])
		}
		r.Arguments.Named = append(make([]NamedArgument, 0), r.Arguments.Named...)
		for i := range r.Arguments.Named {
			clone(&r.Arguments.Named[i].Arg)
		}

	case *ApplyBrace:
		r := new(ApplyBrace)
		*astPtr = r
		*r = *node
		clone(&r.Left)
		clone(&r.Right)

	case *Array:
		r := new(Array)
		*astPtr = r
		*r = *node
		r.Elements = append(make(Nodes, 0), r.Elements...)
		for i := range r.Elements {
			clone(&r.Elements[i])
		}

	case *ArrayComp:
		r := new(ArrayComp)
		*astPtr = r
		*r = *node
		clone(&r.Body)
		cloneForSpec(&r.Spec)

	case *Assert:
		r := new(Assert)
		*astPtr = r
		*r = *node
		clone(&r.Cond)
		clone(&r.Message)
		clone(&r.Rest)

	case *Binary:
		r := new(Binary)
		*astPtr = r
		*r = *node
		clone(&r.Left)
		clone(&r.Right)

	case *Conditional:
		r := new(Conditional)
		*astPtr = r
		*r = *node
		clone(&r.Cond)
		clone(&r.BranchTrue)
		clone(&r.BranchFalse)

	case *Dollar:
		r := new(Dollar)
		*astPtr = r
		*r = *node

	case *Error:
		r := new(Error)
		*astPtr = r
		*r = *node
		clone(&r.Expr)

	case *Function:
		r := new(Function)
		*astPtr = r
		*r = *node
		cloneParameters(&r.Parameters)
		clone(&r.Body)

	case *Import:
		r := new(Import)
		*astPtr = r
		*r = *node
		r.File = new(LiteralString)
		*r.File = *node.File

	case *ImportStr:
		r := new(ImportStr)
		*astPtr = r
		*r = *node
		r.File = new(LiteralString)
		*r.File = *node.File

	case *Index:
		r := new(Index)
		*astPtr = r
		*r = *node
		clone(&r.Target)
		clone(&r.Index)

	case *Slice:
		r := new(Slice)
		*astPtr = r
		*r = *node
		clone(&r.Target)
		clone(&r.BeginIndex)
		clone(&r.EndIndex)
		clone(&r.Step)

	case *Local:
		r := new(Local)
		*astPtr = r
		*r = *node
		r.Binds = append(make(LocalBinds, 0), r.Binds...)
		for i := range r.Binds {
			if r.Binds[i].Fun != nil {
				r.Binds[i].Fun = Clone(r.Binds[i].Fun).(*Function)
			}
			clone(&r.Binds[i].Body)
		}
		clone(&r.Body)

	case *LiteralBoolean:
		r := new(LiteralBoolean)
		*astPtr = r
		*r = *node

	case *LiteralNull:
		r := new(LiteralNull)
		*astPtr = r
		*r = *node

	case *LiteralNumber:
		r := new(LiteralNumber)
		*astPtr = r
		*r = *node

	case *LiteralString:
		r := new(LiteralString)
		*astPtr = r
		*r = *node

	case *Object:
		r := new(Object)
		*astPtr = r
		*r = *node
		r.Fields = append(make(ObjectFields, 0), r.Fields...)
		for i := range r.Fields {
			cloneField(&r.Fields[i])
		}

	case *DesugaredObject:
		r := new(DesugaredObject)
		*astPtr = r
		*r = *node
		r.Fields = append(make(DesugaredObjectFields, 0), r.Fields...)
		for i := range r.Fields {
			cloneDesugaredField(&r.Fields[i])
		}

	case *ObjectComp:
		r := new(ObjectComp)
		*astPtr = r
		*r = *node
		r.Fields = append(make(ObjectFields, 0), r.Fields...)
		for i := range r.Fields {
			cloneField(&r.Fields[i])
		}
		cloneForSpec(&r.Spec)

	case *Parens:
		r := new(Parens)
		*astPtr = r
		*r = *node
		clone(&r.Inner)

	case *Self:
		r := new(Self)
		*astPtr = r
		*r = *node

	case *SuperIndex:
		r := new(SuperIndex)
		*astPtr = r
		*r = *node
		clone(&r.Index)

	case *InSuper:
		r := new(InSuper)
		*astPtr = r
		*r = *node
		clone(&r.Index)

	case *Unary:
		r := new(Unary)
		*astPtr = r
		*r = *node
		clone(&r.Expr)

	case *Var:
		r := new(Var)
		*astPtr = r
		*r = *node

	default:
		panic(fmt.Sprintf("ast.Clone() does not recognize ast: %s", reflect.TypeOf(node)))
	}

	cloneNodeBase(*astPtr)
}

def fill_taxid2asscs(taxid2asscs_usr, taxid2asscs_ret):
        """"""
        for taxid, ab_ret in taxid2asscs_ret.items():
            taxid2asscs_usr[taxid]['ID2GOs'] = ab_ret['ID2GOs']
            taxid2asscs_usr[taxid]['GO2IDs'] = ab_ret['GO2IDs']

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


Question:
Add or Replace a list of synonyms

@param rules the list of rules to add/replace

public JSONObject batchRules(List<JSONObject> rules) throws AlgoliaException {
    return batchRules(rules, false, false);
  }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
@param array            $container
@param Constraint[]     $constraints
@param GetterMetadata[] $getters

@return void

public function composeValidationData(&$container, $constraints, $getters)
    {
        if (null == $container) {
            $container = array();
        }
        if ($getters) {
            if (!isset($container['getters'])) {
                $container['getters'] = array();
            }
            $container['getters'] = array_merge($container['getters'], $this->parseGetters($getters));
        }
        if ($constraints) {
            if (!isset($container['constraints'])) {
                $container['constraints'] = array();
            }
            $container['constraints'] = array_merge($container['constraints'], $this->parseConstraints($constraints));
        }
    }

func (s *CustomizedScalingMetricSpecification) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CustomizedScalingMetricSpecification"}
	if s.MetricName == nil {
		invalidParams.Add(request.NewErrParamRequired("MetricName"))
	}
	if s.Namespace == nil {
		invalidParams.Add(request.NewErrParamRequired("Namespace"))
	}
	if s.Statistic == nil {
		invalidParams.Add(request.NewErrParamRequired("Statistic"))
	}
	if s.Dimensions != nil {
		for i, v := range s.Dimensions {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Dimensions", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

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


Question: callbacks from Liqpay server

def update
      @payment_method = PaymentMethod.find params[:payment_method_id]
      data = JSON.parse Base64.strict_decode64 params[:data]
      render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature]
      @order = Order.find data['order_id']

      raise ArgumentError unless @order.payments.completed.empty? &&
        data['currency'] == @order.currency &&
        BigDecimal(data['amount']) == @order.total &&
        data['type'] == 'buy' &&
        (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox'))

      payment = @order.payments.create amount: @order.total, payment_method: @payment_method
      payment.complete!

      render text: "Thank you.\n"
    end

public function setCreditCard(CreditCard $creditCard)
    {
        $creditCard->setContext(Moip::PAYMENT);
        $this->data->fundingInstrument->method = self::METHOD_CREDIT_CARD;
        $this->data->fundingInstrument->creditCard = $creditCard->getData();
        //$this->setCreditCardHolder($holder);

        return $this;
    }

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


Question:
Return total search result count
@return count

public function searchCount( Form $form, SearchCriteriaBuilder $searchCriteriaBuilder, $params = array() ) {

        $criteria = $searchCriteriaBuilder->build($form, 0, 0, $params);

        $searchResults = $this->repository->getSearchService()->findContent( $criteria );

        return $searchResults->totalCount;
    }

def seek(value,type = :relative)
      command = case type
      when :percent then "seek #{value} 1"
      when :absolute then "seek #{value} 2"
      else "seek #{value} 0"
      end
      resp = command command, /Position/
      resp.gsub("Position: ","").gsub(" %\n","")
    end

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


Question:
Creates a function from the provided source code and closure object.

@param {(string|string[])} code
@param {Object} closure
@returns {string[]}

function compile(code, closure) {
  code = providePlugins(isolateScope(code, closure)).join('\n');
  try {
    return vm.runInThisContext('(' + code + ')').apply({}, values(plugins));
  } catch (err) {
    throw new Meteor.Error(400, err);
  }
}

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:
Report all nodes in an array with a given message.
@param {ASTNode[]} nodes Nodes.
@param {string} messageId Message id to display.
@param {boolean} fix `true` if the directive should be fixed (i.e. removed)
@returns {void}

function reportAll(nodes, messageId, fix) {
            reportSlice(nodes, 0, nodes.length, messageId, fix);
        }

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

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


Question:
Load all previously persisted objects from disk.

@return array A list of objects of type $className

private function loadAllObjects(): array
    {
        if (!file_exists($this->databaseFilePath)) {
            return [];
        }

        $objects = Serializer::deserialize("{$this->className}[]", file_get_contents($this->databaseFilePath));

        Assertion::allIsInstanceOf($objects, $this->className);

        return $objects;
    }

private static Constructor<?> getPersistenceStoreConstructor(Class<?> theClass, Class<?>[] interfaces) throws Exception {
        Constructor<?> constructor = null;
        for (Class<?> interfaceClass : interfaces) {
            try {
                constructor = theClass.getConstructor(new Class[] { interfaceClass });
            } catch (NoSuchMethodException err) {
                // Ignore this error
            }
            if (constructor != null) {
                break;
            }
            constructor = getPersistenceStoreConstructor(theClass, interfaceClass.getInterfaces());
            if (constructor != null) {
                break;
            }
        }
        return constructor;
    }

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


Question:
Create a Flysystem instance with the given adapter.

@param  AdapterInterface $adapter
@param  array $config
@return FlysystemInterface

protected function createFlysystem( AdapterInterface $adapter, array $config )
	{
		$config = Arr::only( $config, ['visibility'] );

		return new Flysystem( $adapter, count( $config ) > 0 ? $config : null );
	}

private function load_command_config_file($file, $prefix) {

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

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

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

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

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

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

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

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


Question:
当Swoole server关闭时
当Task遇到致命错误时

@throws \ReflectionException

public function shutdown() {
        //!\nb\Server::$o ||
        if(Debug::driver()->synchronous() && !Pool::get('\swoole\http\Request')) {
            return;
        }
        //有错记错
        $e = error_get_last();
        if($e) {
            l('shutdown:'.$e['message'],'err');
            $e = new \ErrorException($e['message'], $e['type'], $e['type'], $e['file'], $e['line']);
            //是否为同步进程,非同步，即为task进程
            if(Debug::driver()->synchronous()) {
                $this->dowith($e,true);
                Pool::get('\swoole\http\Response')->end(ob_get_contents());
                ob_end_clean();
            }
            else {
                $this->dowith($e);
            }
        }
        Debug::end();
        Pool::destroy();
    }

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

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

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


Question: More complex HTTP query.

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

public function handleRequest($parent, $upstream)
    {
        $req = $this->beginRequest($parent, $upstream);
        return $req ?: $parent;
    }

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


@Override
	public ShapeStyle create(GeometryEditService editService, GeometryIndex index)
			throws GeometryIndexNotFoundException {
		if (index == null) {
			return findGeometryStyle(editService, index);
		}
		switch (editService.getIndexService().getType(index)) {
			case TYPE_VERTEX:
				return findVertexStyle(editService, index);
			case TYPE_EDGE:
				return findEdgeStyle(editService, index);
			default:
				return findGeometryStyle(editService, index);
		}
	}

@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.


Question:
Force failure (e.g. when a test is not completely implemented
@param {String} optMsg optional message to add to the failure description

function (optMsg) {
                var msg = "Forced Failure";
                if (optMsg) {
                    msg += " (" + optMsg + ")";
                }

                this.raiseFailure(msg);

                // raise an exception to stop subsequent assertions
                throw {
                    name : this.ASSERT_FAILURE,
                    message : msg
                };
            }

private function validate()
    {
        if (!array_key_exists('type', $this->properties)) {
            throw new StatusException(sprintf('Key %s in %s missing', 'type', __CLASS__), 100, null);
        }

        $type = $this->properties['type'];

        // the type specified must be valid
        if (!in_array($this->properties['type'], $this->types)) {
            throw new StatusException('The type specified is invalid', 100, null);
        }

        switch ($type) {
            case StatusInterface::TYPE_INITIAL:
            case StatusInterface::TYPE_EXCEPTION:
                $mandatoryKeys = ['name'];
                break;

            default:
                $mandatoryKeys = ['name', 'transitions_from', 'transitions_to'];
                break;
        }

        foreach ($mandatoryKeys as $key) {
            if (!array_key_exists($key, $this->properties)) {
                throw new StatusException(sprintf('Key %s in %s missing', $key, __CLASS__), 100, null);
            }
        }

        if (StatusInterface::TYPE_INITIAL != $type && StatusInterface::TYPE_EXCEPTION != $type) {
            $keysMustBeArray = ['transitions_from', 'transitions_to'];
            foreach ($keysMustBeArray as $key) {
                if (!is_array($this->properties[$key])) {
                    throw new StatusException(sprintf('Key %s is not an array', $key), 100, null);
                }
            }
        }
    }

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


Question:
// ParseParamNameModifierAndPostFix parses a full parameter key and returns the parameter name,
// modifier, and postfix components.  For example, "foo:bar.baz" would return ["foo","bar","baz"].

func ParseParamNameModifierAndPostFix(fullParam string) (param string, modifier string, postfix string) {
	param = fullParam
	if strings.Contains(fullParam, ".") {
		split := strings.SplitN(fullParam, ".", 2)
		param = split[0]
		postfix = split[1]
	}
	if strings.Contains(param, ":") {
		split := strings.SplitN(param, ":", 2)
		param = split[0]
		modifier = split[1]
	}
	return
}

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question:
Queues the avatar to be updated.

@param avatar The avatar to set.
@param fileType The type of the avatar, e.g. "png" or "jpg".
@return The current instance in order to chain call methods.

public WebhookUpdater setAvatar(InputStream avatar, String fileType) {
        delegate.setAvatar(avatar, fileType);
        return this;
    }

def add_topic(request, forum_slug=None):

    forum = Forum.objects.get(slug=forum_slug)
    form  = AddTopicForm(request.POST or None, request.FILES or None, initial={'forum': forum})

    current_time   = time.time()
    user           = request.user

    if form.is_valid():
        instance = form.save(commit=False)
        instance.forum           = forum
        instance.name            = strip_tags(instance.name)
        instance.slug            = slugify(instance.name)
        instance.user            = user
        instance.author          = user.display_name
        instance.lastpost_author = user.display_name
        instance.created_int     = current_time
        instance.modified_int    = current_time
        instance.save()

        # and now add the child post
        post = Post(
            topic            = instance,
            text             = request.POST['text'],
            user             = user,
            post_date_int    = current_time
        )
        if request.FILES:
            post.image = request.FILES['image']
        post.save()

        return HttpResponseRedirect("/forum/%s/?new_topic=%s" % (forum_slug, instance.id))

    return render(request, 'fretboard/add_edit.html', {
        'form': form,
        'form_title': 'Add a topic',
        'FORUM_BASE_NAME': FORUM_BASE_NAME
    })

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


Question: 対象オフセット位置にあるActionPushデータを置換.

def repl_action_push_string(swf, do_action_offset, action_push_offset, str, parent_sprite_offset = nil)
      swf.force_encoding("ASCII-8BIT") if swf.respond_to? :force_encoding
      str.force_encoding("ASCII-8BIT") if str.respond_to? :force_encoding
      record_header = swf[do_action_offset, 2].unpack("v").first
      # tag check
      raise ReplaceTargetError if (record_header >> 6) & 1023 != 12
      # action check
      raise ReplaceTargetError if swf[action_push_offset].chr.unpack("C").first != 0x96
      raise ReplaceTargetError if swf[action_push_offset + 3].chr.unpack("C").first != 0
      # error for short header (not implemented yet.)
      raise ReplaceTargetError if record_header & 63 < 63
      # calc length
      do_action_len = swf[do_action_offset+2, 4].unpack("i").first # without recordheader
      action_push_len = swf[action_push_offset+1, 2].unpack("v").first
      org_str_length = action_push_len - 2 # data type & terminated null
      delta_str_length = str.length - org_str_length
      # replace string and rewrite length
      swf[action_push_offset+4, org_str_length] = str
      swf[action_push_offset+1, 2] = [action_push_len + delta_str_length].pack("v")
      swf[do_action_offset+2, 4] = [do_action_len + delta_str_length].pack("V")
      if parent_sprite_offset
        swf[parent_sprite_offset+2, 4] = [swf[parent_sprite_offset+2, 4].unpack("V").first + delta_str_length].pack("V")
      end
      swf[4, 4] = [swf[4, 4].unpack("V").first + delta_str_length].pack("V")
      swf
    end

def execute_action_list(obj, target, kw):
    """"""
    env = obj.get_build_env()
    kw = obj.get_kw(kw)
    status = 0
    for act in obj.get_action_list():
        args = ([], [], env)
        status = act(*args, **kw)
        if isinstance(status, SCons.Errors.BuildError):
            status.executor = obj
            raise status
        elif status:
            msg = "Error %s" % status
            raise SCons.Errors.BuildError(
                errstr=msg,
                node=obj.batches[0].targets,
                executor=obj,
                action=act)
    return status

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


Question:
Perform two point gesture from edge to center(in) or center to edge(out).
        Usages:
        d().pinch.In(percent=100, steps=10)
        d().pinch.Out(percent=100, steps=100)

def pinch(self):
        '''

        '''
        @param_to_property(in_or_out=["In", "Out"])
        def _pinch(in_or_out="Out", percent=100, steps=50):
            if in_or_out in ["Out", "out"]:
                return self.jsonrpc.pinchOut(self.selector, percent, steps)
            elif in_or_out in ["In", "in"]:
                return self.jsonrpc.pinchIn(self.selector, percent, steps)
        return _pinch

def average_percentage_of_new_providers(providers_info, providers_count):

    segments_percentages = {}
    all_projects_percentages = []
    providers_count = providers_count.to_dict()[0]

    for _, items in providers_info.groupby('PRONAC'):
        cnpj_array = items['nrCNPJCPF'].unique()
        new_providers = 0
        for cnpj in cnpj_array:
            cnpj_count = providers_count.get(cnpj, 0)
            if cnpj_count <= 1:
                new_providers += 1

        segment_id = items.iloc[0]['idSegmento']
        new_providers_percent = new_providers / cnpj_array.size
        segments_percentages.setdefault(segment_id, [])
        segments_percentages[segment_id].append(new_providers_percent)
        all_projects_percentages.append(new_providers_percent)

    segments_average_percentage = {}
    for segment_id, percentages in segments_percentages.items():
        mean = np.mean(percentages)
        segments_average_percentage[segment_id] = mean

    return pd.DataFrame.from_dict({
        'segments_average_percentage': segments_average_percentage,
        'all_projects_average': np.mean(all_projects_percentages)
    })

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


Question: given an absolute URI, calculate the relative URI

function relativeURI(uri, base) {

    // reduce base and uri strings to just their difference string
    var baseParts = base.split('/');
    baseParts.pop();
    base = baseParts.join('/') + '/';
    i = 0;
    while (base.substr(i, 1) == uri.substr(i, 1))
      i++;
    while (base.substr(i, 1) != '/')
      i--;
    base = base.substr(i + 1);
    uri = uri.substr(i + 1);

    // each base folder difference is thus a backtrack
    baseParts = base.split('/');
    var uriParts = uri.split('/');
    out = '';
    while (baseParts.shift())
      out += '../';

    // finally add uri parts
    while (curPart = uriParts.shift())
      out += curPart + '/';

    return out.substr(0, out.length - 1);
  }

public function getRelativeFileTarget($aspectKernelTarget) {
        return fphp\Helper\Path::join(fphp\Helper\Path::rootPath(dirname($aspectKernelTarget)),
                                      $this->fileSpecification->getTarget());
    }

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


Question:
Sends a new blocking notification that can not be removed by the user.<p>

@param type the notification type
@param message the message

@return the message, use to hide the message

public CmsNotificationMessage sendBusy(Type type, final String message) {

        CmsNotificationMessage notificationMessage = new CmsNotificationMessage(Mode.BUSY, type, message);
        m_messages.add(notificationMessage);
        if (hasWidget()) {
            m_widget.addMessage(notificationMessage);
        }
        return notificationMessage;
    }

private function addHtmlMessage($type, $html = null, $css_selector = null)
    {
        return $this->add($type, array(
            'value' => $html,
            'selector' => $css_selector,
        ));
    }

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


Question:
/*
CreateDB creates a sqlite3 db at provided DBPath.
It will create Table with the name provided during Configure(),
so multiple key-val can be kept isolated at same db-path.
Create fixed fields FieldKey and FieldValue for key-name and key-value in it.
*/

func (sqlite3 *Sqlite3DB) CreateDB() {
	var errDB error
	sqlite3.GolDB, errDB = sql.Open("sqlite3", sqlite3.DBPath)
	if errDB != nil {
		errMsg := fmt.Sprintf("DB %s Creation failed. %q", sqlite3.DBPath, errDB)
		golerror.Boohoo(errMsg, true)
	}
	sqlStmt := fmt.Sprintf("create table IF NOT EXISTS %s (FieldKey text not null primary key, FieldValue text); delete from %s;", sqlite3.TableName, sqlite3.TableName)
	_, errDB = sqlite3.GolDB.Exec(sqlStmt)
	if errDB != nil {
		golerror.Boohoo(errDB.Error(), true)
		return
	}
}

def persist(conditions = nil)
      run_callbacks(:save) do
        self.hash_key = SecureRandom.uuid if hash_key.blank?

        # Add an exists check to prevent overwriting existing records with new ones
        if new_record?
          conditions ||= {}
          (conditions[:unless_exists] ||= []) << self.class.hash_key
        end

        # Add an optimistic locking check if the lock_version column exists
        if self.class.attributes[:lock_version]
          conditions ||= {}
          self.lock_version = (lock_version || 0) + 1
          # Uses the original lock_version value from ActiveModel::Dirty in case user changed lock_version manually
          (conditions[:if] ||= {})[:lock_version] = changes[:lock_version][0] if changes[:lock_version][0]
        end

        attributes_dumped = Dumping.dump_attributes(attributes, self.class.attributes)

        begin
          Dynamoid.adapter.write(self.class.table_name, attributes_dumped, conditions)
          @new_record = false
          true
        rescue Dynamoid::Errors::ConditionalCheckFailedException => e
          if new_record?
            raise Dynamoid::Errors::RecordNotUnique.new(e, self)
          else
            raise Dynamoid::Errors::StaleObjectError.new(self, 'persist')
          end
        end
      end
    end

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


Question:
" b-tree search method
        " param: ip

def btreeSearch(self, ip):

        if not ip.isdigit(): ip = self.ip2Long(ip)

        if len(self.__headerSip) < 1:
            #pass the super block
            self.__f.seek(8)
            #read the header block
            b = self.__f.read(8192)
            #parse the header block
            sip = None
            ptr = None
            for i in range(0, len(b)-1, 8):
                sip = self.getLong(b, i)
                ptr = self.getLong(b, i+4)
                if ptr == 0:
                    break
                self.__headerSip.append(sip)
                self.__headerPtr.append(ptr)

        headerLen = len(self.__headerSip) - 1
        l, h, sptr, eptr = (0, headerLen, 0, 0)
        while l <= h:
            m = int((l+h)/2)

            if ip == self.__headerSip[m]:
                if m > 0:
                    sptr = self.__headerPtr[m-1]
                    eptr = self.__headerPtr[m]
                    break;
                else:
                    sptr = self.__headerPtr[m]
                    eptr = self.__headerPtr[m+1]
                    break;

            if ip > self.__headerSip[m]:
                if m == headerLen:
                    sptr = self.__headerPtr[m-1]
                    eptr = self.__headerPtr[m]
                    break;
                elif ip < self.__headerSip[m+1]:
                    sptr = self.__headerPtr[m]
                    eptr = self.__headerPtr[m+1]
                    break;

                l = m + 1
            else:
                if m == 0:
                    sptr = self.__headerPtr[m]
                    eptr = self.__headerPtr[m+1]
                    break;
                elif ip > self.__headerSip[m-1]:
                    sptr = self.__headerPtr[m-1]
                    eptr = self.__headerPtr[m]
                    break;

                h = m - 1

        if sptr == 0: return "N1"

        indexLen = eptr - sptr
        self.__f.seek(sptr)
        b = self.__f.read(indexLen + 12)

        l, h, mixPtr = (0, int(indexLen/12), 0)
        while l <= h:
            m = int((l+h)/2)
            offset = m * 12

            if ip >= self.getLong(b, offset):
                if ip > self.getLong(b, offset+4):
                    l = m + 1
                else:
                    mixPtr = self.getLong(b, offset+8)
                    break;
            else:
                h = m - 1

        if mixPtr == 0: return "N2"

        return self.returnData(mixPtr)

def find_by_text(text, _connection=None, page_size=100, page_number=0,
        sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):

        return connection.ItemResultSet('find_videos_by_text',
            Video, _connection, page_size, page_number, sort_by, sort_order,
            text=text)

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


Question:
Import root-paragraph from its node

@param   DOMElement  $paragraphNode
@param   ZipArchive  $zip
@param   array       $paragraphIdMap
@param   array       $domains
@param   string      $dbSchema
@return  int

protected function importRootParagraph( DOMElement $paragraphNode,
                                            ZipArchive $zip,
                                            array &$paragraphIdMap,
                                            array $domains,
                                            $dbSchema )
    {
        return $this->saveParagraphStructure(
            $this->loadParagraphStructure(
                $paragraphNode,
                $zip,
                $domains,
                $dbSchema
            ),
            $paragraphIdMap
        );
    }

function parse (buffer, doc, options, key) {
  switch (doc.type) {
    case 'text':
      return [...buffer, doc.content]
    case 'tag': {
      let children = reactify(doc.children, options, key)
      if (!children.length) {
        children = null
      }
      if (doc.name.startsWith(COMMENT_TAG)) {
        return [...buffer, ...children]
      }
      const tag = options.mappings[doc.name] || DEFAULT_TAG
      if (tag.fromMarkup) {
        doc.attrs = tag.fromMarkup(doc.attrs)
      }
      if (tag === DEFAULT_TAG && !doc.attrs.as) {
        doc.attrs.as = doc.name
      }
      if (doc.attrs.class) {
        // Rename class to className for React compatibility
        doc.attrs.className = doc.attrs.class
        delete doc.attrs.class
      }
      return [...buffer, createElement(tag, { key, ...doc.attrs }, children)]
    }
    default:
      return buffer
  }
}

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


Question:
If not already created, a new version element will be created and returned.
Otherwise, the first existing version element will be returned.
@return the instance defined for the element version

public Version<Attributes<T>> getOrCreateVersion()
   {
      List<Node> nodeList = childNode.get("version");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new VersionImpl<Attributes<T>>(this, "version", childNode, nodeList.get(0));
      }
      return createVersion();
   }

def smooth(self):

        smooth = self._element.smooth
        if smooth is None:
            return True
        return smooth.val

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


Question: // WriteTo encode and write a row of data to the writer

func (row Row) WriteTo(writer io.Writer) (err error) {
	encoded, err := encodeRow(row)
	if err != nil {
		return fmt.Errorf("WriteTo encoding error: %v", err)
	}
	return WriteMessage(writer, encoded)
}

@Override
	public void open(int taskNumber, int numTasks) throws IOException {
		super.open(taskNumber, numTasks);
		this.wrt = this.charsetName == null ? new OutputStreamWriter(new BufferedOutputStream(this.stream, 4096)) :
				new OutputStreamWriter(new BufferedOutputStream(this.stream, 4096), this.charsetName);
	}

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


Question:
\
    Returns the TAG kind.

    `tag`
        A string.
    `default`
        A value to return if the TAG kind is unknown
        (set to ``constants.TAG_KIND_UNKNOWN`` by default)

def tag_kind(tag, default=consts.TAG_KIND_UNKNOWN):

    if len(tag) == 2:
        return consts.TAG_KIND_GEO
    if u',' in tag:
        return consts.TAG_KIND_PERSON
    if tag[0] in u'Kk' and len(tag) == 4:
        return consts.TAG_KIND_PROGRAM
    t = tag.upper()
    if t in _TAGS_SUBJECT:
        return consts.TAG_KIND_SUBJECT
    if t in _TAGS_ORG:
        return consts.TAG_KIND_ORG
    return default

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

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


Question:
dropIndex

@param string $name
@param bool   $ifExists
@param bool   $concurrently

@return string

public static function dropIndex($name, $ifExists = false, $concurrently = false)
    {
        $query = static::getQuery();

        return static::build(
            'DROP INDEX',
            $concurrently ? 'CONCURRENTLY' : null,
            $ifExists ? 'IF EXISTS' : null,
            $query->quoteName($name)
        );
    }

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:
Returns the value for this form field,
supports nesting via HTML array.
@return string

public function getLoadValue()
    {
        if ($this->formField->value !== null) {
            return $this->formField->value;
        }

        $defaultValue = !$this->model->exists
            ? $this->formField->getDefaultFromData($this->data ?: $this->model)
            : null;

        return $this->formField->getValueFromData($this->data ?: $this->model, $defaultValue);
    }

function yy_r114(){
    if (preg_match('~^true$~i', $this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = 'true';
    } elseif (preg_match('~^false$~i', $this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = 'false';
    } elseif (preg_match('~^null$~i', $this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = 'null';
    } else {
        $this->_retvalue = "'".$this->yystack[$this->yyidx + 0]->minor."'";
    }
    }

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


Question:
Acquire a new graftm Package

        Parameters
        ----------
        graftm_output_path: str
            path to base directory of graftm

def acquire(graftm_package_path):
        '''
        '''

        contents_hash = json.load(
                                   open(
                                        os.path.join(
                                                     graftm_package_path,
                                                     GraftMPackage._CONTENTS_FILE_NAME
                                                     ),
                                         )
                                   )

        v=contents_hash[GraftMPackage.VERSION_KEY]
        logging.debug("Loading version %i GraftM package: %s" % (v, graftm_package_path))
        if v == 2:
            pkg = GraftMPackageVersion2()
        elif v == 3:
            pkg = GraftMPackageVersion3()
        else:
            raise InsufficientGraftMPackageException("Bad version: %s" % v)

        pkg._contents_hash = contents_hash
        pkg._base_directory = graftm_package_path
        # check we are at current version otherwise choke
        pkg.check_universal_keys(v)
        pkg.check_required_keys(GraftMPackage._REQUIRED_KEYS[str(v)])
        return pkg

function(srcpath, destpath, options) {
        // Destpath is optional.
        if (typeof destpath !== 'string') {
          options = destpath;
          destpath = srcpath;
        }
        // Ensure srcpath is absolute.
        if (!grunt.file.isPathAbsolute(srcpath)) {
          srcpath = init.srcpath(srcpath);
        }
        // Use placeholder file if no src exists.
        if (!srcpath) {
          srcpath = helpers.getFile('misc/placeholder');
        }
        grunt.verbose.or.write('Writing ' + destpath + '...');
        try {
          grunt.file.copy(srcpath, init.destpath(destpath), options);
          grunt.verbose.or.ok();
        } catch(e) {
          grunt.verbose.or.error().error(e);
          throw e;
        }
      }

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


Question:
Summarise executor information from computers array.

@param {Array} computers: computers array, part of Jenkins#computer result
@return executor summary object

function executorSummary(computers) {

  var data = {};

  computers.forEach(function (computer) {

    var idleCount   = 0;
    var activeCount = 0;

    data[computer.displayName] = { executors: [] };

    computer.executors.forEach(function (executor) {
      data[computer.displayName].executors.push({
        idle: executor.idle,
        stuck: executor.likelyStuck,
        progress: executor.progress,
        name: (!executor.idle && executor.currentExecutable.url) ?
          executor.currentExecutable.url.replace(/.*\/job\//, '').replace(/\/.*/, '') :
          undefined
      });

      if (executor.idle) {
        idleCount += 1;
      } else {
        activeCount += 1;
      }
    });

    var summary = [];
    if (activeCount > 0) {
      summary.push(text.__('%d active', activeCount));
    }
    if (idleCount > 0) {
      summary.push(text.__('%d idle', idleCount));
    }

    data[computer.displayName].summary = summary.join(', ');
  });

  return data;
}

private boolean iterate(Production production) {
	List<Construction> constructions = production.getConstructions();
	boolean changed = false;
	/*
	 * Search production for non-terminals...
	 */
	for (int i = 0; i < constructions.size(); i++) {
	    Construction construction = constructions.get(i);
	    if (construction.isTerminal()) {
		continue;
	    }
	    Set<Terminal> followSet = follow.get(construction.getName());
	    if (followSet == null) {
		continue;
	    }
	    int startSize = followSet.size();
	    /*
	     * For the found non-terminal find the following constructions by first sets.
	     */
	    if (i < constructions.size() - 1) {
		for (int j = i + 1; j < constructions.size(); j++) {
		    Construction followingConstruction = constructions.get(j);
		    Set<Terminal> firstSet = first.get(followingConstruction);
		    if (firstSet == null) {
			continue;
		    }
		    for (Terminal follower : firstSet) {
			if (!follower.equals(EmptyTerminal.getInstance())) {
			    followSet.add(follower);
			}
		    }
		    if (!firstSet.contains(EmptyTerminal.getInstance())) {
			break;
		    }
		    if (j == constructions.size() - 1) {
			followSet.addAll(follow.get(production.getName()));
		    }
		}
	    } else {
		followSet.addAll(follow.get(production.getName()));
	    }
	    if (startSize < followSet.size()) {
		changed = true;
	    }
	}
	return changed;
    }

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


Question:
read a sparse matrix, loading row and column name files. if
        specified, will add a prefix to the row or column names

def read(self, filename, rowprefix=None, colprefix=None, delim=":"):
        """"""

        self.matrix = scipy.io.mmread(filename)
        with open(filename + ".rownames") as in_handle:
            self.rownames = [x.strip() for x in in_handle]
            if rowprefix:
                self.rownames = [rowprefix + delim + x for x in self.rownames]
        with open(filename + ".colnames") as in_handle:
            self.colnames = [x.strip() for x in in_handle]
            if colprefix:
                self.colnames = [colprefix + delim + x for x in self.colnames]

def _init_nt_hdr(self, line):
        """"""
        line = line.replace('.', '_')
        line = line.replace(' ', '_')
        line = line.replace('#', 'N')
        line = line.replace('-', '_')
        line = line.replace('"', '')
        #line = re.sub(r"_$", r"", line)
        hdrs = re.split(self.sep, line)
        if '' in hdrs:
            hdrs = NCBIgeneFileReader.replace_nulls(hdrs)
        # Init indexes which will be converted to int or float
        self.idxs_int = [idx for idx, hdr in enumerate(hdrs) if hdr in self.int_hdrs]
        self.idxs_float = [idx for idx, hdr in enumerate(hdrs) if hdr in self.float_hdrs]
        assert hdrs[6] == 'Aliases'
        return namedtuple('ntncbi', ' '.join(hdrs))

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


Question: // SetArn sets the Arn field's value.

func (s *VPCEConfiguration) SetArn(v string) *VPCEConfiguration {
	s.Arn = &v
	return s
}

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

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

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


Question: + "the default is Boolean.FALSE.", new LiteralPhrase(Boolean.FALSE));

public Formula getFormula() {
		Reagent[] reagents = new Reagent[] {KEY, VALUE, PARENT, EXPRESSION};
		final Formula rslt = new SimpleFormula(getClass(), reagents);
		return rslt;
	}

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:
Get a valid SRID value from a prj file.
If the the prj file
- is null,
- doesn't contain a valid srid code,
- is empty     *
then a default srid equals to 0 is added.

@param connection
@param prjFile
@return
@throws SQLException
@throws IOException

public static int getValidSRID(Connection connection, File prjFile) throws SQLException, IOException {
        int srid = getSRID(prjFile);
        if(!isSRIDValid(srid, connection)){
            srid = 0;
        }
        return srid;
    }

def classify_identifier(did):

    if _is_unused_did(did):
        return 'unused on this Member Node'
    elif is_sid(did):
        return 'a Series ID (SID) of a revision chain'
    elif is_local_replica(did):
        return 'a Persistent ID (PID) of a local replica'
    elif is_unprocessed_local_replica(did):
        return (
            'a Persistent ID (PID) of an accepted but not yet processed local replica'
        )
    elif is_archived(did):
        return 'a Persistent ID (PID) of a previously archived local object'
    elif is_obsoleted(did):
        return 'a Persistent ID (PID) of a previously updated (obsoleted) local object'
    elif is_resource_map_db(did):
        return 'a Persistent ID (PID) of a local resource map'
    elif is_existing_object(did):
        return 'a Persistent ID (PID) of an existing local object'
    elif is_revision_chain_placeholder(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing revision of a local '
            'replica'
        )
    elif is_resource_map_member(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing object aggregated in '
            'a local Resource Map'
        )
    logger.warning('Unable to classify known identifier. did="{}"'.format(did))
    return '<UNKNOWN>'

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


Question:
Deletes the commerce tier price entry from the database. Also notifies the appropriate model listeners.

@param commerceTierPriceEntry the commerce tier price entry
@return the commerce tier price entry that was removed
@throws PortalException

@Indexable(type = IndexableType.DELETE)
	@Override
	public CommerceTierPriceEntry deleteCommerceTierPriceEntry(
		CommerceTierPriceEntry commerceTierPriceEntry)
		throws PortalException {
		return commerceTierPriceEntryPersistence.remove(commerceTierPriceEntry);
	}

private function loadCartLinePrices(CartLineInterface $cartLine)
    {
        $purchasable = $cartLine->getPurchasable();
        $purchasablePrice = $purchasable->getPrice();

        /**
         * If present, reducedPrice will be used as purchasable price in current CartLine.
         */
        if ($purchasable->getReducedPrice()->getAmount() > 0) {
            $purchasablePrice = $purchasable->getReducedPrice();
        }

        /**
         * Setting amounts for current CartLine.
         *
         * Line Currency was set by CartManager::addPurchasable when factorizing CartLine
         */
        $cartLine->setPurchasableAmount($purchasablePrice);
        $cartLine->setAmount($purchasablePrice->multiply($cartLine->getQuantity()));

        return $cartLine;
    }

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


Question:
returns API with all CRUD methods scoped to id prefix

@param  {String}   prefix   String all ID’s are implicitly prefixed or
expected to be prefixed with.

function withIdPrefix (state, prefix) {
  var emitter = new EventEmitter()

  var api = {
    add: require('./add').bind(null, state, prefix),
    find: require('./find').bind(null, state, prefix),
    findAll: require('./find-all').bind(null, state, prefix),
    findOrAdd: require('./find-or-add').bind(null, state, prefix),
    update: require('./update').bind(null, state, prefix),
    updateOrAdd: require('./update-or-add').bind(null, state, prefix),
    updateAll: require('./update-all').bind(null, state, prefix),
    remove: require('./remove').bind(null, state, prefix),
    removeAll: require('./remove-all').bind(null, state, prefix),
    withIdPrefix: function (moarPrefix) {
      return withIdPrefix(state, prefix + moarPrefix)
    }
  }

  var prefixState = {
    api: api,
    isListening: false,
    parentEmitter: state.emitter,
    emitter: emitter
  }

  api.on = require('./on').bind(null, prefixState)
  api.one = require('./one').bind(null, prefixState)
  api.off = require('./off').bind(null, prefixState)

  prefixEventHandler(prefix, prefixState)

  return api
}

def logs_handle_job(job_uuid: str,
                    job_name: str,
                    log_lines: Optional[Union[str, Iterable[str]]],
                    temp: bool = True) -> None:
    """"""
    handle_job_logs(job_uuid=job_uuid,
                    job_name=job_name,
                    log_lines=log_lines,
                    temp=temp)

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


Question: Initialize data from a 2-D numpy matrix.

def __init_from_np2d(self, mat, params_str, ref_dataset):
        """"""
        if len(mat.shape) != 2:
            raise ValueError('Input numpy.ndarray must be 2 dimensional')

        self.handle = ctypes.c_void_p()
        if mat.dtype == np.float32 or mat.dtype == np.float64:
            data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
        else:
            # change non-float data to float data, need to copy
            data = np.array(mat.reshape(mat.size), dtype=np.float32)

        ptr_data, type_ptr_data, _ = c_float_array(data)
        _safe_call(_LIB.LGBM_DatasetCreateFromMat(
            ptr_data,
            ctypes.c_int(type_ptr_data),
            ctypes.c_int(mat.shape[0]),
            ctypes.c_int(mat.shape[1]),
            ctypes.c_int(C_API_IS_ROW_MAJOR),
            c_str(params_str),
            ref_dataset,
            ctypes.byref(self.handle)))
        return self

def init_file(self, filename, lines, expected, line_offset):
        """"""
        super(_PycodestyleReport, self).init_file(
            filename, lines, expected, line_offset)
        self.errors = []

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


Question: // NewUniterAPIV11 creates an instance of the V11 uniter API.

func NewUniterAPIV11(context facade.Context) (*UniterAPIV11, error) {
	uniterAPI, err := NewUniterAPI(context)
	if err != nil {
		return nil, err
	}
	authorizer := context.Auth()
	st := context.State()
	resources := context.Resources()
	accessUnit := unitAccessor(authorizer, st)
	return &UniterAPIV11{
		LXDProfileAPI: NewExternalLXDProfileAPI(st, resources, authorizer, accessUnit, logger),
		UniterAPI:     *uniterAPI,
	}, nil
}

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

	return &bee
}

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


Question:
See Also: searchResponse()

        Args:
          queryType:
          query:
          vendorSpecific:
          **kwargs:

        Returns:

def search(self, queryType, query=None, vendorSpecific=None, **kwargs):

        response = self.searchResponse(queryType, query, vendorSpecific, **kwargs)
        return self._read_dataone_type_response(response, 'ObjectList')

def signature(self):
        """"""
        if not use_signature:
            raise NotImplementedError("Python 3 only.")

        if self.static:
            parameters = \
                (Parameter(name='cls',
                           kind=Parameter.POSITIONAL_ONLY),)

        else:
            parameters = \
                (Parameter(name='self',
                           kind=Parameter.POSITIONAL_ONLY),)

        if self.input_transform:
            return signature(self.input_transform)

        if self.uses_request:
            fields = get_fields(self.request_type)
            if not self.static:
                if self.field_name not in fields:
                    raise NameError("field '{}' not found in {}".format(
                        self.field_name, self.request_name))
                fields.remove(self.field_name)
            parameters += tuple(
                Parameter(name=name, kind=Parameter.POSITIONAL_OR_KEYWORD,
                          default=None)
                for name in fields)

        return Signature(parameters)

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


Question:
Get the raw data array for this message. The format of this varies from gateway to
gateway, but will usually be either an associative array, or a SimpleXMLElement.

@return array

public function getData()
    {
        if ($this->getAppleReference() !== null) {
            $this->validate('amount', 'appleReference');

            $data = [
                'opcode'      => 4,
                'product_id'  => $this->getProductId(),
                'apple_token' => urlencode(base64_encode(json_encode($this->getAppleReference()))),
                'token'       => $this->getRequestToken(),
            ];
        } elseif ($this->getCardReference() !== null) {
            $this->validate(
                'amount',
                'card',
                'cardReference',
                'transactionId',
                'clientIp',
                'returnUrl'
            );

            $data = [
                'opcode'      => 21,
                'product_id'  => $this->getProductId(),
                'payment_id'  => $this->getCardReference(),
                'amount'      => $this->getAmount(),
                'cf'          => $this->getTransactionId(),
                'ip_address'  => $this->getClientIp(),
                'cvv'         => $this->getCard()->getCvv(),
                'pp_identity' => 'card',
                'token'       => $this->getRequestToken(),
            ];
        } else {
            $this->validate(
                'amount',
                'card',
                'transactionId',
                'clientIp',
                'returnUrl'
            );

            $card = $this->getCard();

            $card->validate();

            $data = [
                'opcode'      => 0,
                'product_id'  => $this->getProductId(),
                'amount'      => $this->getAmount(),
                'cf'          => $this->getTransactionId(),
                'ip_address'  => $this->getClientIp(),
                'pan'         => $card->getNumber(),
                'cardholder'  => $card->getName(),
                'exp_month'   => $card->getExpiryMonth(),
                'exp_year'    => $card->getExpiryYear(),
                'cvv'         => $card->getCvv(),
                'pp_identity' => 'card',
                'token'       => $this->getRequestToken(),
            ];
        }

        if ($this->getPhone()) {
            $data['phone'] = $this->getPhone();
        }
        if ($this->getCf2()) {
            $data['cf2'] = $this->getCf2();
        }
        if ($this->getCf3()) {
            $data['cf3'] = $this->getCf3();
        }
        if ($this->getCallbackUrl()) {
            $data['cb_url'] = $this->getCallbackUrl();
        }

        return $data;
    }

function ( xhr, type ) {
		type = type || "";
		var result, obj;

		if ( ( regex.json_maybe.test( type ) || string.isEmpty( type ) ) && ( regex.json_wrap.test( xhr.responseText ) && Boolean( obj = json.decode( xhr.responseText, true ) ) ) ) {
			result = obj;
		}
		else if ( regex.xml.test( type ) ) {
			if ( type !== "text/xml" ) {
				xhr.overrideMimeType( "text/xml" );
			}

			result = xhr.responseXML;
		}
		else if ( type === "text/plain" && regex.is_xml.test( xhr.responseText) && xml.valid( xhr.responseText ) ) {
			result = xml.decode( xhr.responseText );
		}
		else {
			result = xhr.responseText;
		}

		return result;
	}

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


Question:
// HasHeader checks if a block header is present in the database or not, caching
// it if present.

func (lc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
	return lc.hc.HasHeader(hash, number)
}

public static function UrlExsist ($url, $timeout = 30, $protocol_version = self::VERSION_1_1) {
		$result = static::HeadRequest($url, $timeout, $protocol_version);
		return isset($result['http']['status']['code']) && $result['http']['status']['code'] !== '404';
	}

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


Question: // node join the cluster

func joinCluster(d *Daemon, w http.ResponseWriter, r *http.Request) *HttpErr {
	if r.URL.RawQuery == "" {
		return &HttpErr{http.StatusBadRequest, "address missing"}
	}

	kvs, err := url.ParseQuery(r.URL.RawQuery)

	if err != nil {
		return &HttpErr{http.StatusBadRequest, "parse query string error"}
	}

	addr, ok := kvs["address"]

	if !ok || addr[0] == "" {
		return &HttpErr{http.StatusBadRequest, "address parameter not exist"}
	}

	log.Println("Join to cluster", addr[0])

	d.clusterChan <- &NodeCtx{addr[0], nodeJoin}
	return nil
}

func (c *cNode) updated(pos uint32, br branch, gen *generation) *cNode {
	array := make([]branch, len(c.array))
	copy(array, c.array)
	array[pos] = br
	ncn := &cNode{bmp: c.bmp, array: array, gen: gen}
	return ncn
}

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


Question:
@param $header

@return array

public function nplurals_and_expression_from_header($header)
    {
        if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s+plural\s*=\s*(.+)$/', $header, $matches)) {
            $nplurals = (int) $matches[1];
            $expression = trim($matches[2]);

            return array($nplurals, $expression);
        } else {
            return array(2, 'n != 1');
        }
    }

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question: representing different versions, because then you have uncertainty on which configuration file is really used

private void createChameleonMarkerFile(Path parent) throws IOException {
        final Path chameleon = parent.resolve("chameleonrunner");
        Files.write(chameleon, "Chameleon Runner was there".getBytes());
    }

def save_config(self):
        """"""
        self.config_section['match_fuzzy'] = self.model_completer.match_fuzzy
        self.config_section['enable_vi_bindings'] = self.enable_vi_bindings
        self.config_section['show_completion_columns'] = \
            self.show_completion_columns
        self.config_section['show_help'] = self.show_help
        self.config_section['theme'] = self.theme
        self.config_obj.write()

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


Question:
Renames a datastore

    datastore_ref
        vim.Datastore reference to the datastore object to be changed

    new_datastore_name
        New datastore name

def rename_datastore(datastore_ref, new_datastore_name):
    '''

    '''
    ds_name = get_managed_object_name(datastore_ref)
    log.trace("Renaming datastore '%s' to '%s'", ds_name, new_datastore_name)
    try:
        datastore_ref.RenameDatastore(new_datastore_name)
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(
            'Not enough permissions. Required privilege: '
            '{}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareRuntimeError(exc.msg)

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)

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


Question:
/*
(non-Javadoc)

@see com.impetus.kundera.persistence.api.Batcher#executeBatch()

@Override
    public int executeBatch()
    {

        Map<Key, List<TableOperation>> operations = new HashMap<Key, List<TableOperation>>();
        for (Node node : nodes)
        {
            if (node.isDirty())
            {
                node.handlePreEvent();
                // delete can not be executed in batch
                if (node.isInState(RemovedState.class))
                {
                    delete(node.getData(), node.getEntityId());
                }
                else
                {
                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            node.getDataClass());
                    List<RelationHolder> relationHolders = getRelationHolders(node);
                    // KunderaCoreUtils.showQuery("Execute batch for" +
                    // metadata.getSchema() + "." + metadata.getTableName(),
                    // showQuery);
                    Row row = createRow(metadata, node.getData(), node.getEntityId(), relationHolders);

                    Table schemaTable = tableAPI.getTable(metadata.getTableName());

                    addOps(operations, schemaTable, row);
                }
                node.handlePostEvent();
            }
        }

        execute(operations);
        return nodes.size();
    }

public String serviceName_quota_PUT(String serviceName, Long quota) throws IOException {
		String qPath = "/metrics/{serviceName}/quota";
		StringBuilder sb = path(qPath, serviceName);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "quota", quota);
		String resp = exec(qPath, "PUT", sb.toString(), o);
		return convertTo(resp, String.class);
	}

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


Question:
Refreshed a Country by Country Instance
@param Country $country
@return Ad

public function refreshCountry(Country $country)
    {

        $refreshedCountry = $this->findCountryBy(array('id' => $country->getId()));
        if (null === $refreshedCountry) {
            throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $country->getId()));
        }
        return $refreshedCountry;
    }

def parse_data_to_internal(self, data=None):

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

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


Question:
Configures and returns the SplitEvaluator and Classifier instance as tuple.

        :return: evaluator and classifier
        :rtype: tuple

def configure_splitevaluator(self):

        if self.classification:
            speval = javabridge.make_instance("weka/experiment/ClassifierSplitEvaluator", "()V")
        else:
            speval = javabridge.make_instance("weka/experiment/RegressionSplitEvaluator", "()V")
        classifier = javabridge.call(speval, "getClassifier", "()Lweka/classifiers/Classifier;")
        return speval, classifier

public void setFileName() {
        String type = "";
        // lenskit does not provide a factorizer class. This check is to actually see if it's a Mahout or Lenskit SVD.
        if (properties.containsKey(RecommendationRunner.FACTORIZER) || properties.containsKey(RecommendationRunner.SIMILARITY)) {
            if (properties.containsKey(RecommendationRunner.FACTORIZER)) {
                type = properties.getProperty(RecommendationRunner.FACTORIZER);
            } else {
                type = properties.getProperty(RecommendationRunner.SIMILARITY);
            }
            type = type.substring(type.lastIndexOf(".") + 1) + ".";
        }
        String num = "";
        if (properties.containsKey(RecommendationRunner.FACTORS) || properties.containsKey(RecommendationRunner.NEIGHBORHOOD)) {
            if (properties.containsKey(RecommendationRunner.FACTORS)) {
                num = properties.getProperty(RecommendationRunner.FACTORS);
            } else {
                num = properties.getProperty(RecommendationRunner.NEIGHBORHOOD);
            }
            num += ".";
        }

        String trainingSet = properties.getProperty(RecommendationRunner.TRAINING_SET);
        trainingSet = trainingSet.substring(trainingSet.lastIndexOf("/") + 1, trainingSet.lastIndexOf("_train"));

        fileName = trainingSet + "."
                + properties.getProperty(RecommendationRunner.FRAMEWORK) + "."
                + properties.getProperty(RecommendationRunner.RECOMMENDER).substring(properties.getProperty(RecommendationRunner.RECOMMENDER).lastIndexOf(".") + 1) + "."
                + type
                + num
                + "tsv";

        System.out.println(fileName);
    }

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


Question:
Pprint the missing files of each given set.

        :param set missing_pys: The set of missing Python files.
        :param set missing_docs: The set of missing documentation files.
        :rtype: None

def pprint_tree_differences(self, missing_pys, missing_docs):

        if missing_pys:
            print('The following Python files appear to be missing:')
            for pyfile in missing_pys:
                print(pyfile)
            print('\n')

        if missing_docs:
            print('The following documentation files appear to be missing:')
            for docfiile in missing_docs:
                print(docfiile)
            print('\n')

def datalab(line, cell=None):

  parser = google.datalab.utils.commands.CommandParser(
      prog='%datalab',
      description="""
Execute operations that apply to multiple Datalab APIs.

Use "%datalab <command> -h" for help on a specific command.
""")

  config_parser = parser.subcommand(
      'config', help='List or set API-specific configurations.')
  config_sub_commands = config_parser.add_subparsers(dest='command')

  # %%datalab config list
  config_list_parser = config_sub_commands.add_parser(
      'list', help='List configurations')
  config_list_parser.set_defaults(func=_config_list_fn)

  # %%datalab config set -n <NAME> -v <VALUE>
  config_set_parser = config_sub_commands.add_parser(
      'set', help='Set configurations')
  config_set_parser.add_argument(
      '-n', '--name',
      help='The name of the configuration value', required=True)
  config_set_parser.add_argument(
      '-v', '--value', help='The value to set', required=True)
  config_set_parser.set_defaults(func=_config_set_fn)

  project_parser = parser.subcommand(
      'project', help='Get or set the default project ID')
  project_sub_commands = project_parser.add_subparsers(dest='command')

  # %%datalab project get
  project_get_parser = project_sub_commands.add_parser(
      'get', help='Get the default project ID')
  project_get_parser.set_defaults(func=_project_get_fn)

  # %%datalab project set -p <PROJECT_ID>
  project_set_parser = project_sub_commands.add_parser(
      'set', help='Set the default project ID')
  project_set_parser.add_argument(
      '-p', '--project', help='The default project ID', required=True)
  project_set_parser.set_defaults(func=_project_set_fn)

  return google.datalab.utils.commands.handle_magic_line(line, cell, parser)

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


Question:
Prepare options for the widget.

@param array      $arrIds       List of ids.
@param IAttribute $objAttribute The metamodel attribute.

@return array

protected function prepareWidgetOptions($arrIds, $objAttribute)
    {
        $arrOptions = $objAttribute->getFilterOptions(
            ($this->get('onlypossible') ? $arrIds : null),
            (bool) $this->get('onlyused')
        );

        // Remove empty values from list.
        foreach ($arrOptions as $mixKeyOption => $mixOption) {
            // Remove html/php tags.
            $mixOption = \strip_tags($mixOption);
            $mixOption = \trim($mixOption);

            if ($mixOption === '' || $mixOption === null) {
                unset($arrOptions[$mixKeyOption]);
            }
        }

        return $arrOptions;
    }

function _fillMissingFields(attrs) {
  var attr;
  for(var i = 0; i < attrs.length; ++i) {
    attr = attrs[i];

    // populate missing name
    if(typeof(attr.name) === 'undefined') {
      if(attr.type && attr.type in pki.oids) {
        attr.name = pki.oids[attr.type];
      } else if(attr.shortName && attr.shortName in _shortNames) {
        attr.name = pki.oids[_shortNames[attr.shortName]];
      }
    }

    // populate missing type (OID)
    if(typeof(attr.type) === 'undefined') {
      if(attr.name && attr.name in pki.oids) {
        attr.type = pki.oids[attr.name];
      } else {
        var error = new Error('Attribute type not specified.');
        error.attribute = attr;
        throw error;
      }
    }

    // populate missing shortname
    if(typeof(attr.shortName) === 'undefined') {
      if(attr.name && attr.name in _shortNames) {
        attr.shortName = _shortNames[attr.name];
      }
    }

    if(typeof(attr.value) === 'undefined') {
      var error = new Error('Attribute value not specified.');
      error.attribute = attr;
      throw error;
    }
  }
}

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


Question:
Merge all LIGO_LW elements that are immediate children of elem by
	appending their children to the first.

def merge_ligolws(elem):

	ligolws = [child for child in elem.childNodes if child.tagName == ligolw.LIGO_LW.tagName]
	if ligolws:
		dest = ligolws.pop(0)
		for src in ligolws:
			# copy children;  LIGO_LW elements have no attributes
			map(dest.appendChild, src.childNodes)
			# unlink from parent
			if src.parentNode is not None:
				src.parentNode.removeChild(src)
	return elem

public void addWorkManager(org.ironjacamar.core.spi.workmanager.Address logicalAddress, org.jgroups.Address address)
   {
      super.localWorkManagerAdd(logicalAddress, address);
   }

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


Question:
Build the rotation-translation matrix.

        It has the form:

        [         | dx ]
        [    R    | dy ]
        [         | dz ]
        [ 0  0  0 | 1  ]

def get_matrix(theta, phi, psi, dx, dy, dz,
                   matrix=np.zeros((4, 4), dtype=DTYPE),
                   angles=np.zeros(3, dtype=DTYPE)):

        # NB!: matrix and angles by default are being overwritten on each call
        # thus, only created once at compile time.

        angles[0] = theta
        angles[1] = phi
        angles[2] = psi

        cx, cy, cz = np.cos(angles)
        sx, sy, sz = np.sin(angles)

        rotation = matrix[:3, :3]
        rotation.flat = (cx * cz - sx * cy * sz,
                         cx * sz + sx * cy * cz, sx * sy,
                         -sx * cz - cx * cy * sz,
                         -sx * sz + cx * cy * cz, cx * sy,
                         sy * sz,
                         -sy * cz, cy)

        # Translation component
        matrix[:3, 3] = dx, dy, dz
        matrix[3, 3] = 1.
        return matrix

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

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


Question:
Rendering assignment files

@param assign_files $tree
@return string

public function render_assign_files(assign_files $tree) {
        $this->htmlid = html_writer::random_id('assign_files_tree');
        $this->page->requires->js_init_call('M.mod_assign.init_tree', array(true, $this->htmlid));
        $html = '
htmlid.'">';
        $html .= $this->htmllize_tree($tree, $tree->dir);
        $html .= '
';

        if ($tree->portfolioform) {
            $html .= $tree->portfolioform;
        }
        return $html;
    }

def run(args = ARGV)
      opts.parse!(args)

      if !analyze_gemfile? && args.empty?
        puts opts.parser
        exit 1
      end

      print_requires(options, args)
    end

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