Question:
Register the Menus.

@return void

protected function registerBreadcrumb()
    {
        BreadcrumbFacade::make('admin.dashboard', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Dashboard');
        });

        BreadcrumbFacade::make('admin.product.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Product')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.product.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Create')
                ->parent('admin.dashboard')
                ->parent('admin.product.index');
        });

        BreadcrumbFacade::make('admin.product.edit', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Edit')
                ->parent('admin.dashboard')
                ->parent('admin.product.index');
        });

        BreadcrumbFacade::make('admin.attribute.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Attribute')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.attribute.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Create')
                ->parent('admin.dashboard')
                ->parent('admin.attribute.index');
        });

        BreadcrumbFacade::make('admin.attribute.edit', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Edit')
                ->parent('admin.dashboard')
                ->parent('admin.attribute.index');
        });

        BreadcrumbFacade::make('admin.property.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Property')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.property.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Create')
                ->parent('admin.dashboard')
                ->parent('admin.property.index');
        });

        BreadcrumbFacade::make('admin.attribute.edit', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Edit')
                ->parent('admin.dashboard')
                ->parent('admin.attribute.index');
        });

        BreadcrumbFacade::make('admin.order.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Order')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.order.view', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('View')
                ->parent('admin.dashboard')
                ->parent('admin.order.index');
        });

        BreadcrumbFacade::make('admin.theme.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Theme')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.theme.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Upload')
                ->parent('admin.dashboard')
                ->parent('admin.theme.index');
        });

        BreadcrumbFacade::make('admin.role.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Role')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.role.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Create')
                ->parent('admin.dashboard')
                ->parent('admin.role.index');
        });

        BreadcrumbFacade::make('admin.role.edit', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Edit')
                ->parent('admin.dashboard')
                ->parent('admin.role.index');
        });

        BreadcrumbFacade::make('admin.admin-user.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Admin User')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.admin-user.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Create')
                ->parent('admin.dashboard')
                ->parent('admin.admin-user.index');
        });

        BreadcrumbFacade::make('admin.admin-user.edit', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Edit')
                ->parent('admin.dashboard')
                ->parent('admin.admin-user.index');
        });

        BreadcrumbFacade::make('admin.admin-user.show', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Show')
                ->parent('admin.dashboard')
                ->parent('admin.admin-user.index');
        });

        BreadcrumbFacade::make('admin.configuration', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Configuration')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.category.index', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Category')
                ->parent('admin.dashboard');
        });

        BreadcrumbFacade::make('admin.category.create', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Create')
                ->parent('admin.dashboard')
                ->parent('admin.category.index');
        });

        BreadcrumbFacade::make('admin.category.edit', function (Breadcrumb $breadcrumb) {
            $breadcrumb->label('Edit')
                ->parent('admin.dashboard')
                ->parent('admin.category.index');
        });
    }

def showPanelMenu(self, panel, point=None):

        if not self._panelMenu:
            self._panelMenu = XViewPanelMenu(self)

        if point is None:
            point = QtGui.QCursor.pos()

        self._panelMenu.setCurrentPanel(panel)
        self._panelMenu.exec_(point)

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


Question:
// LoadSite implements Storage.LoadSite by loading it from disk. If it is not
// present, an instance of ErrNotExist is returned.

func (s *FileStorage) LoadSite(domain string) (*SiteData, error) {
	var err error
	siteData := new(SiteData)
	siteData.Cert, err = s.readFile(s.siteCertFile(domain))
	if err != nil {
		return nil, err
	}
	siteData.Key, err = s.readFile(s.siteKeyFile(domain))
	if err != nil {
		return nil, err
	}
	siteData.Meta, err = s.readFile(s.siteMetaFile(domain))
	if err != nil {
		return nil, err
	}
	return siteData, nil
}

public function fire()
    {
        $entityName      = $this->parseName($this->argument('name'));
        $pieces          = explode('\\', $entityName);
        $entityShortName = array_pop($pieces);

        $this->appNamespace        = $this->laravel->getNamespace();
        $this->entityNamespace     = implode('\\', $pieces);
        $this->contractNamespace   = $this->appNamespace . 'Contracts\Repository';
        $this->repositoryNamespace = $this->appNamespace . 'Repositories';

        $repoName         = $entityShortName . 'Repository';
        $repoAppEntity    = $this->appNamespace . 'Support\AppEntityRepository';
        $repoContractName = sprintf('%s\%s', $this->contractNamespace, $repoName);
        $repoConcreteName = sprintf('%s\%s', $this->repositoryNamespace, $repoName);

        $traits     = new Collection();
        $interfaces = new Collection();

        $this->buildBehaviourOptions($traits, $interfaces);

        $this->createFile($entityName, $this->entityClassStub($entityShortName, $interfaces, $traits));

        if ($this->option('repository')) {
            $this->createFile($repoAppEntity,    $this->appRepositoryClassStub());
            $this->createFile($repoConcreteName, $this->repositoryClassStub($repoName));
            $this->createFile($repoContractName, $this->repositoryInterfaceStub($repoName));
        }

        return 0;
    }

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


Question:
// EncodeJSON - Encodes the contained object back to a JSON formatted []byte
// using a variant list of modifier functions for the encoder being used.
// Functions for modifying the output are prefixed with EncodeOpt, e.g.
// EncodeOptHTMLEscape.

func (g *Container) EncodeJSON(encodeOpts ...EncodeOpt) []byte {
	var b bytes.Buffer
	encoder := json.NewEncoder(&b)
	encoder.SetEscapeHTML(false) // Do not escape by default.
	for _, opt := range encodeOpts {
		opt(encoder)
	}
	if err := encoder.Encode(g.object); err != nil {
		return []byte("{}")
	}
	result := b.Bytes()
	if len(result) > 0 {
		result = result[:len(result)-1]
	}
	return result
}

public function convert($str, $reverse = false)
    {
        $encoding        = $this->getEncoding();
        $convertEncoding = $this->getConvertEncoding();

        if ($convertEncoding === null) {
            throw new Exception\LogicException(
                'No convert encoding defined'
            );
        }

        if ($encoding === $convertEncoding) {
            return $str;
        }

        $fromEncoding = $reverse ? $convertEncoding : $encoding;
        $toEncoding   = $reverse ? $encoding : $convertEncoding;
        return mb_convert_encoding($str, $toEncoding, $fromEncoding);
    }

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


Question:
Creates a composite option of all {@link KnopflerfishFrameworkOption} versions (up to the date of Pax Exam
release).

@return all knopflerfish framework versions composite option

public static Option allKnopflerfishVersions()
    {
        return composite(
            //exclude version 2.0.0 as it looks like it has an internal problem of NPE in BundlePackages.java:266 while
            //looking for annotations from CallableTestMethodImpl.getAnnotatedMethods
            //knopflerfish().version( "2.0.0" ),
            knopflerfish().version( "2.0.1" ),
            knopflerfish().version( "2.0.2" ),
            knopflerfish().version( "2.0.3" ),
            knopflerfish().version( "2.0.4" ),
            knopflerfish().version( "2.0.5" ),
            knopflerfish().version( "2.1.0" ),
            knopflerfish().version( "2.1.1" ),
            knopflerfish().version( "2.2.0" ),
            knopflerfish().version( "2.3.0" ),
            knopflerfish().version( "2.3.1" ),
            knopflerfish().version( "2.3.2" ),
            knopflerfish().version( "2.3.3" ),
            knopflerfish().version( "3.0.0" )
        );
    }

def run(call_file, ref_file, vrn_files, data):

    algs = [data["config"]["algorithm"]] * len(data.get("vrn_files", [1]))
    if includes_missingalt(data):
        logger.info("Removing variants with missing alts from %s." % call_file)
        call_file = gatk_remove_missingalt(call_file, data)

    if "gatkcnn" in dd.get_tools_on(data):
        return _cnn_filter(call_file, vrn_files, data)
    elif config_utils.use_vqsr(algs, call_file):
        if vcfutils.is_gvcf_file(call_file):
            raise ValueError("Cannot force gVCF output with joint calling using tools_on: [gvcf] and use VQSR. "
                             "Try using cutoff-based soft filtering with tools_off: [vqsr]")
        snp_file, indel_file = vcfutils.split_snps_indels(call_file, ref_file, data["config"])
        snp_filter_file = _variant_filtration(snp_file, ref_file, vrn_files, data, "SNP",
                                              vfilter.gatk_snp_cutoff)
        indel_filter_file = _variant_filtration(indel_file, ref_file, vrn_files, data, "INDEL",
                                                vfilter.gatk_indel_cutoff)
        orig_files = [snp_filter_file, indel_filter_file]
        out_file = "%scombined.vcf.gz" % os.path.commonprefix(orig_files)
        combined_file = vcfutils.combine_variant_files(orig_files, out_file, ref_file, data["config"])
        return combined_file
    else:
        snp_filter = vfilter.gatk_snp_cutoff(call_file, data)
        indel_filter = vfilter.gatk_indel_cutoff(snp_filter, data)
        return indel_filter

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


Question: Marshall the given parameter object.

