_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', body || []), req: req || [], opts: opts || [] } }
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.send(oracleRegisterTx, opt)), ...(await (await getOracleObject.bind(this)(oracleId)).getQuery(queryId)) } }
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.sign(txWithNetworkId)] return buildTx({ encodedTx: rlpBinaryTx, signatures }, TX_TYPE.signed).tx }
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.balance(await this.address())).times(percentage) let spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount: requestTransferAmount })) const { tx: txObject } = TxBuilder.unpackTx(spendTx) // If the requestTransferAmount should include the fee keep calculating the fee let amount = requestTransferAmount if (!options.excludeFee) { while (amount.plus(txObject.fee).gt(requestTransferAmount)) { amount = requestTransferAmount.minus(txObject.fee) } } // Rebuild tx spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount })) return this.send(spendTx, opt) }
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.send(nameUpdateTx, opt) }
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)) } }, transfer: async (account, options) => { return { ...(await this.aensTransfer(nameId, account, options)), ...(await this.aensQuery(name)) } }, revoke: async (options) => this.aensRevoke(nameId, options) })) }
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, { accountId: await this.address(), nameSalt: salt, name: `nm_${encodeBase58Check(Buffer.from(name))}` })) const result = await this.send(claimTx, opt) return { ...result, ...(await this.aensQuery(name)) } }
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(), commitmentId: hash })) const result = await this.send(preclaimTx, opt) return Object.freeze({ ...result, height, claim: options => this.aensClaim(name, _salt, (height + 1), options), salt: _salt, commitmentId: hash }) }
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, decodedError })) } const decodedError = await this.contractDecodeData('string', error) throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError })) }
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) })) const { hash, rawTx } = await this.send(tx, opt) const result = await this.getTxInfo(hash) if (result.returnType === 'ok') { return { hash, rawTx, result, decode: (type) => this.contractDecodeData(type, result.returnValue) } } else { await this.handleCallError(result) } }
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, { callData, code, ownerId })) const { hash, rawTx } = await this.send(tx, opt) const result = await this.getTxInfo(hash) return Object.freeze({ result, owner: ownerId, transaction: hash, rawTx, address: contractId, call: async (name, args = [], options) => this.contractCall(source, contractId, name, args, options), callStatic: async (name, args = [], options) => this.contractCallStatic(source, contractId, name, args, options), createdAt: new Date() }) }
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, source, init, options) }, { bytecode })) }
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: return `"${value}"` case SOPHIA_TYPES.list: return `[${value.map(el => transform(generic, el))}]` case SOPHIA_TYPES.tuple: return `(${value.map((el, i) => transform(generic[i], el))})` case SOPHIA_TYPES.address: return `#${decode(value).toString('hex')}` case SOPHIA_TYPES.record: return `{${generic.reduce( (acc, { name, type }, i) => { if (i !== 0) acc += ',' acc += `${name} = ${transform(type[0], value[name])}` return acc }, '' )}}` } return `${value}` }
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 SOPHIA_TYPES.address: return !(value[2] === '_' && ['ak', 'ct'].includes(value.slice(0, 2))) default: return false } }
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.value === 0 ? 0 : encodeAddress(toBytes(result.value, true), addressPrefix) case SOPHIA_TYPES.map: const [keyT, valueT] = generic return result.value .reduce( (acc, { key, val }, i) => { key = transformDecodedData(keyT, { value: key.value }) val = transformDecodedData(valueT, { value: val.value }) acc[i] = { key, val } return acc }, {} ) case SOPHIA_TYPES.list: return result.value.map(({ value }) => transformDecodedData(generic, { value })) case SOPHIA_TYPES.tuple: return result.value.map(({ value }, i) => { return transformDecodedData(generic[i], { value }) }) case SOPHIA_TYPES.record: return result.value.reduce( (acc, { name, value }, i) => ({ ...acc, [generic[i].name]: transformDecodedData(generic[i].type, { value }) }), {} ) } return result.value }
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 (validation.length) throw new Error('Validation error: ' + JSON.stringify(validation)) return aci.arguments.map(({ type }, i) => transform(type, params[i])) }
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 * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype () => ContractInstance: Object * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage */ instance.compile = compile(this).bind(instance) /** * Deploy contract * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype (init: Array, options: Object = { skipArgsConvert: false }) => ContractInstance: Object * @param {Array} init Contract init function arguments array * @param {Object} [options={}] options Options object * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage */ instance.deploy = deploy(this).bind(instance) /** * Call contract function * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype (init: Array, options: Object = { skipArgsConvert: false, skipTransformDecoded: false, callStatic: false }) => CallResult: Object * @param {String} fn Function name * @param {Array} params Array of function arguments * @param {Object} [options={}] Array of function arguments * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data * @param {Boolean} [options.skipTransformDecoded=false] Skip Transform decoded data to JS type * @param {Boolean} [options.callStatic=false] Static function call * @return {Object} CallResult */ instance.call = call(this).bind(instance) return instance }
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.from(keypair.secretKey, 'hex'), publicKey: keypair.publicKey }) }
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 FIELD_TYPES.binary: return encode(value, prefix) case FIELD_TYPES.string: return value.toString() case FIELD_TYPES.pointers: return readPointers(value) case FIELD_TYPES.rlpBinary: return unpackTx(value, true) case FIELD_TYPES.rlpBinaries: return value.map(v => unpackTx(v, true)) case FIELD_TYPES.rawBinary: return value case FIELD_TYPES.hex: return value.toString('hex') case FIELD_TYPES.offChainUpdates: return value.map(v => unpackTx(v, true)) case FIELD_TYPES.callStack: // TODO: fix this return [readInt(value)] case FIELD_TYPES.mptree: return value.map(mpt.deserialize) case FIELD_TYPES.callReturnType: switch (readInt(value)) { case '0': return 'ok' case '1': return 'error' case '2': return 'revert' default: return value } default: return value } }
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(options.kdf)) throw new Error('Unsupported kdf type') return DERIVED_KEY_FUNCTIONS[options.kdf](password, nonce, options) }
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.secret_type, symmetric_alg: opt.symmetric_alg, ciphertext: Buffer.from(encrypt(Buffer.from(privateKey), derivedKey, nonce, opt.symmetric_alg)).toString('hex'), cipher_params: { nonce: Buffer.from(nonce).toString('hex') } }, { kdf: opt.kdf, kdf_params: { ...opt.kdf_params, salt: Buffer.from(salt).toString('hex') } } ) } ) }
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 value of the token, check if // this is the full token. if (message[i] === token[0]) { if (containsToken(message, token, i)) { return i; } } } return -1; }
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 = stringToUint8Array('\r\n\r\n'); let headerIndex = findToken(message, separator, 0, maxSearchLength); if (headerIndex === -1) { throw new Error('Response message has no multipart mime header'); } const header = uint8ArrayToString(message, 0, headerIndex); const boundaryString = identifyBoundary(header); if (!boundaryString) { throw new Error('Header of response message does not specify boundary'); } const boundary = stringToUint8Array(boundaryString); const boundaryLength = boundary.length; const components = []; let offset = headerIndex + separator.length; // Loop until we cannot find any more boundaries let boundaryIndex; while (boundaryIndex !== -1) { // Search for the next boundary in the message, starting // from the current offset position boundaryIndex = findToken(message, boundary, offset); // If no further boundaries are found, stop here. if (boundaryIndex === -1) { break; } // Extract data from response message, excluding "\r\n" const spacingLength = 2; const length = boundaryIndex - offset - spacingLength; const data = response.slice(offset, offset + length); // Add the data to the array of results components.push(data); // Move the offset to the end of the current section, // plus the identified boundary offset += length + spacingLength + boundaryLength; } return components; }
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_ID) ); const cipherMessage = await alice.encrypt(createSessionId(bob), 'Hello', bobBundle.serialise()); await bob.decrypt(createSessionId(alice), cipherMessage); return {alice, bob}; }
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(value => alice.encrypt(createSessionId(bob), `This is a long message with number ${value.toString()}`)) ); let stopTime = getTimeInSeconds(startTime); process.stdout.write('Done.\n'); console.info(`Execution time: ${stopTime} seconds.\n`); // Decryption process.stdout.write(`Measuring decryption time for "${messageCount}" messages ... `); startTime = process.hrtime(); await Promise.all( encryptedMessages.map(async encryptedMessage => await bob.decrypt(createSessionId(alice), encryptedMessage)) ); stopTime = getTimeInSeconds(startTime); process.stdout.write('Done.\n'); console.info(`Execution time: ${stopTime} seconds.\n`); }
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 = []; var maxRowLen = []; columns.forEach(function (e, i) { if (typeof tabularData[i] == "undefined") { tabularData[i] = []; } var regex = new RegExp(delimiter + '(?![^"]*"\\B)'); var row = e.split(regex); row.forEach(function (ee, ii) { if (typeof maxRowLen[ii] == "undefined") { maxRowLen[ii] = 0; } maxRowLen[ii] = Math.max(maxRowLen[ii], ee.length); tabularData[i][ii] = ee; }); }); var headerOutput = ""; var seperatorOutput = ""; maxRowLen.forEach(function (len) { var sizer = Array(len + 1 + 2); seperatorOutput += "|" + sizer.join("-"); headerOutput += "|" + sizer.join(" "); }); headerOutput += "| \n"; seperatorOutput += "| \n"; if (hasHeader) { headerOutput = ""; } var rowOutput = ""; tabularData.forEach(function (col, i) { maxRowLen.forEach(function (len, y) { var row = typeof col[y] == "undefined" ? "" : col[y]; var spacing = Array((len - row.length) + 1).join(" "); var out = "| " + row + spacing + " "; if (hasHeader && i === 0) { headerOutput += out; } else { rowOutput += out; } }); if (hasHeader && i === 0) { headerOutput += "| \n"; } else { rowOutput += "| \n"; } }); return "" + headerOutput + seperatorOutput + rowOutput; }
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.categories = [item.name]; } clientLibDirectoryFields.forEach(function (nodeKey) { if (item.hasOwnProperty(nodeKey)) { content[nodeKey] = item[nodeKey]; } }); var jsonFile = path.join(item.path, item.name + ".json"); options.verbose && console.log("write clientlib json file: " + jsonFile); if (!options.dry) { fse.writeJsonSync(jsonFile, content, {spaces: 2}); } }
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 fieldValue = item.categories.join(','); content += ' categories="[' + fieldValue + ']"'; } else { content += ' categories="[' + item.name + ']" '; } clientLibDirectoryFields.forEach(function (fieldKey) { if (item.hasOwnProperty(fieldKey)) { if (typeof item[fieldKey] === 'boolean') { // Boolean value content += ' ' + fieldKey + '="{Boolean}' + item[fieldKey] + '"'; } else if (Array.isArray(item[fieldKey])) { // Array of strings var fieldValue = item[fieldKey].join(','); content += ' ' + fieldKey + '="[' + fieldValue + ']"'; } else if (typeof item[fieldKey] === 'string') { // String value content += ' ' + fieldKey + '="' + item[fieldKey] + '"'; } } }); content += "/>"; var outputPath = item.outputPath || path.join(item.path, item.name); var contentXml = path.join(outputPath + "/.content.xml"); options.verbose && console.log("write clientlib json file: " + contentXml); fse.writeFileSync(contentXml, content); }
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.verbose) { console.log("\nstart aem-clientlib-generator"); console.log(" working directory: " + process.cwd()); } options.dry && console.log("\nDRY MODE - without write options!"); async.eachSeries(itemList, function (item, processItemDone) { processItem(item, options, processItemDone); }, done); }
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)) { assetItem = { files: assetItem }; } if (!assetItem.base) { assetItem.base = assetKey; } assetItem.type = assetKey; list.push(assetItem); }); } // transform files to scr-dest mapping list.forEach(function (asset) { var mapping = []; var flatName = typeof asset.flatten !== "boolean" ? true : asset.flatten; var assetPath = path.posix.join(clientLibPath, asset.base); var globOptions = {}; if (asset.cwd) { globOptions.cwd = asset.cwd; } asset.files.forEach(function (file) { var fileItem = file; // convert simple syntax to object if (_.isString(file)) { fileItem = { src: file }; } // no magic pattern -> default behaviour if (!glob.hasMagic(fileItem.src)) { // determine default dest if (!fileItem.dest) { fileItem.dest = path.posix.basename(file); } // generate full path fileItem.dest = path.posix.join(assetPath, fileItem.dest); mapping.push(fileItem); } // resolve magic pattern else { var files = glob.sync(fileItem.src, globOptions); var hasCwd = !!globOptions.cwd; var dest = fileItem.dest ? path.posix.join(assetPath, fileItem.dest) : assetPath; files.forEach(function (resolvedFile) { // check 'flatten' option -> strip dir name var destFile = flatName ? path.posix.basename(resolvedFile) : resolvedFile; var item = { src: resolvedFile, dest: path.posix.join(dest, destFile) }; // check "cwd" option -> rebuild path, because it was stripped by glob.sync() if (hasCwd) { item.src = path.posix.join(globOptions.cwd, resolvedFile); } mapping.push(item); }); } }); asset.files = mapping; }); return list; }
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.join(item.path, item.name); // create clientlib directory fse.mkdirsSync(clientLibPath); var serializationFormat = (item.serializationFormat === SERIALIZATION_FORMAT_XML) ? SERIALIZATION_FORMAT_XML : SERIALIZATION_FORMAT_JSON; options.verbose && console.log("Write node configuration using serialization format: " + serializationFormat); if (serializationFormat === SERIALIZATION_FORMAT_JSON) { // write configuration JSON writeClientLibJson(item, options); } else { writeClientLibXml(item, options); } var assetList = normalizeAssets(clientLibPath, item.assets); // iterate through assets async.eachSeries(assetList, function (asset, assetDone) { // write clientlib creator files if (asset.type === "js" || asset.type === "css") { options.verbose && console.log(""); writeAssetTxt(clientLibPath, asset, options); } // copy files for given asset async.eachSeries(asset.files, function (fileItem, copyDone) { if (fileItem.src == fileItem.dest) { options.verbose && console.log(`${fileItem.src} already in output directory`); return copyDone(); } options.verbose && console.log("copy:", fileItem.src, fileItem.dest); if (options.dry) { return copyDone(); } // create directories separately or it will be copied recursively if (fs.lstatSync(fileItem.src).isDirectory()) { fs.mkdir(fileItem.dest, copyDone); } else { fse.copy(fileItem.src, fileItem.dest, copyDone); } }, assetDone); }, processDone); }); }
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 (pattern == '.') { fixedPattern = '**/*.feature'; } else if (pattern.match(/.*\/\*\*/)) { fixedPattern = pattern + '/**.feature'; } else if (pattern.match(/.*\.feature/)) { fixedPattern = pattern; } else { try { if (fs.statSync(pattern).isDirectory()) { fixedPattern = path.join(pattern, '**/*.feature'); } } catch(e) { // Don't show the fs callstack, we will print a custom error message bellow instead } } if (!fixedPattern) { logger.boldError(`Invalid format of the feature file path/pattern: "${pattern}".\nTo run the linter please specify an existing feature file, directory or glob.`); process.exit(1); return; // This line will only be hit by tests that stub process.exit } var globOptions = {ignore: getIgnorePatterns(ignoreArg)}; files = files.concat(glob.sync(fixedPattern, globOptions)); }); return _.uniq(files); }
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); }; return WsStream .openStream(makeUrl, api.session.getAuthorization('GET', getAppLogsUrl(appId), {})) .filter((line) => { const lineDate = Date.parse(line._source['@timestamp']); const isBefore = !before || lineDate < before.getTime(); const isAfter = !after || lineDate > after.getTime(); return isBefore && isAfter; }); }
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.filter(false).mapEnd(new Date()); const s_interruption = s_endTimestamp.flatMapLatest((endTimestamp) => { Logger.warn('WebSocket connexion closed, reconnecting...'); if (retries === 0) { return new Bacon.Error(`WebSocket connexion failed ${MAX_RETRY_COUNT} times!`); } return Bacon.later(RETRY_DELAY, null).flatMapLatest(() => { return openStream(makeUrl, authorization, endTimestamp, retries - 1); }); }); return Bacon.mergeAll(s_websocket, s_interruption); }
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 => { const name = baseName + ' / ' + route.name; const url = location.protocol + '//' + location.host + '/' + route.fullPath; Vue.appInsights.stopTrackPage(name, url); }) }
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 options.end !== 'number') return invalid(); if (options.pattern && typeof options.pattern !== 'string') return invalid(); if (options.retry && typeof options.retry !== 'function') return invalid(); if (options.messages && typeof options.messages !== 'boolean') return invalid(); options.objectMode = !options.messages; options.start = options.start || Date.now() - 15 * 60 * 1000; options.end = options.end || Date.now(); options.retry = options.retry || function() {}; var logs = new AWS.CloudWatchLogs({ region: options.region }); var params = { logGroupName: options.group, endTime: options.end, filterPattern: options.pattern ? '"' + options.pattern + '"' : undefined, interleaved: true, startTime: options.start }; var logStream = new stream.Readable(options); var nextRequest = logs.filterLogEvents(params); var pending = false; var events = []; function makeRequest(request) { pending = true; request .on('error', function(err) { logStream.emit('error', err); }) .on('retry', options.retry) .on('success', function(response) { pending = false; nextRequest = response.hasNextPage() ? response.nextPage() : false; for (var i = 0; i < response.data.events.length; i++) { var item = options.messages ? response.data.events[i].message.trim() + '\n' : response.data.events[i]; events.push(item); } logStream._read(); }).send(); } logStream._read = function() { var status = true; while (status && events.length) status = logStream.push(events.shift()); if (events.length) return; if (!nextRequest) return logStream.push(null); if (status && !pending) makeRequest(nextRequest); }; return logStream; }
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, value: value, prop: prop, _njSrc: true }; } return value; } } } }
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: 'item' in params ? params.item : context.item }); }
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 = v.options; if (_extension) { extensions[name] = _extension; } else if (!mergeConfig) { extensions[name] = v; } if (mergeConfig) { if (!extensionConfig[name]) { extensionConfig[name] = _config(); } assign(extensionConfig[name], _options3); } else { extensionConfig[name] = _config(_options3); } } }, false); }
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; if (_options) { if (_options.isOperator) { var createRegexOperators = nj.createRegexOperators; if (createRegexOperators) { createRegexOperators(name); } } var alias = _options.alias; if (alias) { var createFilterAlias = nj.createFilterAlias; if (createFilterAlias) { createFilterAlias(name, alias); name = alias; } } } if (_filter) { filters[name] = _filter; } else if (!mergeConfig) { filters[name] = v; } if (mergeConfig) { if (!filterConfig[name]) { filterConfig[name] = _config$1(); } assign(filterConfig[name], _options); } else { filterConfig[name] = _config$1(_options); } } }, false); }
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 = []; } var value = matchArr[8], onlyBrace = matchArr[4] != null ? matchArr[4] : matchArr[6], onlyKey = false; if (value != null) { value = clearQuot(value); //Remove quotation marks } else { value = key; //Match to Similar to "checked" or "disabled" attribute. if (!onlyBrace) { onlyKey = true; } } //Removed at the end of "/>", ">" or "/". if (!matchArr[9] && !matchArr[10]) { if (/\/>$/.test(value)) { value = value.substr(0, value.length - 2); } else if (/>$/.test(value) || /\/$/.test(value)) { value = value.substr(0, value.length - 1); } } //Transform special key var hasColon = void 0; if (key[0] === ':') { key = key.substr(1); hasColon = true; } ret.push({ key: key, value: value, onlyBrace: onlyBrace, hasColon: hasColon, onlyKey: onlyKey }); } return 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; } exPropsNode.parentType = parent.type; parent[exPropsName] = exPropsNode; } else { arrayPush(parent[exPropsName].content, isDirective || isSubTag ? [node] : node.content); } }
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); if (fixedExTagName) { ret = tmplRule.extensionRule + lowerFirst(ret); } } else if (isStrPropS(elemName, tmplRule)) { ret = _transformToEx(true, elemName, elemParams, tmplRule); } else if (isPropS(elemName, tmplRule)) { ret = _transformToEx(false, elemName, elemParams, tmplRule); } else { var retS = _getSplitParams(elem, tmplRule, outputH); ret = retS.elem; paramsEx = retS.params; } if (bySelfClose) { var retC = [ret]; if (paramsEx) { retC.push(paramsEx); } elemArr.push(retC); } else { elemArr.push(ret); if (paramsEx) { elemArr.push(paramsEx); } } }
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.directives; var paramsEx; //Replace the parameter like "{...props}". elem = elem.replace(spreadProp, function (all, g1, propR, g3, prop) { if (propR) { prop = propR; } if (!paramsEx) { paramsEx = [extensionRule + 'props']; } paramsEx.push([extensionRule + 'spread ' + (propR ? firstChar : '') + startRule + prop.replace(/\.\.\./, '') + endRule + (propR ? lastChar : '') + '/']); return ' '; }); //Replace the parameter like "#show={false}". elem = elem.replace(directives, function (all, g1, g2, g3, g4, g5, g6, key, hasColon, hasEx, name, hasEqual, value) { if (hasEx == null) { return all; } if (!paramsEx) { paramsEx = [extensionRule + 'props']; } var args, modifiers; name = name.replace(REGEX_EX_ATTR, function (all, name, modifier, g3, arg) { if (arg) { args = arg.substr(1).split('-').map(function (item) { var argStr; var modifierStr = ''; var strs = item.split(/[$.]/); strs.forEach(function (str, i) { if (i == 0) { argStr = 'name:\'' + str + '\'' + (i < strs.length - 1 ? ',' : ''); } else { modifierStr += '\'' + str + '\'' + (i < strs.length - 1 ? ',' : ''); } }); return '{' + argStr + (modifierStr != '' ? 'modifiers:[' + modifierStr + ']' : '') + '}'; }); } if (modifier) { modifiers = modifier.substr(1).split(/[$.]/).map(function (item) { return '\'' + item + '\''; }); } return name; }); var exPreAst = [extensionRule + name + ' _njIsDirective' + (args ? ' arguments="' + firstChar + startRule + '[' + args.join(',') + ']' + endRule + lastChar + '"' : '') + (modifiers ? ' modifiers="' + startRule + '[' + modifiers.join(',') + ']' + endRule + '"' : '') + (hasEqual ? '' : ' /')]; hasEqual && exPreAst.push((hasColon ? (outputH ? firstChar : '') + startRule + ' ' : '') + clearQuot(value) + (hasColon ? ' ' + endRule + (outputH ? lastChar : '') : '')); paramsEx.push(exPreAst); return ' '; }); return { elem: elem, params: paramsEx }; }
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 inside; }
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.push({ buffer: buffer, z: parseInt(zxy[0]), x: parseInt(zxy[1]), y: parseInt(zxy[2]) }); }); return 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() .replace(hyphenPatternRegex, function(_, character) { return character.toUpperCase(); }); }
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 (isOverridePresent) { overrides = override(key, value); if (overrides && overrides.length === 2) { result[overrides[0]] = overrides[1]; continue; } } if (typeof value === 'string') { result[value] = key; } } return result; }
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 track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } }
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(propertyName)) { props[propertyName] = propertyValue; continue; } // make HTML DOM attribute/property consistent with React attribute/property reactProperty = config.html[propertyName.toLowerCase()]; if (reactProperty) { if ( DOMProperty.properties.hasOwnProperty(reactProperty) && DOMProperty.properties[reactProperty].hasBooleanValue ) { props[reactProperty] = true; } else { props[reactProperty] = propertyValue; } continue; } // make SVG DOM attribute/property consistent with React attribute/property reactProperty = config.svg[propertyName]; if (reactProperty) { props[reactProperty] = propertyValue; } else if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) { props[propertyName] = propertyValue; } } // convert inline style to object if (attributes.style != null) { props.style = cssToJs(attributes.style); } return props; }
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)] = propValue; } }); return styleObj; }
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 element (if applicable) if (isReplacePresent) { replacement = options.replace(node); if (React.isValidElement(replacement)) { // specify a "key" prop if element has siblings // https://fb.me/react-warning-keys if (len > 1) { replacement = React.cloneElement(replacement, { key: replacement.key || i }); } result.push(replacement); continue; } } if (node.type === 'text') { result.push(node.data); continue; } props = node.attribs; if (!shouldPassAttributesUnaltered(node)) { // update values props = attributesToProps(node.attribs); } children = null; // node type for <script> is "script" // node type for <style> is "style" if (node.type === 'script' || node.type === 'style') { // prevent text in <script> or <style> from being escaped // https://facebook.github.io/react/tips/dangerously-set-inner-html.html if (node.children[0]) { props.dangerouslySetInnerHTML = { __html: node.children[0].data }; } } else if (node.type === 'tag') { // setting textarea value in children is an antipattern in React // https://reactjs.org/docs/forms.html#the-textarea-tag if (node.name === 'textarea' && node.children[0]) { props.defaultValue = node.children[0].data; // continue recursion of creating React elements (if applicable) } else if (node.children && node.children.length) { children = domToReact(node.children, options); } // skip all other cases (e.g., comment) } else { continue; } // specify a "key" prop if element has siblings // https://fb.me/react-warning-keys if (len > 1) { props.key = i; } result.push(React.createElement(node.name, props, children)); } return result.length === 1 ? result[0] : result; }
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 frameRate === 'number' && frameRate>0) this.frameRate = frameRate; else throw new Error('Number expected as framerate'); if (this.frameRate!==23.976 && this.frameRate!==24 && this.frameRate!==25 && this.frameRate!==29.97 && this.frameRate!==30 && this.frameRate!==50 && this.frameRate!==59.94 && this.frameRate!==60 ) throw new Error('Unsupported framerate'); // If we are passed dropFrame, we need to use it if (typeof dropFrame === 'boolean') this.dropFrame = dropFrame; else this.dropFrame = (this.frameRate===29.97 || this.frameRate===59.94); // by default, assume DF for 29.97 and 59.94, NDF otherwise // Now either get the frame count, string or datetime if (typeof timeCode === 'number') { this.frameCount = Math.round(timeCode); this._frameCountToTimeCode(); } else if (typeof timeCode === 'string') { // pick it apart var parts = timeCode.match('^([012]\\d):(\\d\\d):(\\d\\d)(:|;|\\.)(\\d\\d)$'); if (!parts) throw new Error("Timecode string expected as HH:MM:SS:FF or HH:MM:SS;FF"); this.hours = parseInt(parts[1]); this.minutes = parseInt(parts[2]); this.seconds = parseInt(parts[3]); // do not override input parameters if (typeof dropFrame !== 'boolean') { this.dropFrame = parts[4]!==':'; } this.frames = parseInt(parts[5]); this._timeCodeToFrameCount(); } else if (typeof timeCode === 'object' && timeCode instanceof Date) { var midnight = new Date(timeCode.getFullYear(), timeCode.getMonth(), timeCode.getDate(),0,0,0); var midnight_tz = midnight.getTimezoneOffset() * 60 * 1000; var timecode_tz = timeCode.getTimezoneOffset() * 60 * 1000; this.frameCount = Math.round(((timeCode-midnight + (midnight_tz - timecode_tz))*this.frameRate)/1000); this._frameCountToTimeCode(); } else if (typeof timeCode === 'object' && timeCode.hours >= 0) { this.hours = timeCode.hours; this.minutes = timeCode.minutes; this.seconds = timeCode.seconds; this.frames = timeCode.frames; this._timeCodeToFrameCount(); } else if (typeof timeCode === 'undefined') { this.frameCount = 0; } else { throw new Error('Timecode() constructor expects a number, timecode string, or Date()'); } this._validate(timeCode); return this; }
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.sys.readFile, getCurrentDirectory: typescript.sys.getCurrentDirectory, }; const tsconfig = typescript.getParsedCommandLineOfConfigFile(configFilePath, {}, createConfigFileHost); if (!tsconfig) { return [`could not parse "${configFilePath}"`]; } if (tsconfig.options.skipLibCheck === undefined) { warnings.push( 'skipLibCheck option was NOT specified\n' + 'By default the fork-ts-checker-webpack-plugin will check all types inside the node_modules directory\n' + 'even for unused dependencies and slow down the type checking a lot.\n' + 'To skip that checking add the following line to your tsconfig.json compilerOptions configuration:\n' + '"skipLibCheck": true\n' + 'To keep the default behaviour with possible performance penalties set skipLibCheck to false to hide this warning.\n' ); } if (tsconfig.options.moduleResolution === undefined) { warnings.push( 'moduleResolution option was NOT specified\n' + 'This will result in typescript warnings like "module not found".\n' + 'To fix that add the following line to your tsconfig.json compilerOptions configuration:\n' + '"moduleResolution": "node"\n' + 'To keep the default behaviour with possible type checking errors set moduleResolution to "classic" to hide this warning.\n' ); } return warnings; }
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] : null) return listTimezonesFolder(subset ? subset + "/" : "", subset ? path.join(TZDIR, "/" + subset) : TZDIR, function (err, tzs) { if (err) return cb(err); cb(null, tzs.sort()); }); }
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]) ? eventType + ': ' + selector.normalized : eventType }; }
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 part = selector.parts[i]; if (part === '>') { immediate = true; } else { if (!immediate) { this._fa.transition(this._lastState, '', this._lastState); } this._fa.transition(this._lastState, part, ++this._lastState); immediate = false; } } var finalState = this._lastState++; this._finalStates[selector.normalized] = finalState; } return finalState; }
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 { emitText.call(this, element); } } }
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.call(element, child) && child !== '$' && child != '$name') { if (child === '$text') { hasText = true; } else { emitElement.call(this, element[child], child); } } } if (hasText) { emitText.call(this, element.$text); } } } else { emitStart.call(this, name, element.$); emitText.call(this, element); } if (!onLeave) { emitEnd.call(this, name); } }
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') + ' failed: ' + message); }); return xml; }
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": "" }