_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q46400 | classifyParameters | train | function classifyParameters (parameters) {
const { req, opts } = R.groupBy(p => p.required ? 'req' : 'opts', parameters)
const { path, query, body } = R.groupBy(p => p.in, parameters)
return {
pathArgs: R.pluck('name', path || []),
queryArgs: R.pluck('name', query || []),
bodyArgs: R.pluck('name', bo... | javascript | {
"resource": ""
} |
q46401 | pascalizeParameters | train | function pascalizeParameters (parameters) {
return parameters.map(o => R.assoc('name', snakeToPascal(o.name), o))
} | javascript | {
"resource": ""
} |
q46402 | operationSignature | train | function operationSignature (name, req, opts) {
const args = req.length ? `${R.join(', ', R.pluck('name', req))}` : null
const opt = opts.length ? `{${R.join(', ', R.pluck('name', opts))}}` : null
return `${name} (${R.join(', ', [args, opt].filter(R.identity))})`
} | javascript | {
"resource": ""
} |
q46403 | destructureClientError | train | function destructureClientError (error) {
const { method, url } = error.config
const { status, data } = error.response
const reason = R.has('reason', data) ? data.reason : R.toString(data)
return `${method.toUpperCase()} to ${url} failed with ${status}: ${reason}`
} | javascript | {
"resource": ""
} |
q46404 | postQueryToOracle | train | async function postQueryToOracle (oracleId, query, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const senderId = await this.address()
const { tx: oracleRegisterTx, queryId } = await this.oraclePostQueryTx(R.merge(opt, {
oracleId,
senderId,
query
}))
return {
...(await this.s... | javascript | {
"resource": ""
} |
q46405 | hello | train | async function hello () {
const id = await Rpc.compose.deepProperties.rpcMethods.hello.call(this)
this.rpcSessions[id].address = await this.address()
return Promise.resolve(id)
} | javascript | {
"resource": ""
} |
q46406 | signTransaction | train | async function signTransaction (tx) {
const networkId = this.getNetworkId()
const rlpBinaryTx = Crypto.decodeBase64Check(Crypto.assertedType(tx, 'tx'))
// Prepend `NETWORK_ID` to begin of data binary
const txWithNetworkId = Buffer.concat([Buffer.from(networkId), rlpBinaryTx])
const signatures = [await this.s... | javascript | {
"resource": ""
} |
q46407 | send | train | async function send (tx, options) {
const opt = R.merge(this.Ae.defaults, options)
const signed = await this.signTransaction(tx)
return this.sendTransaction(signed, opt)
} | javascript | {
"resource": ""
} |
q46408 | spend | train | async function spend (amount, recipientId, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount: amount }))
return this.send(spendTx, opt)
} | javascript | {
"resource": ""
} |
q46409 | transferFunds | train | async function transferFunds (percentage, recipientId, options = { excludeFee: false }) {
if (percentage < 0 || percentage > 1) throw new Error(`Percentage should be a number between 0 and 1, got ${percentage}`)
const opt = R.merge(this.Ae.defaults, options)
const requestTransferAmount = BigNumber(await this.bal... | javascript | {
"resource": ""
} |
q46410 | transfer | train | async function transfer (nameId, account, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const nameTransferTx = await this.nameTransferTx(R.merge(opt, {
nameId,
accountId: await this.address(),
recipientId: account
}))
return this.send(nameTransferTx, opt)
} | javascript | {
"resource": ""
} |
q46411 | revoke | train | async function revoke (nameId, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const nameRevokeTx = await this.nameRevokeTx(R.merge(opt, {
nameId,
accountId: await this.address()
}))
return this.send(nameRevokeTx, opt)
} | javascript | {
"resource": ""
} |
q46412 | classify | train | function classify (s) {
const keys = {
ak: 'account_pubkey',
ok: 'oracle_pubkey'
}
if (!s.match(/^[a-z]{2}_.+/)) {
throw Error('Not a valid hash')
}
const klass = s.substr(0, 2)
if (klass in keys) {
return keys[klass]
} else {
throw Error(`Unknown class ${klass}`)
}
} | javascript | {
"resource": ""
} |
q46413 | update | train | async function update (nameId, target, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const nameUpdateTx = await this.nameUpdateTx(R.merge(opt, {
nameId: nameId,
accountId: await this.address(),
pointers: [R.fromPairs([['id', target], ['key', classify(target)]])]
}))
return this.sen... | javascript | {
"resource": ""
} |
q46414 | query | train | async function query (name) {
const o = await this.getName(name)
const nameId = o.id
return Object.freeze(Object.assign(o, {
pointers: o.pointers || {},
update: async (target, options) => {
return {
...(await this.aensUpdate(nameId, target, options)),
...(await this.aensQuery(name))... | javascript | {
"resource": ""
} |
q46415 | claim | train | async function claim (name, salt, waitForHeight, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
// wait until block was mined before send claim transaction
// if (waitForHeight) await this.awaitHeight(waitForHeight, { attempts: 200 })
const claimTx = await this.nameClaimTx(R.merge(opt, {
acc... | javascript | {
"resource": ""
} |
q46416 | preclaim | train | async function preclaim (name, options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const _salt = salt()
const height = await this.height()
const hash = await commitmentHash(name, _salt)
const preclaimTx = await this.namePreclaimTx(R.merge(opt, {
accountId: await this.address(),
commitmentI... | javascript | {
"resource": ""
} |
q46417 | handleCallError | train | async function handleCallError (result) {
const error = Buffer.from(result.returnValue).toString()
if (isBase64(error.slice(3))) {
const decodedError = Buffer.from(error.slice(3), 'base64').toString()
throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error... | javascript | {
"resource": ""
} |
q46418 | contractCall | train | async function contractCall (source, address, name, args = [], options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const tx = await this.contractCallTx(R.merge(opt, {
callerId: await this.address(),
contractId: address,
callData: await this.contractEncodeCall(source, name, args)
}))
con... | javascript | {
"resource": ""
} |
q46419 | contractDeploy | train | async function contractDeploy (code, source, initState = [], options = {}) {
const opt = R.merge(this.Ae.defaults, options)
const callData = await this.contractEncodeCall(source, 'init', initState)
const ownerId = await this.address()
const { tx, contractId } = await this.contractCreateTx(R.merge(opt, {
ca... | javascript | {
"resource": ""
} |
q46420 | contractCompile | train | async function contractCompile (source, options = {}) {
const bytecode = await this.compileContractAPI(source, options)
return Object.freeze(Object.assign({
encodeCall: async (name, args) => this.contractEncodeCall(source, name, args),
deploy: async (init, options = {}) => this.contractDeploy(bytecode, sour... | javascript | {
"resource": ""
} |
q46421 | transform | train | function transform (type, value) {
let { t, generic } = readType(type)
// contract TestContract = ...
// fn(ct: TestContract)
if (typeof value === 'string' && value.slice(0, 2) === 'ct') t = SOPHIA_TYPES.address // Handle Contract address transformation
switch (t) {
case SOPHIA_TYPES.string:
retur... | javascript | {
"resource": ""
} |
q46422 | readType | train | function readType (type, returnType = false) {
const [t] = Array.isArray(type) ? type : [type]
// Base types
if (typeof t === 'string') return { t }
// Map, Tuple, List
if (typeof t === 'object') {
const [[baseType, generic]] = Object.entries(t)
return { t: baseType, generic }
}
} | javascript | {
"resource": ""
} |
q46423 | validate | train | function validate (type, value) {
const { t } = readType(type)
if (value === undefined || value === null) return { require: true }
switch (t) {
case SOPHIA_TYPES.int:
return isNaN(value) || ['boolean'].includes(typeof value)
case SOPHIA_TYPES.bool:
return typeof value !== 'boolean'
case S... | javascript | {
"resource": ""
} |
q46424 | transformDecodedData | train | function transformDecodedData (aci, result, { skipTransformDecoded = false, addressPrefix = 'ak' } = {}) {
if (skipTransformDecoded) return result
const { t, generic } = readType(aci, true)
switch (t) {
case SOPHIA_TYPES.bool:
return !!result.value
case SOPHIA_TYPES.address:
return result.val... | javascript | {
"resource": ""
} |
q46425 | prepareArgsForEncode | train | function prepareArgsForEncode (aci, params) {
if (!aci) return params
// Validation
const validation = aci.arguments
.map(
({ type }, i) =>
validate(type, params[i])
? `Argument index: ${i}, value: [${params[i]}] must be of type [${type}]`
: false
).filter(e => e)
if (v... | javascript | {
"resource": ""
} |
q46426 | getFunctionACI | train | function getFunctionACI (aci, name) {
const fn = aci.functions.find(f => f.name === name)
if (!fn && name !== 'init') throw new Error(`Function ${name} doesn't exist in contract`)
return fn
} | javascript | {
"resource": ""
} |
q46427 | getContractInstance | train | async function getContractInstance (source, { aci, contractAddress } = {}) {
aci = aci || await this.contractGetACI(source)
const instance = {
interface: aci.interface,
aci: aci.encoded_aci.contract,
source,
compiled: null,
deployInfo: { address: contractAddress }
}
/**
* Compile contract... | javascript | {
"resource": ""
} |
q46428 | setKeypair | train | function setKeypair (keypair) {
if (keypair.hasOwnProperty('priv') && keypair.hasOwnProperty('pub')) {
keypair = { secretKey: keypair.priv, publicKey: keypair.pub }
console.warn('pub/priv naming for accounts has been deprecated, please use secretKey/publicKey')
}
secrets.set(this, {
secretKey: Buffer.... | javascript | {
"resource": ""
} |
q46429 | deserializeField | train | function deserializeField (value, type, prefix) {
if (!value) return ''
switch (type) {
case FIELD_TYPES.int:
return readInt(value)
case FIELD_TYPES.id:
return readId(value)
case FIELD_TYPES.ids:
return value.map(readId)
case FIELD_TYPES.bool:
return value[0] === 1
case F... | javascript | {
"resource": ""
} |
q46430 | calculateTtl | train | async function calculateTtl (ttl = 0, relative = true) {
if (ttl === 0) return 0
if (ttl < 0) throw new Error('ttl must be greater than 0')
if (relative) {
const { height } = await this.api.getCurrentKeyBlock()
return +(height) + ttl
}
return ttl
} | javascript | {
"resource": ""
} |
q46431 | getAccountNonce | train | async function getAccountNonce (accountId, nonce) {
if (nonce) return nonce
const { nonce: accountNonce } = await this.api.getAccountByPubkey(accountId).catch(() => ({ nonce: 0 }))
return accountNonce + 1
} | javascript | {
"resource": ""
} |
q46432 | str2buf | train | function str2buf (str, enc) {
if (!str || str.constructor !== String) return str
if (!enc && isHex(str)) enc = 'hex'
if (!enc && isBase64(str)) enc = 'base64'
return Buffer.from(str, enc)
} | javascript | {
"resource": ""
} |
q46433 | deriveKey | train | async function deriveKey (password, nonce, options = {
kdf_params: DEFAULTS.crypto.kdf_params,
kdf: DEFAULTS.crypto.kdf
}) {
if (typeof password === 'undefined' || password === null || !nonce) {
throw new Error('Must provide password and nonce to derive a key')
}
if (!DERIVED_KEY_FUNCTIONS.hasOwnProperty... | javascript | {
"resource": ""
} |
q46434 | marshal | train | function marshal (name, derivedKey, privateKey, nonce, salt, options = {}) {
const opt = Object.assign({}, DEFAULTS.crypto, options)
return Object.assign(
{ name, version: 1, public_key: getAddressFromPriv(privateKey), id: uuid.v4() },
{
crypto: Object.assign(
{
secret_type: opt.secr... | javascript | {
"resource": ""
} |
q46435 | train | function(email, firstName, lastName, companyName, password) {
var _this = this;
GetClient.call(_this, email, firstName, lastName, companyName);
_this['password'] = password;
} | javascript | {
"resource": ""
} | |
q46436 | train | function(email, firstName, lastName, companyName, address, plan, relay) {
var _this = this;
GetExtendedClient.call(_this, email, firstName, lastName, companyName, address);
_this['plan'] = plan;
_this['relay'] = relay;
} | javascript | {
"resource": ""
} | |
q46437 | uint8ArrayToString | train | function uint8ArrayToString(arr, offset, limit) {
offset = offset || 0;
limit = limit || arr.length - offset;
let str = '';
for (let i = offset; i < offset + limit; i++) {
str += String.fromCharCode(arr[i]);
}
return str;
} | javascript | {
"resource": ""
} |
q46438 | stringToUint8Array | train | function stringToUint8Array(str) {
const arr = new Uint8Array(str.length);
for (let i = 0, j = str.length; i < j; i++) {
arr[i] = str.charCodeAt(i);
}
return arr;
} | javascript | {
"resource": ""
} |
q46439 | containsToken | train | function containsToken(message, token, offset=0) {
if (offset + token.length > message.length) {
return false;
}
let index = offset;
for (let i = 0; i < token.length; i++) {
if (token[i] !== message[index++]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q46440 | findToken | train | function findToken(message, token, offset=0, maxSearchLength) {
let searchLength = message.length;
if (maxSearchLength) {
searchLength = Math.min(offset + maxSearchLength, message.length);
}
for (let i = offset; i < searchLength; i++) {
// If the first value of the message matches
// the first valu... | javascript | {
"resource": ""
} |
q46441 | multipartDecode | train | function multipartDecode(response) {
const message = new Uint8Array(response);
/* Set a maximum length to search for the header boundaries, otherwise
findToken can run for a long time
*/
const maxSearchLength = 1000;
// First look for the multipart mime header
let separator = stringToU... | javascript | {
"resource": ""
} |
q46442 | camelCase | train | function camelCase(text) {
text = text || '';
return text.replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => {
return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '');
} | javascript | {
"resource": ""
} |
q46443 | createCryptobox | train | async function createCryptobox(storeName, amountOfPreKeys = 1) {
const engine = new MemoryEngine();
await engine.init(storeName);
return new Cryptobox(engine, amountOfPreKeys);
} | javascript | {
"resource": ""
} |
q46444 | initialSetup | train | async function initialSetup() {
const alice = await createCryptobox('alice', 1);
await alice.create();
const bob = await createCryptobox('bob', 1);
await bob.create();
const bobBundle = Proteus.keys.PreKeyBundle.new(
bob.identity.public_key,
await bob.store.load_prekey(Proteus.keys.PreKey.MAX_PREKEY... | javascript | {
"resource": ""
} |
q46445 | encryptBeforeDecrypt | train | async function encryptBeforeDecrypt({alice, bob}, messageCount) {
const numbers = numbersInArray(messageCount);
// Encryption
process.stdout.write(`Measuring encryption time for "${messageCount}" messages ... `);
let startTime = process.hrtime();
const encryptedMessages = await Promise.all(
numbers.map(v... | javascript | {
"resource": ""
} |
q46446 | csvToMarkdown | train | function csvToMarkdown(csvContent, delimiter, hasHeader) {
if (delimiter === void 0) { delimiter = "\t"; }
if (hasHeader === void 0) { hasHeader = false; }
if (delimiter != "\t") {
csvContent = csvContent.replace(/\t/g, " ");
}
var columns = csvContent.split("\n");
var tabularData = [... | javascript | {
"resource": ""
} |
q46447 | writeClientLibJson | train | function writeClientLibJson(item, options) {
var content = {
'jcr:primaryType': 'cq:ClientLibraryFolder'
};
// if categories is a config entry append the values to the array, else use item.name
if (item.hasOwnProperty('categories')) {
content.categories = item['categories'];
} else {
content.cate... | javascript | {
"resource": ""
} |
q46448 | writeClientLibXml | train | function writeClientLibXml(item, options) {
var content = '<?xml version="1.0" encoding="UTF-8"?>' +
'<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"' +
' jcr:primaryType="cq:ClientLibraryFolder"';
if (item.hasOwnProperty('categories')) {
var fi... | javascript | {
"resource": ""
} |
q46449 | start | train | function start(itemList, options, done) {
if (_.isFunction(options)) {
done = options;
options = {};
}
if (!_.isArray(itemList)) {
itemList = [itemList];
}
if (options.context || options.cwd) {
options.cwd = options.context || options.cwd;
process.chdir(options.cwd);
}
if (options.... | javascript | {
"resource": ""
} |
q46450 | normalizeAssets | train | function normalizeAssets(clientLibPath, assets) {
var list = assets;
// transform object to array
if (!_.isArray(assets)) {
list = [];
_.keys(assets).forEach(function (assetKey) {
var assetItem = assets[assetKey];
// check/transform short version
if (_.isArray(assetItem)) {
as... | javascript | {
"resource": ""
} |
q46451 | processItem | train | function processItem(item, options, processDone) {
if (!item.path) {
item.path = options.clientLibRoot;
}
options.verbose && console.log("\n\nprocessing clientlib: " + item.name);
// remove current files if exists
removeClientLib(item, function (err) {
var clientLibPath = item.outputPath || path.j... | javascript | {
"resource": ""
} |
q46452 | checkFeatureChildNode | train | function checkFeatureChildNode(node, restrictedPatterns, errors) {
checkNameAndDescription(node, restrictedPatterns, errors);
node.steps.forEach(function(step) {
// Use the node type of the parent to determine which rule configuration to use
checkStepNode(step, restrictedPatterns[node.type], errors);
});
... | javascript | {
"resource": ""
} |
q46453 | getFeatureFiles | train | function getFeatureFiles(args, ignoreArg) {
var files = [];
var patterns = args.length ? args : ['.'];
patterns.forEach(function(pattern) {
// First we need to fix up the pattern so that it only matches .feature files
// and it's in the format that glob expects it to be
var fixedPattern;
if (patt... | javascript | {
"resource": ""
} |
q46454 | getContinuousLogs | train | function getContinuousLogs (api, appId, before, after, search, deploymentId) {
function makeUrl (retryTimestamp) {
const newAfter = retryTimestamp === null || after.getTime() > retryTimestamp.getTime() ? after : retryTimestamp;
return getWsLogUrl(appId, newAfter.toISOString(), search, deploymentId);
};
r... | javascript | {
"resource": ""
} |
q46455 | openStream | train | function openStream (makeUrl, authorization, endTimestamp, retries = MAX_RETRY_COUNT) {
const endTs = endTimestamp || null;
const s_websocket = openWebSocket(makeUrl(endTs), authorization);
// Stream which contains only one element: the date at which the websocket closed
const s_endTimestamp = s_websocket.filt... | javascript | {
"resource": ""
} |
q46456 | randomToken | train | function randomToken () {
return crypto.randomBytes(20).toString('base64').replace(/\//g, '-').replace(/\+/g, '_').replace(/=/g, '');
} | javascript | {
"resource": ""
} |
q46457 | performPreorder | train | function performPreorder (api, orgaId, name, planId, providerId, region) {
const params = orgaId ? [orgaId] : [];
return api.owner(orgaId).addons.preorders.post().withParams(params).send(JSON.stringify({
name: name,
plan: planId,
providerId: providerId,
region: region,
}));
} | javascript | {
"resource": ""
} |
q46458 | setupPageTracking | train | function setupPageTracking(options, Vue) {
const router = options.router
const baseName = options.baseName || '(Vue App)'
router.beforeEach( (route, from, next) => {
const name = baseName + ' / ' + route.name;
Vue.appInsights.startTrackPage(name)
next()
})
router.afterEach( route => {
cons... | javascript | {
"resource": ""
} |
q46459 | readable | train | function readable(options) {
options = options || {};
if (!options.region || typeof options.region !== 'string') return invalid();
if (!options.group || typeof options.group !== 'string') return invalid();
if (options.start && typeof options.start !== 'number') return invalid();
if (options.end && typeof opt... | javascript | {
"resource": ""
} |
q46460 | camelCase | train | function camelCase(str) {
if (str.indexOf('-') > -1) {
str = str.replace(/-\w/g, function (letter) {
return letter.substr(1).toUpperCase();
});
}
return str;
} | javascript | {
"resource": ""
} |
q46461 | getData | train | function getData(prop, data, hasSource) {
var value, obj;
if (!data) {
data = this.data;
}
for (var i = 0, l = data.length; i < l; i++) {
obj = data[i];
if (obj) {
value = obj[prop];
if (value !== undefined) {
if (hasSource) {
return {
source: obj,
... | javascript | {
"resource": ""
} |
q46462 | newContext | train | function newContext(context, params) {
if (!params) {
return context;
}
return assign({}, context, {
data: params.data ? arrayPush(params.data, context.data) : context.data,
parent: params.newParent ? context : context.parent,
index: 'index' in params ? params.index : context.index,
item: 'it... | javascript | {
"resource": ""
} |
q46463 | registerExtension | train | function registerExtension(name, extension, options, mergeConfig) {
var params = name;
if (!isObject(name)) {
params = {};
params[name] = {
extension: extension,
options: options
};
}
each(params, function (v, name) {
if (v) {
var _extension = v.extension,
_options3... | javascript | {
"resource": ""
} |
q46464 | _ | train | function _(obj, prop, options) {
if (obj == null) {
return obj;
}
return getAccessorData(obj[prop], options.context);
} | javascript | {
"resource": ""
} |
q46465 | int | train | function int(val) {
var radix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
var ret = parseInt(val, radix);
return isNaN(ret) ? 0 : ret;
} | javascript | {
"resource": ""
} |
q46466 | float | train | function float(val, bit) {
var ret = parseFloat(val);
return isNaN(ret) ? 0 : bit != null ? ret.toFixed(bit) : ret;
} | javascript | {
"resource": ""
} |
q46467 | registerFilter | train | function registerFilter(name, filter, options, mergeConfig) {
var params = name;
if (!isObject(name)) {
params = {};
params[name] = {
filter: filter,
options: options
};
}
each(params, function (v, name) {
if (v) {
var _filter = v.filter,
_options = v.options;
... | javascript | {
"resource": ""
} |
q46468 | _clearRepeat | train | function _clearRepeat(str) {
let ret = '',
i = 0,
l = str.length,
char;
for (; i < l; i++) {
char = str[i];
if (ret.indexOf(char) < 0) {
ret += char;
}
}
return ret;
} | javascript | {
"resource": ""
} |
q46469 | getOpenTagParams | train | function getOpenTagParams(tag, tmplRule) {
var pattern = tmplRule.openTagParams,
matchArr,
ret;
while (matchArr = pattern.exec(tag)) {
var key = matchArr[1];
if (key === '/') {
//If match to the last of "/", then continue the loop.
continue;
}
if (!ret) {
ret = [];
... | javascript | {
"resource": ""
} |
q46470 | addParamsEx | train | function addParamsEx(node, parent, isDirective, isSubTag) {
var exPropsName = 'paramsEx';
if (!parent[exPropsName]) {
var exPropsNode;
if (isDirective || isSubTag) {
exPropsNode = {
type: 'nj_ex',
ex: 'props',
content: [node]
};
} else {
exPropsNode = node;
... | javascript | {
"resource": ""
} |
q46471 | _setElem | train | function _setElem(elem, elemName, elemParams, elemArr, bySelfClose, tmplRule, outputH) {
var ret,
paramsEx,
fixedExTagName = fixExTagName(elemName, tmplRule);
if (fixedExTagName) {
elemName = fixedExTagName;
}
if (isEx(elemName, tmplRule, true)) {
ret = elem.substring(1, elem.length - 1);
... | javascript | {
"resource": ""
} |
q46472 | _getSplitParams | train | function _getSplitParams(elem, tmplRule, outputH) {
var extensionRule = tmplRule.extensionRule,
startRule = tmplRule.startRule,
endRule = tmplRule.endRule,
firstChar = tmplRule.firstChar,
lastChar = tmplRule.lastChar,
spreadProp = tmplRule.spreadProp,
directives = tmplRule.directiv... | javascript | {
"resource": ""
} |
q46473 | _setSelfCloseElem | train | function _setSelfCloseElem(elem, elemName, elemParams, elemArr, tmplRule, outputH) {
if (/\/$/.test(elemName)) {
elemName = elemName.substr(0, elemName.length - 1);
}
_setElem(elem, elemName, elemParams, elemArr, true, tmplRule, outputH);
} | javascript | {
"resource": ""
} |
q46474 | train | function () {
this.showHeader(this.todoList);
this.showFooter(this.todoList);
this.showTodoList(this.todoList);
this.todoList.on('all', this.updateHiddenElements, this);
this.todoList.fetch();
} | javascript | {
"resource": ""
} | |
q46475 | insidePolygon | train | function insidePolygon(rings, p) {
var inside = false;
for (var i = 0, len = rings.length; i < len; i++) {
var ring = rings[i];
for (var j = 0, len2 = ring.length, k = len2 - 1; j < len2; k = j++) {
if (rayIntersect(p, ring[j], ring[k])) inside = !inside;
}
}
return i... | javascript | {
"resource": ""
} |
q46476 | getTiles | train | function getTiles(name) {
let tiles = [];
let dir = `./node_modules/@mapbox/mvt-fixtures/real-world/${name}`;
var files = fs.readdirSync(dir);
files.forEach(function(file) {
let buffer = fs.readFileSync(path.join(dir, '/', file));
file = file.replace('.mvt', '');
let zxy = file.split('-');
tiles... | javascript | {
"resource": ""
} |
q46477 | isFootway | train | function isFootway(newVersion) {
if (
newVersion.properties &&
newVersion.properties.highway === 'footway' &&
newVersion.properties['osm:version'] === 1
) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q46478 | camelCase | train | function camelCase(string) {
if (typeof string !== 'string') {
throw new TypeError('First argument must be a string');
}
// custom property or no hyphen found
if (CUSTOM_PROPERTY_OR_NO_HYPHEN_REGEX.test(string)) {
return string;
}
// convert to camelCase
return string
.toLowerCase()
.rep... | javascript | {
"resource": ""
} |
q46479 | invertObject | train | function invertObject(obj, override) {
if (!obj || typeof obj !== 'object') {
throw new TypeError('First argument must be an object');
}
var key;
var value;
var isOverridePresent = typeof override === 'function';
var overrides = {};
var result = {};
for (key in obj) {
value = obj[key];
if... | javascript | {
"resource": ""
} |
q46480 | isCustomComponent | train | function isCustomComponent(tagName, props) {
if (tagName.indexOf('-') === -1) {
return props && typeof props.is === 'string';
}
switch (tagName) {
// These are reserved SVG and MathML elements.
// We don't mind this whitelist too much because we expect it to never grow.
// The alternative is to t... | javascript | {
"resource": ""
} |
q46481 | attributesToProps | train | function attributesToProps(attributes) {
attributes = attributes || {};
var props = {};
var propertyName;
var propertyValue;
var reactProperty;
for (propertyName in attributes) {
propertyValue = attributes[propertyName];
// custom attributes (`data-` and `aria-`)
if (isCustomAttribute(property... | javascript | {
"resource": ""
} |
q46482 | cssToJs | train | function cssToJs(style) {
if (typeof style !== 'string') {
throw new TypeError('First argument must be a string.');
}
var styleObj = {};
styleToObject(style, function(propName, propValue) {
// Check if it's not a comment node
if (propName && propValue) {
styleObj[utilities.camelCase(propName)... | javascript | {
"resource": ""
} |
q46483 | HTMLReactParser | train | function HTMLReactParser(html, options) {
if (typeof html !== 'string') {
throw new TypeError('First argument must be a string');
}
return domToReact(htmlToDOM(html, domParserOptions), options);
} | javascript | {
"resource": ""
} |
q46484 | domToReact | train | function domToReact(nodes, options) {
options = options || {};
var result = [];
var node;
var isReplacePresent = typeof options.replace === 'function';
var replacement;
var props;
var children;
for (var i = 0, len = nodes.length; i < len; i++) {
node = nodes[i];
// replace with custom React el... | javascript | {
"resource": ""
} |
q46485 | train | function ( timeCode, frameRate, dropFrame ) {
// Make this class safe for use without "new"
if (!(this instanceof Timecode)) return new Timecode( timeCode, frameRate, dropFrame);
// Get frame rate
if (typeof frameRate === 'undefined') this.frameRate = 29.97;
else if (typeof fra... | javascript | {
"resource": ""
} | |
q46486 | verifyTsConfig | train | function verifyTsConfig(configFilePath) {
/**
* @type {string[]}
*/
const warnings = [];
const createConfigFileHost = {
onUnRecoverableConfigFileDiagnostic() {},
useCaseSensitiveFileNames: false,
readDirectory: typescript.sys.readDirectory,
fileExists: typescript.sys.fileExists,
readFile: typescript.sy... | javascript | {
"resource": ""
} |
q46487 | listTimezones | train | function listTimezones () {
if (arguments.length == 0) {
throw new Error("You must set a callback");
}
if (typeof arguments[arguments.length - 1] != "function") {
throw new Error("You must set a callback");
}
var cb = arguments[arguments.length - 1]
, subset = (arguments.length > 1 ? arguments[0] ... | javascript | {
"resource": ""
} |
q46488 | pad | train | function pad (num, padLen) {
var padding = '0000';
num = String(num);
return padding.substring(0, padLen - num.length) + num;
} | javascript | {
"resource": ""
} |
q46489 | normalizeSelector | train | function normalizeSelector(selector) {
var parts = selector.match(/[^\s>]+|>/ig);
selector = (parts) ? parts.join(' ') : '';
return {
normalized: selector,
parts: parts || []
};
} | javascript | {
"resource": ""
} |
q46490 | parseEvent | train | function parseEvent(event) {
var eventParts = event.match(/^((?:start|end|update)Element|text):?(.*)/);
if (eventParts === null) {
return null;
}
var eventType = eventParts[1];
var selector = normalizeSelector(eventParts[2]);
return {
selector: selector,
type: eventType,
name: (eventParts[2]... | javascript | {
"resource": ""
} |
q46491 | getFinalState | train | function getFinalState(selector) {
if (__own.call(this._finalStates, selector.normalized)) {
var finalState = this._finalStates[selector.normalized];
} else {
var n = selector.parts.length;
var immediate = false;
this._startState[this._lastState] = true;
for (var i = 0; i < n; i++) {
var p... | javascript | {
"resource": ""
} |
q46492 | emitStart | train | function emitStart(name, attrs) {
this.emit('data', '<' + name);
for (var attr in attrs) if (__own.call(attrs, attr)) {
this.emit('data', ' ' + attr + '="' + escape(attrs[attr]) + '"');
}
this.emit('data', '>');
} | javascript | {
"resource": ""
} |
q46493 | emitElement | train | function emitElement(element, name, onLeave) {
if (Array.isArray(element)) {
var i;
for (i = 0; i < element.length - 1; i++) {
emitOneElement.call(this, element[i], name);
}
emitOneElement.call(this, element[i], name, onLeave);
} else {
emitOneElement.call(this, element, name, onLeave);
... | javascript | {
"resource": ""
} |
q46494 | emitChildren | train | function emitChildren(elements) {
var i;
for (i = 0; i < elements.length; i++) {
var element = elements[i];
if (typeof element === 'object') {
emitStart.call(this, element.$name, element.$);
emitChildren.call(this, element.$children);
emitEnd.call(this, element.$name);
} else {
e... | javascript | {
"resource": ""
} |
q46495 | emitOneElement | train | function emitOneElement(element, name, onLeave) {
if (typeof element === 'object') {
emitStart.call(this, name, element.$);
if (__own.call(element, '$children')) {
emitChildren.call(this, element.$children);
} else {
var hasText = false;
for (var child in element) {
if (__own.cal... | javascript | {
"resource": ""
} |
q46496 | train | function(data) {
if (self._encoder) {
data = self._encoder.convert(data);
}
if (!xml.parse(data, false)) {
self.emit('error', new Error(xml.getError()+" in line "+xml.getCurrentLineNumber()));
}
} | javascript | {
"resource": ""
} | |
q46497 | setup | train | function setup(encoding) {
var stream = fs.createReadStream(path.join(__dirname, 'encoding.xml'));
var xml = new XmlStream(stream, encoding);
xml.on('endElement: node', function(node) {
console.log(node);
});
xml.on('error', function(message) {
console.log('Parsing as ' + (encoding || 'auto') + ' fail... | javascript | {
"resource": ""
} |
q46498 | sanitize | train | function sanitize(ev){
var obj = {};
for (var key in ev)
if (key.indexOf("_") !== 0)
obj[key] = ev[key];
if (!cfg.use_id)
delete obj.id;
return obj;
} | javascript | {
"resource": ""
} |
q46499 | orderEdgesOne | train | function orderEdgesOne (G, v) {
const node = G.node(v)
node.ports.forEach(port => {
port.incoming.sort(compareDirection(G, node, false))
port.outgoing.sort(compareDirection(G, node, true))
})
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.