public void marshall(SetSourceRequest setSourceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(setSourceRequest.getDecryption(), DECRYPTION_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getEntitlementArn(), ENTITLEMENTARN_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getIngestPort(), INGESTPORT_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getMaxBitrate(), MAXBITRATE_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getMaxLatency(), MAXLATENCY_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getName(), NAME_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getProtocol(), PROTOCOL_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getStreamId(), STREAMID_BINDING);
            protocolMarshaller.marshall(setSourceRequest.getWhitelistCidr(), WHITELISTCIDR_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Try to get a module, or return false.

@param {[string]} paths  Possible paths to find their module.
@returns {object|false}

function tryRequireEach(paths) {
  let result;

  while (!result && paths.length) {
    result = tryRequire(paths.shift());
  }

  return result;
}

function walk (router, transform) {
  assert.equal(typeof router, 'function', 'wayfarer.walk: router should be an function')
  assert.equal(typeof transform, 'function', 'wayfarer.walk: transform should be a function')

  var trie = router._trie
  assert.equal(typeof trie, 'object', 'wayfarer.walk: trie should be an object')

  // (str, obj) -> null
  ;(function walk (route, trie) {
    if (trie.cb) {
      trie.cb = transform(route, trie.cb)
    }

    if (trie.nodes) {
      var nodes = trie.nodes
      Object.keys(nodes).forEach(function (key) {
        var node = nodes[key]
        var newRoute = (key === '$$')
          ? route + '/:' + trie.name
          : route + '/' + key
        walk(newRoute, node)
      })
    }
  })('', trie.trie)
}

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


Question: Transfer name on blockchain

def transfer_user(self, username, transfer_address, owner_privkey):

        url = self.base_url + "/users/" + username + "/update"

        owner_pubkey = get_pubkey_from_privkey(owner_privkey)

        payload = {
            'transfer_address': transfer_address,
            'owner_pubkey': owner_pubkey
            }

        resp = self._post_request(url, payload)

        try:
            unsigned_tx = resp['unsigned_tx']
        except:
            return resp

        # sign all unsigned inputs
        signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)

        return self.broadcast_transaction(signed_tx)

def balance(self, account: Address):

        return self.web3.eth.getBalance(to_checksum_address(account), 'pending')

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


Question:
// Signum determines the sign of a number, returning a number between -1 and
// 1 to represent the sign.

func Signum(num cty.Value) (cty.Value, error) {
	return SignumFunc.Call([]cty.Value{num})
}

func (sink writerSink) Log(level LogLevel, log []byte) {
	if level < sink.minLogLevel {
		return
	}

	sink.writer.Write(log)
	if len(log) > 0 {
		sink.writer.Write([]byte("\n"))
	}
}

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


Question: Load a generic spaCy model and add the sentencizer for sentence tokenization

def load_default_model_sentencizer(lang):

    loading_start = time.time()
    lang_class = get_lang_class(lang)
    nlp = lang_class()
    nlp.add_pipe(nlp.create_pipe('sentencizer'))
    loading_end = time.time()
    loading_time = loading_end - loading_start
    return nlp, loading_time, lang + "_default_" + 'sentencizer'

def _apply_pipeline_and_get_build_instance(self,
	                                           X_factory,
	                                           mX_factory,
	                                           category_idx_store,
	                                           df,
	                                           parse_pipeline,
	                                           term_idx_store,
	                                           metadata_idx_store,
	                                           y):
		'''

		'''
		df.apply(parse_pipeline.parse, axis=1)
		y = np.array(y)
		X, mX = build_sparse_matrices(y, X_factory, mX_factory)
		return CorpusDF(df,
		                X,
		                mX,
		                y,
		                self._text_col,
		                term_idx_store,
		                category_idx_store,
		                metadata_idx_store)

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


Question:
Add the elements from the model to the bridge for file check step

@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model

protected function addStepRoundMatch(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
    {
        $this->displayHeader($bridge, $this->_('Match the current track rounds to import rounds.'), 'h3');

        // Load the import data form settings
        $import = $this->loadImportData();

        $this->addExistingRoundsToModel($import, $model);

        $rounds = $model->getColNames('existingRound');

        if ($rounds) {
            $this->addItems($bridge, $rounds);
        } else {
            $bridge->addHtml('existingRound')->pInfo($this->_('No rounds in current track.'));
        }
    }

public void marshall(AbortMultipartUploadRequest abortMultipartUploadRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(abortMultipartUploadRequest.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(abortMultipartUploadRequest.getVaultName(), VAULTNAME_BINDING);
            protocolMarshaller.marshall(abortMultipartUploadRequest.getUploadId(), UPLOADID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Decodes our custom extension types

def ext_hook(self, code, data):

        if code == self.EXT_DATETIME:
            # Unpack datetime object from a big-endian signed 64-bit integer.
            microseconds = self.STRUCT_DATETIME.unpack(data)[0]
            return datetime.datetime.utcfromtimestamp(microseconds / 1000000.0)
        elif code == self.EXT_DATE:
            # Unpack local-date object from a big-endian unsigned short and two big-endian unsigned chars
            return datetime.date(*self.STRUCT_DATE.unpack(data))
        elif code == self.EXT_TIME:
            # Unpack a dateless-time object from three big-endian unsigned chars and a big-endian unsigned
            # 32-bit integer.
            return datetime.time(*self.STRUCT_TIME.unpack(data))
        elif code == self.EXT_DECIMAL:
            obj_len = self.STRUCT_DECIMAL_LENGTH.unpack(data[:2])[0]
            obj_decoder = struct.Struct(str('!{}s'.format(obj_len)))
            return decimal.Decimal(obj_decoder.unpack(data[2:])[0].decode('utf-8'))
        elif code == self.EXT_CURRINT:
            # Unpack Amount object into (code, minor) from a 3-char ASCII string and a signed 64-bit integer.
            code, minor_value = self.STRUCT_CURRINT.unpack(data)
            return currint.Amount.from_code_and_minor(code.decode('ascii'), minor_value)
        else:
            raise TypeError('Cannot decode unknown extension type {} from MessagePack'.format(code))

public function setClientEncType(\Zend\Http\Client $client)
    {
        // Setting EncType to UrlEncoded
        $client->setEncType(\Zend\Http\Client::ENC_URLENCODED);

        return $client;
    }

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


Question: // SetTags sets the Tags field's value.

func (s *SimulationJob) SetTags(v map[string]*string) *SimulationJob {
	s.Tags = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
If b1 and b2 would be ``int`` s this would be ``b1 ^ b2`` :

	>>> from py_register_machine2.engine_tools.operations import bitsetxor
	>>> b1 = [1, 1, 1, 1]
	>>> b2 = [1, 1, 0, 1]
	>>> bitsetxor(b1, b2)
	[0, 0, 1, 0]
	>>> bin(0b1111 ^ 0b1101)
	'0b10'

def bitsetxor(b1, b2):

	res = []
	for bit1, bit2 in zip(b1, b2):
		res.append( bit1 ^ bit2)
	return res

async def _digital_message(self, data):

        port = data[0]
        port_data = (data[PrivateConstants.MSB] << 7) + \
                    data[PrivateConstants.LSB]
        pin = port * 8
        for pin in range(pin, min(pin + 8, len(self.digital_pins))):
            # get pin value
            value = port_data & 0x01

            # set the current value in the pin structure
            self.digital_pins[pin].current_value = value

            # append pin number, pin value, and pin type to return value and return as a list
            message = [pin, value, Constants.INPUT]

            if self.digital_pins[pin].cb:
                if self.digital_pins[pin].cb_type:
                    await self.digital_pins[pin].cb(message)
                else:
                    # self.digital_pins[pin].cb(data)
                    loop = self.loop
                    loop.call_soon(self.digital_pins[pin].cb, message)

                # is there a latch entry for this pin?
                key = 'D' + str(pin)
                if key in self.latch_map:
                    await self._check_latch_data(key, port_data & 0x01)
            port_data >>= 1

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


Question:
Returns Apache Solr add command.

@param values
values to include
@return XML as String

public static String getSolrAddDocument(Map<String, String> values) {
    StringBuilder builder = new StringBuilder();
    builder.append("<add><doc>");
    for (Map.Entry<String, String> pair : values.entrySet()) {
      XMLUtils.addSolrField(builder, pair);
    }
    builder.append("</doc></add>");
    return builder.toString();
  }

def process_children(self, node, path, level, parent=None):

        data_parent = parent if parent else node
        chs = node.i_children
        for ch in chs:
            if ch.keyword in ["choice", "case"]:
                self.process_children(ch, path, level, node)
                continue
            p = path + "/" + self.qname(ch)
            tmpl = self.xsl_template(p)
            ct = self.xsl_calltemplate(ch.keyword, tmpl)
            self.xsl_withparam("level", "%d" % level, ct)
            if (data_parent.i_module is None or
                ch.i_module.i_modulename != data_parent.i_module.i_modulename):
                self.xsl_withparam("nsid", ch.i_module.i_modulename + ":", ct)
            if ch.keyword in ["leaf", "leaf-list"]:
                self.type_param(ch, ct)
            elif ch.keyword != "anyxml":
                offset = 2 if ch.keyword == "list" else 1
                self.process_children(ch, p, level + offset)

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


Question: Compute and return median z1pt0 (in m), equation 17, pqge 79.

def _compute_median_z1pt0(self, vs30):

        z1pt0_median = np.zeros_like(vs30) + 6.745

        idx = np.where((vs30 >= 180.0) & (vs30 <= 500.0))
        z1pt0_median[idx] = 6.745 - 1.35 * np.log(vs30[idx] / 180.0)

        idx = vs30 > 500.0
        z1pt0_median[idx] = 5.394 - 4.48 * np.log(vs30[idx] / 500.0)

        return np.exp(z1pt0_median)

def print_agi_and_mpe_balances(self):

        if (self.args.account):
            account = self.args.account
        else:
            account = self.ident.address
        eth_wei  = self.w3.eth.getBalance(account)
        agi_cogs = self.call_contract_command("SingularityNetToken", "balanceOf", [account])
        mpe_cogs = self.call_contract_command("MultiPartyEscrow",    "balances",  [account])

        # we cannot use _pprint here because it doesn't conserve order yet
        self._printout("    account: %s"%account)
        self._printout("    ETH: %s"%self.w3.fromWei(eth_wei, 'ether'))
        self._printout("    AGI: %s"%cogs2stragi(agi_cogs))
        self._printout("    MPE: %s"%cogs2stragi(mpe_cogs))

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


Question:
@return string

@throws \Exception

public function getPassword()
    {
        if (!array_key_exists(self::PASSWORD, $this->passwd)) {
            throw new \Exception('Could not get user password from passwd.');
        }
        return $this->passwd[self::PASSWORD];
    }

public function execute($command, callable $next)
    {
        if ($command instanceof FallbackCommand) {
            $command->message = new TextTemplate();
            $command->message->text = "Oops! I dont know wath you say.";
        }

        return $next($command);
    }

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


Question:
Convert timestamp to date

@param type type
@param dateTime timestamp
@return date

public static <D extends Comparable> DateExpression<D> date(Class<D> type, DateTimeExpression<?> dateTime) {
        return Expressions.dateOperation(type, Ops.DateTimeOps.DATE, dateTime);
    }

private TSMeta parseTSMetaQS(final HttpQuery query) {
    final String tsuid = query.getQueryStringParam("tsuid");
    final TSMeta meta;
    if (tsuid != null && !tsuid.isEmpty()) {
      meta = new TSMeta(tsuid);
    } else {
      meta = new TSMeta();
    }

    final String display_name = query.getQueryStringParam("display_name");
    if (display_name != null) {
      meta.setDisplayName(display_name);
    }

    final String description = query.getQueryStringParam("description");
    if (description != null) {
      meta.setDescription(description);
    }

    final String notes = query.getQueryStringParam("notes");
    if (notes != null) {
      meta.setNotes(notes);
    }

    final String units = query.getQueryStringParam("units");
    if (units != null) {
      meta.setUnits(units);
    }

    final String data_type = query.getQueryStringParam("data_type");
    if (data_type != null) {
      meta.setDataType(data_type);
    }

    final String retention = query.getQueryStringParam("retention");
    if (retention != null && !retention.isEmpty()) {
      try {
        meta.setRetention(Integer.parseInt(retention));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'retention' value");
      }
    }

    final String max = query.getQueryStringParam("max");
    if (max != null && !max.isEmpty()) {
      try {
        meta.setMax(Float.parseFloat(max));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'max' value");
      }
    }

    final String min = query.getQueryStringParam("min");
    if (min != null && !min.isEmpty()) {
      try {
        meta.setMin(Float.parseFloat(min));
      } catch (NumberFormatException nfe) {
        throw new BadRequestException("Unable to parse 'min' value");
      }
    }

    return meta;
  }

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


Question:
Can be applied to any function or method to be traced by X-Ray.

    If `skip_args` is True, the arguments of the function won't be sent to
    X-Ray.

def trace_xray_subsegment(skip_args=False):

    @wrapt.decorator
    def wrapper(wrapped, instance, args, kwargs):
        metadata_extractor = (
            noop_function_metadata
            if skip_args
            else extract_function_metadata
        )
        return generic_xray_wrapper(
            wrapped, instance, args, kwargs,
            name=get_function_name,
            namespace='local',
            metadata_extractor=metadata_extractor,
        )

    return wrapper

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

      :ok # passes
    end

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


Question:
Ends the execution of an async method.
@param promise The promise returned by beginAsyncMethod.
@return The method return value.

public JsonNode endAsyncMethod(final JsiiPromise promise) {
        ObjectNode req = makeRequest("end");
        req.put("promiseid", promise.getPromiseId());
        JsonNode resp = this.runtime.requestResponse(req);
        if (resp == null) {
            return null; // result is null
        }
        return resp.get("result");
    }

protected <T extends RaftRequest, U extends RaftResponse> void sendRequest(T request, BiFunction<MemberId, T, CompletableFuture<U>> sender, int count, CompletableFuture<U> future) {
    MemberId node = next();
    if (node != null) {
      log.trace("Sending {} to {}", request, node);
      int selectionId = this.selectionId;
      sender.apply(node, request).whenCompleteAsync((r, e) -> {
        if (e != null || r != null) {
          handleResponse(request, sender, count, selectionId, node, r, e, future);
        } else {
          future.complete(null);
        }
      }, context);
    } else {
      future.completeExceptionally(new ConnectException("Failed to connect to the cluster"));
    }
  }

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


Question:
Parse a SpotVirtualMachineRequest, make a DescribeInstances call if instanceId is returned
to gather more information
@param node
@return
@throws CloudException

private SpotVirtualMachineRequest toSpotVmRequest( @Nonnull Node node ) throws CloudException {
        NodeList el = node.getChildNodes();
        String requestId = null;
        float price = 0.0F;
        SpotVirtualMachineRequestType type = null;
        long createdTs = 0;
        long validFromTs = 0;
        long validUntilTs = 0;
        String fulfillmentDcid = null;
        String launchGroup = null;

        // use to look up the instance
        String instanceId = null;

        // get these from the instance if fulfilled
        String amiId = null;
        String productId = null;
        long fulfillmentTs = 0;

        for( int i = 0; i < el.getLength(); i++ ) {
            Node item = el.item(i);
            String name = item.getNodeName();

            if( "spotInstanceRequestId".equals(name) ) {
                requestId = item.getFirstChild().getNodeValue().trim();
            }
            else if( "spotPrice".equals(name) ) {
                price = AWSCloud.getFloatValue(item);
            }
            else if( "type".equals(name) ) {
                type = SpotVirtualMachineRequestType.ONE_TIME;
                String value = AWSCloud.getTextValue(item);
                if( "persistent".equals(value) ) {
                    type = SpotVirtualMachineRequestType.PERSISTENT;
                }
            }
            else if( "launchGroup".equals(name) ) {
                launchGroup = AWSCloud.getTextValue(item);
            }
            else if( "launchedAvailabilityZone".equals(name) ) {
                fulfillmentDcid = AWSCloud.getTextValue(item);
            }
            else if( "createTime".equals(name) ) {
                createdTs = AWSCloud.getTimestampValue(item);
            }
            else if( "validFrom".equals(name) ) {
                validFromTs = AWSCloud.getTimestampValue(item);
            }
            else if( "validUntil".equals(name) ) {
                validUntilTs = AWSCloud.getTimestampValue(item);
            }
            else if( "instanceId".equals(name) ) {
                instanceId = AWSCloud.getTextValue(item);
            }
        }
        if( instanceId != null ) {
            try {
                // see if the instance is there
                VirtualMachine vm = getVirtualMachine(instanceId);
                productId = vm.getProductId();
                fulfillmentTs = vm.getCreationTimestamp();
                amiId = vm.getProviderMachineImageId();
            } catch (CloudException ce) {
                // ignore
            } catch( InternalException e ) {
                // ignore
            }
        }
        return SpotVirtualMachineRequest.getInstance(requestId, price, type, amiId, productId, createdTs, validFromTs, validUntilTs, fulfillmentTs, fulfillmentDcid, launchGroup);
    }

def __register_types(self):

        try:
            for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']:
                cls = entry_point.load()
                self.types[ResourceType.get(cls.resource_type).resource_type_id] = cls
                logger.debug('Registered resource type {}'.format(cls.__name__))
        except SQLAlchemyError as ex:
            logger.warning('Failed loading type information: {}'.format(ex))

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


Question: // newEvent creates a new event.

func newEvent(typ string, value interface{}, prevValue interface{}) *event {
	return &event{
		typ:       typ,
		value:     value,
		prevValue: prevValue,
	}
}

func (s *WorkflowExecutionContinuedAsNewEventAttributes) SetWorkflowType(v *WorkflowType) *WorkflowExecutionContinuedAsNewEventAttributes {
	s.WorkflowType = v
	return s
}

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


Question:
Redirects to the specified file or shows an historical resource.<p>

@throws Exception if redirection fails

public void actionShow() throws Exception {

        // try to load the historical resource
        if (CmsStringUtil.isNotEmpty(getParamVersion())) {
            showHistoricVersion();
        } else {
            String resourceStr = getParamResource();
            // trying to read the resource
            CmsResource resource = readResource(resourceStr);
            if (isDeleted(resource)) {
                // resource has been deleted in offline project
                throw new CmsVfsResourceNotFoundException(Messages.get().container(
                    Messages.ERR_RESOURCE_DELETED_2,
                    resourceStr,
                    getCms().getRequestContext().getCurrentProject().getName()));
            }

            // check for release / expiration time window
            autoTimeWarp(resource);

            // code for display resource after all tests for displayability (exists, not deleted)
            //            if (CmsResourceTypeXmlContainerPage.isContainerPage(resource)) {
            //                // if we have a container page look for the first sitemap entry
            //                // and use that to display the container page
            //                List<CmsInternalSitemapEntry> entries = OpenCms.getSitemapManager().getEntriesForStructureId(
            //                    getJsp().getCmsObject(),
            //                    resource.getStructureId());
            //                if (!entries.isEmpty()) {
            //                    CmsInternalSitemapEntry entry = entries.get(0);
            //                    resourceStr = entry.getRootPath();
            //                }
            //            }
            if (OpenCms.getSiteManager().isSharedFolder(getCms().getRequestContext().getSiteRoot())) {
                if (!OpenCms.getSiteManager().startsWithShared(resourceStr)) {
                    resourceStr = CmsStringUtil.joinPaths(OpenCms.getSiteManager().getSharedFolder(), resourceStr);
                }
            }
            String url = getJsp().link(resourceStr);
            // if in online project
            if ((url.indexOf("://") < 0) && getCms().getRequestContext().getCurrentProject().isOnlineProject()) {
                url = prependSiteRoot(url);
            }
            getJsp().getResponse().sendRedirect(url);
        }
    }

public static XPathUtils newXPath(final URL url) {
        final DefaultHttpClient client = new DefaultHttpClientImpl();
        final GetMethod method = new GetMethod(url.toExternalForm());
        try {
            final int responseCode = client.executeMethod(method);
            if (responseCode != HttpStatus.SC_OK) {
                LOG.warn("Unexpected response code: " + responseCode);
            } else {
                final InputStream is = method.getResponseBodyAsStream();
                return XPathUtils.newXPath(is);
            }
        } catch (final HttpException e) {
            LOG.warn("Could not handle XPath", e);
        } catch (final IOException e) {
            LOG.warn("Could not handle XPath", e);
        } catch (final SAXException e) {
            LOG.warn("Could not handle XPath", e);
        } finally {
            method.releaseConnection();
        }
        return null;
    }

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


Question:
Register the JMX agent

@throws java.lang.Exception

public synchronized void register() throws Exception {
        if (mbeanName != null) {
            throw new Exception("Agent already registered");
        }
        mbeanName = new ObjectName(getClass().getPackage().getName() + ":type=" + getClass().getSimpleName());
        logger.info("Registering JMX agent " + mbeanName);
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, mbeanName);
        logger.info("JMX agent " + mbeanName + " registered");
    }

private static boolean hasMoxyReflector() {
		if (hasMoxyReflector != null) {
			return hasMoxyReflector;
		}

		try {
			new MoxyReflector();

			hasMoxyReflector = true;
		} catch (NoClassDefFoundError error) {
			hasMoxyReflector = false;
		}

		return hasMoxyReflector;
	}

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


Question:
Flushes all loaded cart and related entities.

We only persist it if have lines loaded inside, so empty carts will never
be persisted

@param CartInterface $cart Cart

public function saveCart(CartInterface $cart)
    {
        if (!$cart->getCartLines()->isEmpty()) {
            $this->cartObjectManager->persist($cart);
        }

        $this
            ->cartObjectManager
            ->flush();
    }

public static function hydrate(stdClass $application)
    {
        $hydrated = new ApplicationEntity();

        if (isset($application->id)) {
            $hydrated->setId($application->id);
        }

        if (isset($application->name)) {
            $hydrated->setName($application->name);
        }

        if (isset($application->current_scan)) {
            $hydrated->setCurrentScan($application->current_scan);
        }

        if (isset($application->created_by)) {
            $hydrated->setCreatedBy(UserHydrator::hydrate($application->created_by));
        }

        if (isset($application->charged_quota)) {
            $hydrated->setChargedQuota(QuotaHydrator::hydrate($application->charged_quota));
        }

        if (isset($application->created_at)) {
            $hydrated->setCreatedAt(new DateTime($application->created_at));
        }

        if (isset($application->organization)) {
            $hydrated->setOrganization(OrgHydrator::hydrate($application->organization));
        }

        if (isset($application->auto_renew)) {
            $hydrated->setAutoRenew($application->auto_renew);
        }

        return $hydrated;
    }

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


Question:
Make a string safe to use in a URL
Inspired by (c) Panther <http://www.pantherforum.org/>

@param $str
@return string

public static function slug($str)
    {
        $str = strtr($str, self::$url_replace);
        $str = strtolower(utf8_decode($str));
        $str = Utils::trim(preg_replace(['/[^a-z0-9\s]/', '/[\s]+/'], ['', '-'], $str), '-');

        if (empty($str)) {
            $str = 'view';
        }

        return $str;
    }

public function getParameter( $parameter )
    {

        self::isParameterAllowed( $parameter );

        $value = $this->query(new Raw("SHOW {$parameter}"))->fetch( Result::FETCH_SINGLE );

        return ( $value === 'true' or $value === 'false' )
            ? \Bond\boolval( $value )
            : $value;

    }

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


Question:
Returns next token.

@return Token

@throws InternalErrorException If there is no more token

public function getNext()
    {
        if ($this->peeking) {
            $this->peeking = false;
            $this->used[] = $this->peeked;

            return $this->peeked;
        }

        if (!isset($this->tokens[$this->cursor])) {
            throw new InternalErrorException('Unexpected token stream end.');
        }

        return $this->tokens[$this->cursor++];
    }

public static TopologyMaster.ExceptionLogResponse toProtobuf(ExceptionResponse response) {
    TopologyMaster.ExceptionLogResponse.Builder builder =
        TopologyMaster.ExceptionLogResponse.newBuilder();
    // default OK if we have response to build already
    builder.setStatus(Common.Status.newBuilder().setStatus(Common.StatusCode.OK));

    for (ExceptionDatum e : response.getExceptionDatapointList()) {
      TopologyMaster.TmasterExceptionLog.Builder exceptionBuilder =
          TopologyMaster.TmasterExceptionLog.newBuilder();
      // ExceptionDatapoint
      exceptionBuilder.setComponentName(e.getComponentName());
      exceptionBuilder.setHostname(e.getHostname());
      exceptionBuilder.setInstanceId(e.getInstanceId());
      // ExceptionData
      exceptionBuilder.setStacktrace(e.getStackTrace());
      exceptionBuilder.setLasttime(e.getLastTime());
      exceptionBuilder.setFirsttime(e.getFirstTime());
      exceptionBuilder.setCount(e.getCount());
      exceptionBuilder.setLogging(e.getLogging());

      builder.addExceptions(exceptionBuilder);
    }

    return builder.build();
  }

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


Question:
Cancels timer by ID
@param  integer|string $id Timer ID
@return void

public static function cancelTimeout($id)
    {
        if (isset(self::$list[$id])) {
            self::$list[$id]->cancel();
        }
    }

func (c *Call) matches(args []interface{}) error {
	if !c.methodType.IsVariadic() {
		if len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}

		for i, m := range c.args {
			if !m.Matches(args[i]) {
				return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
					c.origin, strconv.Itoa(i), args[i], m)
			}
		}
	} else {
		if len(c.args) < c.methodType.NumIn()-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
				c.origin, len(c.args), c.methodType.NumIn()-1)
		}
		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}
		if len(args) < len(c.args)-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
				c.origin, len(args), len(c.args)-1)
		}

		for i, m := range c.args {
			if i < c.methodType.NumIn()-1 {
				// Non-variadic args
				if !m.Matches(args[i]) {
					return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
						c.origin, strconv.Itoa(i), args[i], m)
				}
				continue
			}
			// The last arg has a possibility of a variadic argument, so let it branch

			// sample: Foo(a int, b int, c ...int)
			if i < len(c.args) && i < len(args) {
				if m.Matches(args[i]) {
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
					// Got Foo(a, b) want Foo(matcherA, matcherB)
					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
					continue
				}
			}

			// The number of actual args don't match the number of matchers,
			// or the last matcher is a slice and the last arg is not.
			// If this function still matches it is because the last matcher
			// matches all the remaining arguments or the lack of any.
			// Convert the remaining arguments, if any, into a slice of the
			// expected type.
			vargsType := c.methodType.In(c.methodType.NumIn() - 1)
			vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
			for _, arg := range args[i:] {
				vargs = reflect.Append(vargs, reflect.ValueOf(arg))
			}
			if m.Matches(vargs.Interface()) {
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
				break
			}
			// Wrong number of matchers or not match. Fail.
			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
			return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
				c.origin, strconv.Itoa(i), args[i:], c.args[i])

		}
	}

	// Check that all prerequisite calls have been satisfied.
	for _, preReqCall := range c.preReqs {
		if !preReqCall.satisfied() {
			return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
				c.origin, preReqCall, c)
		}
	}

	// Check that the call is not exhausted.
	if c.exhausted() {
		return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
	}

	return nil
}

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


Question: Get or create a new case specific gene list record.

def case_genelist(self, case_obj):
        """"""
        list_id = "{}-HPO".format(case_obj.case_id)
        gene_list = self.gene_list(list_id)

        if gene_list is None:
            gene_list = GeneList(list_id=list_id)
            case_obj.gene_lists.append(gene_list)
            self.session.add(gene_list)

        return gene_list

def weather_cells(self):

        if not self._weather_cells:

            # get all the weather cell ids
            self._weather_cells = []
            for gen in self.generators:
                if hasattr(gen, 'weather_cell_id'):
                    self._weather_cells.append(gen.weather_cell_id)

            # drop duplicates
            self._weather_cells = list(set(self._weather_cells))
            # no need to check for Nones in the list because None in
            # gen.weather_cell_id is kicked out by the if hasattr() before

        return self._weather_cells

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


Question:
BusinessRule constructor
@param {Object}   meta           Meta infos like: { name: 'name', priority: 1, description: 'bla bla' }
@param {Function} businessRuleFn Function handle
`function(changed, previous, events, command, callback){}`
@constructor

function BusinessRule (meta, businessRuleFn) {
  Definition.call(this, meta);

  meta = meta || {};

  if (!businessRuleFn || !_.isFunction(businessRuleFn)) {
    var err = new Error('Business rule function not injected!');
    debug(err);
    throw err;
  }

  this.description = meta.description;
  this.priority = meta.priority || Infinity;

  this.businessRuleFn = businessRuleFn;
}

public function updateKstrukturs($id, $data) {
		// find
		$model = $this->get($id);

		if ($model === null) {
			return new NotFound(['message' => 'Skill not found.']);
		}

		// pass update to internal logic
		try {
			$this->doUpdateKstrukturs($model, $data);
		} catch (ErrorsException $e) {
			return new NotValid(['errors' => $e->getErrors()]);
		}

		// save and dispatch events
		$this->dispatch(SkillEvent::PRE_KSTRUKTURS_UPDATE, $model, $data);
		$this->dispatch(SkillEvent::PRE_SAVE, $model, $data);
		$rows = $model->save();
		$this->dispatch(SkillEvent::POST_KSTRUKTURS_UPDATE, $model, $data);
		$this->dispatch(SkillEvent::POST_SAVE, $model, $data);

		if ($rows > 0) {
			return Updated(['model' => $model]);
		}

		return NotUpdated(['model' => $model]);
	}

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


Question:
Add another property to the list of requested properties.

@param property
The property to request from the server.
@return This instance.

public PropertyRequest addProperty(ElementDescriptor<?> property)
	{
		if (mProp == null)
		{
			mProp = new HashMap<ElementDescriptor<?>, Object>(16);
		}
		mProp.put(property, null);
		return this;
	}

func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string,
	routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool,
	args map[string]interface{}, data interface{}) (BaseResponse, error) {
	var url string
	var retval BaseResponse
	url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh)
	if err != nil {
		return retval, err
	}
	var method string
	if len(id) == 0 {
		method = "POST"
	} else {
		method = "PUT"
	}
	body, err := c.DoCommand(method, url, args, data)
	if err != nil {
		return retval, err
	}
	if err == nil {
		// marshall into json
		jsonErr := json.Unmarshal(body, &retval)
		if jsonErr != nil {
			return retval, jsonErr
		}
	}
	return retval, err
}

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


Question:
Convert a specific node to XML (ugh! recursion!)

@param $data
@param $nodeName
@param $depth

private function convertNodeToXML($data, $nodeName, $depth)
    {
        if (is_scalar($data))
        {
            //Treat it as a scalar, just add the node to the output
            $this->output .= str_repeat(static::TAB_CHARACTER, $depth);
            $this->output .= '<' . $nodeName . '>' . $data . '</' . $nodeName . '>' . PHP_EOL;

            return;
        }

        //Handle objects as arrays and arrays as arrays
        if (is_object($data))
        {
            //Sorry for the typecast
            $data = (array)$data;

            //We can assume an object is an associative array now
            $isAssociative = true;
        }
        else
        {
            //This is considered the "Fastest" way to figure out if an array is associative or not
            $isAssociative = ($data !== array_values($data));
        }

        if ($isAssociative)
        {
            //Associative array, treat each node as an element of the parent, indent each one
            $this->output .= str_repeat(static::TAB_CHARACTER, $depth);
            $this->output .= '<' . $nodeName . '>' . PHP_EOL;

            foreach ($data as $key => $value)
            {
                $this->convertNodeToXML($value, $key, $depth + 1);
            }

            $this->output .= str_repeat(static::TAB_CHARACTER, $depth);
            $this->output .= '</' . $nodeName . '>' . PHP_EOL;
        }
        else
        {
            //Integer indexed array (we hope), treat each node as a clone of the parent with no extra indent
            foreach ($data as $key => $value)
            {
                $this->convertNodeToXML($value, $nodeName, $depth);
            }
        }
    }

private function loadDrupal(FileLoader $loader, ContainerBuilder $container, array $config)
    {
        if (isset($config['drupal'])) {
            $loader->load('drivers/drupal.yml');
            $container->setParameter('drupal.driver.drupal.drupal_root', $config['drupal']['drupal_root']);
        }
    }

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


Question:
Sets the feed categories.

This method is a convenience method, it maps to the Dublin Core module subjects.

@param categories the list of SyndCategoryImpl elements with the feed categories to set, an
empty list or null if none.

@Override
    public void setCategories(final List<SyndCategory> categories) {
        getDCModule().setSubjects(SyndCategoryListFacade.convertElementsSyndCategoryToSubject(categories));
    }

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

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


Question: Given an object and point relating to that object, returns a set of coords representing the same point with respect to the parent. TODO: refactor out TODO: provide more explanation, visuals?

function normalizeCoords(dispObj, coords) {
    var focalAngleRad = dispObj.rotation * Math.PI / 180;
    var oppositeRad = (Math.PI - focalAngleRad) / 2;

    // Distance from register point to coords
    var relX = coords.x - dispObj.regX;
    var relY = dispObj.regY - coords.y; // opposite of cartesian
    var distFromFocal = Math.sqrt(Math.pow(relX, 2) +
                        Math.pow(relY, 2));
    if(relX < 0) distFromFocal = -distFromFocal;

    // Distance between the relative and normalized point
    var pointDistance;
    if(oppositeRad !== 0)
        pointDistance = distFromFocal * Math.sin(focalAngleRad) /
                        Math.sin(oppositeRad);
    else
        pointDistance =  distFromFocal * 2;

    var totalRelativeRad = 0;
    if(distFromFocal !== 0)
        totalRelativeRad = Math.asin(relY / distFromFocal);

    var xRad = (Math.PI / 2) - focalAngleRad - oppositeRad +
                            totalRelativeRad;

    var x = Math.sin(xRad) * pointDistance +
            coords.x - dispObj.regX + dispObj.x;
    var y = Math.cos(xRad) * pointDistance +
            coords.y - dispObj.regY + dispObj.y;

    var rotation = coords.rotation || 0;
    rotation += dispObj.rotation;

    return {
        x: x,
        y: y,
        rotation: rotation
    };
}

void copy(State source)
    {
        this.ref = source.ref;
        this.score = source.score;
        this.previous = source.previous;
        this.buffer = source.buffer;
        this.top0 = source.top0;
        this.top1 = source.top1;
        this.stack = source.stack;
        this.last_action = source.last_action;
        this.heads = source.heads;
        this.deprels = source.deprels;
        this.left_most_child = source.left_most_child;
        this.right_most_child = source.right_most_child;
        this.left_2nd_most_child = source.left_2nd_most_child;
        this.right_2nd_most_child = source.right_2nd_most_child;
        this.nr_left_children = source.nr_left_children;
        this.nr_right_children = source.nr_right_children;
    }

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


Question:
// Connect registers a route for the Connect http method.
//
// Returns a *Route and an error which will be filled if route wasn't registered successfully.

func (api *APIBuilder) Connect(relativePath string, handlers ...context.Handler) *Route {
	return api.Handle(http.MethodConnect, relativePath, handlers...)
}

public function any($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('GET|HEAD|POST|PUT|PATCH|DELETE', $pattern, $handler, $requirements, $defaults);
    }

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


Question:
Gets the ProxyInfo of all fully initialized proxies in this registry.
The result is written into 'result'.

@param result The ProxyInfo of all proxies in this registry.

public void getProxyInfos(Collection<ProxyInfo> result) {
        for (Map.Entry<String, DistributedObjectFuture> entry : proxies.entrySet()) {
            DistributedObjectFuture future = entry.getValue();
            if (future.isSetAndInitialized()) {
                String proxyName = entry.getKey();
                result.add(new ProxyInfo(serviceName, proxyName));
            }
        }
    }

func HTTPServerTrace(options ...TracerOption) kithttp.ServerOption {
	cfg := TracerOptions{}

	for _, option := range options {
		option(&cfg)
	}

	if !cfg.Public && cfg.HTTPPropagate == nil {
		cfg.HTTPPropagate = &b3.HTTPFormat{}
	}

	serverBefore := kithttp.ServerBefore(
		func(ctx context.Context, req *http.Request) context.Context {
			var (
				spanContext trace.SpanContext
				span        *trace.Span
				name        string
				ok          bool
			)

			if cfg.Name != "" {
				name = cfg.Name
			} else {
				name = req.Method + " " + req.URL.Path
			}

			spanContext, ok = cfg.HTTPPropagate.SpanContextFromRequest(req)
			if ok && !cfg.Public {
				ctx, span = trace.StartSpanWithRemoteParent(
					ctx,
					name,
					spanContext,
					trace.WithSpanKind(trace.SpanKindServer),
					trace.WithSampler(cfg.Sampler),
				)
			} else {
				ctx, span = trace.StartSpan(
					ctx,
					name,
					trace.WithSpanKind(trace.SpanKindServer),
					trace.WithSampler(cfg.Sampler),
				)
				if ok {
					span.AddLink(trace.Link{
						TraceID:    spanContext.TraceID,
						SpanID:     spanContext.SpanID,
						Type:       trace.LinkTypeChild,
						Attributes: nil,
					})
				}
			}

			span.AddAttributes(
				trace.StringAttribute(ochttp.MethodAttribute, req.Method),
				trace.StringAttribute(ochttp.PathAttribute, req.URL.Path),
			)

			return ctx
		},
	)

	serverFinalizer := kithttp.ServerFinalizer(
		func(ctx context.Context, code int, r *http.Request) {
			if span := trace.FromContext(ctx); span != nil {
				span.SetStatus(ochttp.TraceStatus(code, http.StatusText(code)))

				if rs, ok := ctx.Value(kithttp.ContextKeyResponseSize).(int64); ok {
					span.AddAttributes(
						trace.Int64Attribute("http.response_size", rs),
					)
				}

				span.End()
			}
		},
	)

	return func(s *kithttp.Server) {
		serverBefore(s)
		serverFinalizer(s)
	}
}

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


Question:
// NewEffect creates a new haptic effect on a specified device.
// Pass pointer to a Haptic struct (Constant|Periodic|Condition|Ramp|LeftRight|Custom) instead of HapticEffect union.
// (https://wiki.libsdl.org/SDL_HapticNewEffect)

func (h *Haptic) NewEffect(he HapticEffect) (int, error) {
	ret := int(C.SDL_HapticNewEffect(
		h.cptr(),
		he.cHapticEffect()))
	return ret, errorFromInt(ret)
}

def get_band_structure(self):
        """"""

        kpath = HighSymmKpath(self.data.structure)
        kpt_line = [Kpoint(k, self.data.structure.lattice) for k
                    in
                    kpath.get_kpoints(coords_are_cartesian=False)[
                        0]]
        kpoints = np.array(
            [kp.frac_coords for kp in kpt_line])

        labels_dict = {l: k for k, l in zip(
            *kpath.get_kpoints(coords_are_cartesian=False)) if l}

        lattvec = self.data.get_lattvec()
        egrid, vgrid = fite.getBands(kpoints, self.equivalences, lattvec, self.coeffs)

        bands_dict = {Spin.up: (egrid / units.eV)}

        sbs = BandStructureSymmLine(kpoints, bands_dict,
                                    self.data.structure.lattice.reciprocal_lattice,
                                    self.efermi / units.eV,
                                    labels_dict=labels_dict)
        return sbs

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


Question:
获取依存
@param deprels 依存列表
@param id 依存下标
@return 依存

int DEPREL(final List<Integer> deprels, int id)
    {
        return ((id != -1) ? (deprels.get(id) + kDeprelInFeaturespace) : kNilDeprel);
    }

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: // SetMediaPackageOutputSettings sets the MediaPackageOutputSettings field's value.

func (s *OutputSettings) SetMediaPackageOutputSettings(v *MediaPackageOutputSettings) *OutputSettings {
	s.MediaPackageOutputSettings = v
	return s
}

protected function updateComposerJson($type)
    {
        // If the generated package is a Module.
        if ($type == 'module') {
            $namespace = 'Modules\\';

            $directory = 'modules/';
        }

        // If the generated package is a Theme.
        else if ($type == 'theme') {
            $namespace = 'Themes\\';

            $directory = 'themes/';
        }

        // Standard processing for the Packages.
        else {
            $namespace = $this->data['namespace'] .'\\';

            $directory = 'packages/' . $this->data['name'] . "/src/";
        }

        $composerJson = getenv('COMPOSER') ?: 'composer.json';

        $path = base_path($composerJson);

        // Get the composer.json contents in a decoded form.
        $config = json_decode(file_get_contents($path), true);

        if (! is_array($config)) {
            return;
        }

        // Update the composer.json
        else if (! Arr::has($config, "autoload.psr-4.$namespace")) {
            Arr::set($config, "autoload.psr-4.$namespace", $directory);

            $output = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";

            file_put_contents($path, $output);
        }
    }

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


Question:
casts a value to a XML Element Array

@param doc XML Document
@param o Object to cast
@return XML Comment Array
@throws PageException

public static Element[] toElementArray(Document doc, Object o) throws PageException {
	// Node[]
	if (o instanceof Node[]) {
	    Node[] nodes = (Node[]) o;
	    if (_isAllOfSameType(nodes, Node.ELEMENT_NODE)) return (Element[]) nodes;

	    Element[] elements = new Element[nodes.length];
	    for (int i = 0; i < nodes.length; i++) {
		elements[i] = toElement(doc, nodes[i]);
	    }
	    return elements;
	}
	// Collection
	else if (o instanceof Collection) {
	    Collection coll = (Collection) o;
	    Iterator<Object> it = coll.valueIterator();
	    List<Element> elements = new ArrayList<Element>();
	    while (it.hasNext()) {
		elements.add(toElement(doc, it.next()));
	    }
	    return elements.toArray(new Element[elements.size()]);
	}
	// Node Map and List
	Node[] nodes = _toNodeArray(doc, o);
	if (nodes != null) return toElementArray(doc, nodes);
	// Single Text Node
	try {
	    return new Element[] { toElement(doc, o) };
	}
	catch (ExpressionException e) {
	    throw new XMLException("can't cast Object of type " + Caster.toClassName(o) + " to a XML Element Array");
	}
    }

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

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

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


Question:
Převede číselnou velikost na textové výjádření v jednotkách velikosti (KB,MB,...)
@param $size
@return string

public static function formatSize($size, $decimalPrecision = 2) {

        if ($size < 1024)                           return $size . ' B';
        elseif ($size < 1048576)                   return round($size / 1024, $decimalPrecision) . ' kB';
        elseif ($size < 1073741824)                return round($size / 1048576, $decimalPrecision) . ' MB';
        elseif ($size < 1099511627776)             return round($size / 1073741824, $decimalPrecision) . ' GB';
        elseif ($size < 1125899906842624)          return round($size / 1099511627776, $decimalPrecision) . ' TB';
        elseif ($size < 1152921504606846976)       return round($size / 1125899906842624, $decimalPrecision) . ' PB';
        else return round($size / 1152921504606846976, $decimalPrecision) . ' EB';
    }

function fileSize($fichier)
	{
		$taille_fichier = "0";

		$taille_fichier = filesize($fichier);
		if ($taille_fichier >= 1073741824)
		{
			$taille_fichier = round($taille_fichier / 1073741824 * 100) / 100 . " Go";
		}
		elseif ($taille_fichier >= 1048576)
		{
			$taille_fichier = round($taille_fichier / 1048576 * 100) / 100 . " Mo";
		}
		elseif ($taille_fichier >= 1024)
		{
			$taille_fichier = round($taille_fichier / 1024 * 100) / 100 . " Ko";
		}
		else
		{
			$taille_fichier = $taille_fichier . " o";
		}

		return $taille_fichier;
	}

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


Question:
// MarshalJSON converts the feature collection object into the proper JSON.
// It will handle the encoding of all the child features and geometries.
// Alternately one can call json.Marshal(fc) directly for the same result.

func (fc FeatureCollection) MarshalJSON() ([]byte, error) {
	type featureCollection FeatureCollection

	fcol := &featureCollection{
		Type: "FeatureCollection",
	}

	if fc.BoundingBox != nil && len(fc.BoundingBox) != 0 {
		fcol.BoundingBox = fc.BoundingBox
	}

	fcol.Features = fc.Features
	if fcol.Features == nil {
		fcol.Features = make([]*Feature, 0) // GeoJSON requires the feature attribute to be at least []
	}

	if fc.CRS != nil && len(fc.CRS) != 0 {
		fcol.CRS = fc.CRS
	}

	return json.Marshal(fcol)
}

public void marshall(ListedFlow listedFlow, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listedFlow.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
            protocolMarshaller.marshall(listedFlow.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(listedFlow.getFlowArn(), FLOWARN_BINDING);
            protocolMarshaller.marshall(listedFlow.getName(), NAME_BINDING);
            protocolMarshaller.marshall(listedFlow.getSourceType(), SOURCETYPE_BINDING);
            protocolMarshaller.marshall(listedFlow.getStatus(), STATUS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Computes $x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1, without a slow divide.

private function modNn(int $x) : int
    {
        while ($x >= $this->blockSize) {
            $x -= $this->blockSize;
            $x = ($x >> $this->symbolSize) + ($x & $this->blockSize);
        }

        return $x;
    }

func builtinChar(args []types.Datum, ctx context.Context) (d types.Datum, err error) {
	// The kinds of args are int or string, and the last one represents charset.
	var resultStr string
	var intSlice = make([]int64, 0, len(args)-1)

	for _, datum := range args[:len(args)-1] {
		switch datum.Kind() {
		case types.KindNull:
			continue
		case types.KindString:
			i, err := datum.ToInt64(ctx.GetSessionVars().StmtCtx)
			if err != nil {
				d.SetString(resultStr)
				return d, nil
			}
			intSlice = append(intSlice, i)
		case types.KindInt64, types.KindUint64, types.KindMysqlHex, types.KindFloat32, types.KindFloat64, types.KindMysqlDecimal:
			x, err := datum.Cast(ctx.GetSessionVars().StmtCtx, types.NewFieldType(mysql.TypeLonglong))
			if err != nil {
				return d, errors.Trace(err)
			}
			intSlice = append(intSlice, x.GetInt64())
		default:
			return d, errors.Errorf("Char invalid args, need int or string but get %T", args[0].GetValue())
		}
	}

	resultStr = string(convertInt64ToBytes(intSlice))

	// The last argument represents the charset name after "using".
	// If it is nil, the default charset utf8 is used.
	argCharset := args[len(args)-1]
	if !argCharset.IsNull() {
		char, err := argCharset.ToString()
		if err != nil {
			return d, errors.Trace(err)
		}

		if strings.ToLower(char) == "ascii" || strings.HasPrefix(strings.ToLower(char), "utf8") {
			d.SetString(resultStr)
			return d, nil
		}

		encoding, _ := charset.Lookup(char)
		if encoding == nil {
			return d, errors.Errorf("unknown encoding: %s", char)
		}

		resultStr, _, err = transform.String(encoding.NewDecoder(), resultStr)
		if err != nil {
			log.Printf("Convert %s to %s with error: %v", resultStr, char, err)
			return d, errors.Trace(err)
		}
	}
	d.SetString(resultStr)
	return d, nil
}

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


Question:
// Parse - Will parse out message received from Freeswitch and basically build it accordingly for later use.
// However, in case of any issues func will return error.

func (m *Message) Parse() error {

	cmr, err := m.tr.ReadMIMEHeader()

	if err != nil && err.Error() != "EOF" {
		Error(ECouldNotReadMIMEHeaders, err)
		return err
	}

	if cmr.Get("Content-Type") == "" {
		Debug("Not accepting message because of empty content type. Just whatever with it ...")
		return fmt.Errorf("Parse EOF")
	}

	// Will handle content length by checking if appropriate lenght is here and if it is than
	// we are going to read it into body
	if lv := cmr.Get("Content-Length"); lv != "" {
		l, err := strconv.Atoi(lv)

		if err != nil {
			Error(EInvalidContentLength, err)
			return err
		}

		m.Body = make([]byte, l)

		if _, err := io.ReadFull(m.r, m.Body); err != nil {
			Error(ECouldNotReadyBody, err)
			return err
		}
	}

	msgType := cmr.Get("Content-Type")

	Debug("Got message content (type: %s). Searching if we can handle it ...", msgType)

	if !StringInSlice(msgType, AvailableMessageTypes) {
		return fmt.Errorf(EUnsupportedMessageType, msgType, AvailableMessageTypes)
	}

	// Assing message headers IF message is not type of event-json
	if msgType != "text/event-json" {
		for k, v := range cmr {

			m.Headers[k] = v[0]

			// Will attempt to decode if % is discovered within the string itself
			if strings.Contains(v[0], "%") {
				m.Headers[k], err = url.QueryUnescape(v[0])

				if err != nil {
					Error(ECouldNotDecode, err)
					continue
				}
			}
		}
	}

	switch msgType {
	case "text/disconnect-notice":
		for k, v := range cmr {
			Debug("Message (header: %s) -> (value: %v)", k, v)
		}
	case "command/reply":
		reply := cmr.Get("Reply-Text")

		if strings.Contains(reply, "-ERR") {
			return fmt.Errorf(EUnsuccessfulReply, reply[5:])
		}
	case "api/response":
		if strings.Contains(string(m.Body), "-ERR") {
			return fmt.Errorf(EUnsuccessfulReply, string(m.Body)[5:])
		}
	case "text/event-json":
		// OK, what is missing here is a way to interpret other JSON types - it expects string only (understandably
		// because the FS events are generally "string: string") - extract into empty interface and migrate only strings.
		// i.e. Event CHANNEL_EXECUTE_COMPLETE - "variable_DP_MATCH":["a=rtpmap:101 telephone-event/8000","101"]
		var decoded map[string]interface{}

		if err := json.Unmarshal(m.Body, &decoded); err != nil {
			return err
		}

		// Copy back in:
		for k, v := range decoded {
			switch v.(type) {
			case string:
				m.Headers[k] = v.(string)
			default:
				//delete(m.Headers, k)
				Warning("Removed non-string property (%s)", k)
			}
		}

		if v, _ := m.Headers["_body"]; v != "" {
			m.Body = []byte(v)
			delete(m.Headers, "_body")
		} else {
			m.Body = []byte("")
		}

	case "text/event-plain":
		r := bufio.NewReader(bytes.NewReader(m.Body))

		tr := textproto.NewReader(r)

		emh, err := tr.ReadMIMEHeader()

		if err != nil {
			return fmt.Errorf(ECouldNotReadMIMEHeaders, err)
		}

		if vl := emh.Get("Content-Length"); vl != "" {
			length, err := strconv.Atoi(vl)

			if err != nil {
				Error(EInvalidContentLength, err)
				return err
			}

			m.Body = make([]byte, length)

			if _, err = io.ReadFull(r, m.Body); err != nil {
				Error(ECouldNotReadyBody, err)
				return err
			}
		}
	}

	return nil
}

func (c *Client) ListChannels() (rec []ChannelInfo, err error) {
	req, err := newGETRequest(c, "channels")
	if err != nil {
		return []ChannelInfo{}, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return []ChannelInfo{}, err
	}

	return rec, nil
}

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


Question:
Get a class properties. (execute DbGetClassPropertyList on DB device)

@param name
The class name
@param propertyNames
The properties names
@return
@throws DevFailed

@Override
    public Map<String, String[]> getClassProperties(final String name, final String... propertyNames) throws DevFailed {
        Map<String, String[]> map;
        if (propertyNames.length == 0) {
            map = getProperties(PropertyType.Class, name);
        } else {
            map = getProperty(PropertyType.Class, name, propertyNames);
        }
        return map;
    }

public function getTableFields($table, $withPrefix = false)
    {
        $fullTable = $withPrefix ? $table : $this->getTable($table);
        if (isset($this->tableFields[$fullTable])) {
            return $this->tableFields[$fullTable];
        } else {
            $fields = array();
            switch ($this->driver) {
                case 'mysql':
                    $tableInfo = $this->fetchAll("SHOW COLUMNS FROM $fullTable");
                    $fields = $this->filter($tableInfo, 'Field');
                    break;

                case 'sqlite':
                    $tableInfo = $this->fetchAll("PRAGMA table_info($fullTable)");
                    $fields = $this->filter($tableInfo, 'name');
                    break;

                case 'pgsql':
                    $tableInfo = $this->fetchAll(
                        "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS
                        WHERE table_catalog = ? AND table_name = ?
                        ORDER BY dtd_identifier ASC",
                        array($this->dbname, $fullTable)
                    );
                    $fields = $this->filter($tableInfo, 'column_name');
            }
            if (empty($fields)) {
                // For SQLite and PostgreSQL
                throw new \PDOException(sprintf('Table or view "%s" not found', $fullTable));
            }
            return $this->tableFields[$table] = $fields;
        }
    }

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


Question: // UnmarshalValidatorData converts the bytes input to typed data

func UnmarshalValidatorData(data interface{}) (ValidatorData, error) {
	raw, ok := data.(map[string]interface{})
	if !ok {
		return ValidatorData{}, errors.New("validator input is not a map[string]interface{}")
	}
	addr, ok := raw["address"].(string)
	if !ok {
		return ValidatorData{}, errors.New("validator address is not sent as a string")
	}
	addrBytes, err := hexutil.Decode(addr)
	if err != nil {
		return ValidatorData{}, err
	}
	if !ok || len(addrBytes) == 0 {
		return ValidatorData{}, errors.New("validator address is undefined")
	}

	message, ok := raw["message"].(string)
	if !ok {
		return ValidatorData{}, errors.New("message is not sent as a string")
	}
	messageBytes, err := hexutil.Decode(message)
	if err != nil {
		return ValidatorData{}, err
	}
	if !ok || len(messageBytes) == 0 {
		return ValidatorData{}, errors.New("message is undefined")
	}

	return ValidatorData{
		Address: common.BytesToAddress(addrBytes),
		Message: messageBytes,
	}, nil
}

public static List<Metric> toValidValues(List<Metric> metrics) {
    return metrics.stream().map(ValidCharacters::toValidValue).collect(Collectors.toList());
  }

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


Question:
Override parent to lazy-load object store.

{@inheritdoc}

protected function getContainer()
    {
        if (!$this->objectStore) {
            $this->objectStore = $this->objectStoreFactory->getObjectStore();
        }

        return parent::getContainer();
    }

public static function get( $id ) {
		if ( file_exists( Utils\get_snapshot_directory() . $id . '/meta.json' ) ) {
			$meta_file_contents = file_get_contents( Utils\get_snapshot_directory() . $id . '/meta.json' );
			$meta               = json_decode( $meta_file_contents, true );
		} else {
			$meta = [];
		}

		/**
		 * Backwards compant - need to fill in repo before we started saving repo in meta.
		 */
		if ( empty( $meta['repository'] ) ) {
			Log::instance()->write( 'Legacy snapshot found without repository. Assuming default repository.', 1, 'warning' );

			$meta['repository'] = RepositoryManager::instance()->getDefault();
		}

		return new self( $id, $meta['repository'], $meta );
	}

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


Question:
Return true if `cb` has been decorated with :func:`depsignal` for the given
    signal, class and connection mode.

def is_depsignal_handler(class_, signal_name, cb, *, defer=False):

    try:
        handlers = get_magic_attr(cb)
    except AttributeError:
        return False

    return _depsignal_spec(class_, signal_name, cb, defer) in handlers

def search_db(self, search):

        def search_callback(_, address, balance):
            """

            :param _:
            :param address: The address of the contract with the code in search
            :param balance: The balance of the corresponding contract
            """
            print("Address: " + address + ", balance: " + str(balance))

        try:
            self.leveldb.search(search, search_callback)

        except SyntaxError:
            raise CriticalError("Syntax error in search expression.")

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


Question:
Get the op definition of a given
tensorflow op.

Note that if the name does not exist,
an {@link ND4JIllegalStateException} will be thrown
@param name the name of the op
@return the op definition for a given op

public OpDef getOpDefByTensorflowName(String name) {
        if(!tensorflowOpDescriptors.containsKey(name)) {
            throw new ND4JIllegalStateException("No op found with name " + name);
        }

        return tensorflowOpDescriptors.get(name);
    }

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

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

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

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

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

        self.send_queue.append(message)

        return future

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


Question:
Get module of all modules in the system.

@return array
Module list.

protected function getAllModules()
    {
        return $this->extensionManager->discoverModules()
                    ->showInstalled()
                    ->showUninstalled()
                    ->showNoCore()
                    ->showCore()
                    ->getList(true);
    }

public function walk($callback, $output = null)
    {
        if ($output === null) {
            $output = clone $this;
            $output->exchangeArray([]);
        } elseif (is_string($output) and class_exists($output)) {
            $output = new $output();
        }

        foreach ($this as $key => $value) {
            $output[$key] = $callback($value, $key);
        }

        return $output;
    }

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


Question:
Return a polygon framing the specified tile.

@param x the tile x-position coordinate.
@param y the tile y-position coordinate.

public static Polygon getTilePolygon (
        MisoSceneMetrics metrics, int x, int y)
    {
        return getFootprintPolygon(metrics, x, y, 1, 1);
    }

public function getParameter($name)
	{
		$chunks = explode('.', $name);

		$name = $chunks[0] .
			(isset($chunks[1]) ? '.' . $chunks[1] : '');

		if (!isset($this->parameters[$name])) {
			throw new ReferenceException(sprintf('Parameter "%s" is not defined in the container', $name));
		}

		$value = $this->parameters[$name];

		if (count($chunks) > 2) {
			$path = array_slice($chunks, 2);

			while ($key = array_shift($path)) {
				if (!array_key_exists($key, $value)) {
					throw new ReferenceException(sprintf('Lost at sub-key "%s" for parameter "%s"', $key, $name));
				}

				$value = $value[$key];
			}
		}

		return $value;
	}

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


Question: Liberty change start

@FFDCIgnore({Throwable.class})
    private static Method getJAXRSGetCurrentMessageMethod() {
        Method m;
        try {
            Class<?> jaxrsUtilsClass = Class.forName("org.apache.cxf.jaxrs.utils.JAXRSUtils");
            m = ReflectionUtil.getDeclaredMethod(jaxrsUtilsClass, "getCurrentMessage");
        } catch (Throwable t) {
            // expected in non-JAX-RS server environments
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.log(Level.FINEST, "Caught exception getting JAXRUtils class", t);
            }
            m = null;
        }
        return m;
    }

func (h *Heartbeater) SetStrategy(strategy Strategy) *Heartbeater {
	h.Strategy = strategy

	return h
}

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


Question: // SetFileShareStatus sets the FileShareStatus field's value.

func (s *FileShareInfo) SetFileShareStatus(v string) *FileShareInfo {
	s.FileShareStatus = &v
	return s
}

def changed(self):

        if not self.parents:
            return []
        return ChangedFileNodesGenerator([n for n in
                                self._get_paths_for_status('modified')], self)

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


Question:
Field has to be greater than or equal to X characters long.

@param int $len
@param string $message
@return FormValidator

public function minlength($len, $message = null)
    {
        $this->setRule(__FUNCTION__, function($val, $args)
                       {
                           return !(strlen(trim($val)) < $args[0]);
                       }, $message, array($len));
        return $this;
    }

def validate_wrap(self, value):
        ''' '''
        self._validate_wrap_type(value)
        self._length_valid(value)
        for v in value:
            self._validate_child_wrap(v)

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


Question: Is this widget required?

def is_widget_required_attribute(widget):

    if not widget.is_required:
        return False
    if isinstance(widget, WIDGETS_NO_REQUIRED):
        return False
    return True

public String getRequiredString(String name) {
        String value = getString(name, null);
        if (value != null) {
            return value.trim();
        }
        throw new PippoRuntimeException("Setting '{}' has not been configured!", name);
    }

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


Question:
We add the JIP to the jobInitQueue, which is processed
asynchronously to handle split-computation and build up
the right TaskTracker/Block mapping.

@Override
  public void jobAdded(JobInProgress job) {
    synchronized (jobInitQueue) {
      jobInitQueue.add(job);
      resortInitQueue();
      jobInitQueue.notifyAll();
    }

  }

def wait_multi(self, channels, allowed_methods=None, timeout=None):
        """"""
        chanmap = dict((chan.channel_id, chan) for chan in channels)
        chanid, method_sig, args, content = self._wait_multiple(
                chanmap.keys(), allowed_methods, timeout=timeout)

        channel = chanmap[chanid]

        if content \
        and channel.auto_decode \
        and hasattr(content, 'content_encoding'):
            try:
                content.body = content.body.decode(content.content_encoding)
            except Exception:
                pass

        amqp_method = channel._METHOD_MAP.get(method_sig, None)

        if amqp_method is None:
            raise Exception('Unknown AMQP method (%d, %d)' % method_sig)

        if content is None:
            return amqp_method(channel, args)
        else:
            return amqp_method(channel, args, content)

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


Question: Checks if a user is a chat admin

def is_chat_admin(user):
    """"""
    from indico_chat.plugin import ChatPlugin
    return ChatPlugin.settings.acls.contains_user('admins', user)

public function getMaterialCount()
    {
        $result = $this->httpGet(self::WECHAT_MATERIAL_COUNT_GET_PREFIX, [
            'access_token' => $this->getAccessToken()
        ]);
        return !array_key_exists('errorcode', $result) ? $result : false;
    }

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


Question: Decorator to note which object methods require authorization.

def requires_auth(func):
    """"""
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        auth = False
        if hasattr(self, '_session'):
            auth = (self._session.auth or
                    self._session.headers.get('Authorization'))

        if auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper

public function getAuthorizeLink($website = 0)
    {
        //base url, check for custom oauth domain
        if ($this->isAuthorizeCustomDomain($website)) {
            $baseUrl = $this->getWebsiteConfig(self::XML_PATH_CONNECTOR_CUSTOM_DOMAIN)
                . self::API_CONNECTOR_OAUTH_URL_AUTHORISE;
        } else {
            $baseUrl = $this->getRegionAuthorize($website) . self::API_CONNECTOR_OAUTH_URL_AUTHORISE;
        }

        return $baseUrl;
    }

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


Question: // SetFunctionName sets the FunctionName field's value.

func (s *UpdateEventSourceMappingInput) SetFunctionName(v string) *UpdateEventSourceMappingInput {
	s.FunctionName = &v
	return s
}

func (s *LoadBalancerDescription) SetHealthCheck(v *HealthCheck) *LoadBalancerDescription {
	s.HealthCheck = v
	return s
}

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


Question:
/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.isup.ISUPMessageImpl#decodeMandatoryParameters (byte[], int)

protected int decodeMandatoryParameters(ISUPParameterFactory parameterFactory, byte[] b, int index)
            throws ParameterException {
        int localIndex = index;
        index += super.decodeMandatoryParameters(parameterFactory, b, index);
        if (b.length - index > 1) {

            try {
                byte[] informationInd = new byte[2];
                informationInd[0] = b[index++];
                informationInd[1] = b[index++];
                InformationIndicators bci = parameterFactory.createInformationIndicators();
                ((AbstractISUPParameter) bci).decode(informationInd);
                this.setInformationIndicators(bci);
            } catch (Exception e) {
                // AIOOBE or IllegalArg
                throw new ParameterException("Failed to parse BackwardCallIndicators due to: ", e);
            }

            // return 3;
            return index - localIndex;
        } else {
            throw new IllegalArgumentException("byte[] must have atleast 2 octets");
        }
    }

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question:
Create a JsonParser for a given json node.
@param jsonNode the json node
@return the json parser
@throws IOException

private static JsonParser newJsonParserForNode(JsonNode jsonNode) throws IOException {
        JsonParser parser = new JsonFactory().createParser(jsonNode.toString());
        parser.nextToken();
        return parser;
    }

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

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


Question: Converts a GitHub search JSON into a InspectionReport

def parse_results(query, results)
      report = InspectionReport.new
      report.url = "https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓"
      report.query = query
      report.total_results = results['total_count']
      report.issues = results['items'].map { |item| Issue.new(item) }
      report
    end

static function fromJson(object $map): self {
    return new static(
      isset($map->found) && is_int($map->found) ? $map->found : 0,
      isset($map->hit) && is_int($map->hit) ? $map->hit : 0,
      isset($map->data) && is_array($map->data) ? array_map([LineData::class, 'fromJson'], $map->data) : []
    );
  }

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


Question:
Needed AWS actions:

ec2:DescribeInstances

@return the current EC2 instance

public Instance getInstance() {
        DescribeInstancesRequest req = new DescribeInstancesRequest();
        req.setInstanceIds(Collections.singleton(this.getInstanceId()));
        DescribeInstancesResult result = this.ec2Client.describeInstances(req);
        if (result.getReservations().size() != 1) {
            throw new IllegalStateException("Found multiple instances");
        }
        List<Instance> instances = result.getReservations().get(0).getInstances();
        if (instances.size() != 1) {
            throw new IllegalStateException("Found multiple instances");
        }
        return instances.get(0);
    }

def list():
    ""
    for node in env.nodes:
        print "%s (%s, %s)" % (node.tags["Name"], node.ip_address,
            node.private_ip_address)

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