_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q34700
train
function(widget_config, raw_template) { var storage_schema = this.getMergedStorageSchema(widget_config), tags = Lava.parsers.Common.asBlockType(raw_template, 'tag'), i = 0, count = tags.length, item_schema; for (; i < count; i++) { item_schema = storage_schema[tags[i].name]; if (Lava.schema.DEBUG && !item_schema) Lava.t('parsing storage; no schema for ' + tags[i].name); Lava.store(widget_config, 'storage', tags[i].name, this[this._root_handlers[item_schema.type]](item_schema, tags[i])); } }
javascript
{ "resource": "" }
q34701
train
function(schema, raw_tag, exclude_name) { var tags = Lava.parsers.Common.asBlockType(raw_tag.content, 'tag'), i = 0, count = tags.length, result = {}, descriptor, name; for (; i < count; i++) { descriptor = schema.properties[tags[i].name]; if (Lava.schema.DEBUG && !descriptor) Lava.t("Unknown tag in object: " + tags[i].name); if (Lava.schema.DEBUG && (tags[i].name in result)) Lava.t('[Storage] duplicate item in object: ' + tags[i].name); result[tags[i].name] = this[this._object_property_handlers[descriptor.type]](descriptor, tags[i]); } for (name in raw_tag.attributes) { if (exclude_name && name == 'name') continue; descriptor = schema.properties[name]; if (Lava.schema.DEBUG && (!descriptor || !descriptor.is_attribute)) Lava.t("Unknown attribute in object: " + name); if (Lava.schema.DEBUG && (name in result)) Lava.t('[Storage] duplicate item (attribute) in object: ' + name); result[name] = this[this._object_attributes_handlers[descriptor.type]](descriptor, raw_tag.attributes[name]); } return result; }
javascript
{ "resource": "" }
q34702
train
function(s) { var r = ''; for (var i = s.length - 1; i >= 0; i--) { r += s[i]; } return r; }
javascript
{ "resource": "" }
q34703
npmInstall
train
function npmInstall(requires, done) { var npmBin = path.join(path.dirname(process.argv[0]), 'npm'); if (process.platform === 'win32') { npmBin += '.cmd'; } async.forEachSeries(requires, function(module, next) { // skip existing modules if (grunt.file.exists(path.join('./node_modules/' + module))) { grunt.log.writeln(String('Module "' + module + '" already installed, skipping.').cyan); return next(); } grunt.log.writeln('npm install ' + module + ' --save'); // spawn npm install var s = grunt.util.spawn({ cmd: npmBin, args: ['install', module, '--save'] }, next); // write output s.stdout.on('data', function(buf) { grunt.log.write(String(buf)); }); s.stderr.on('data', function(buf) { grunt.log.write(String(buf)); }); }, done); }
javascript
{ "resource": "" }
q34704
camelize
train
function camelize() { return function(input, output) { var target = output || input; var f = output ? remove : add; for (var key in target) { var value = target[key]; var key_ = f(key); if (key_ === key) continue; delete target[key]; target[key_] = value; } }; }
javascript
{ "resource": "" }
q34705
filter
train
function filter(obj, keys, recurse) { if (typeof obj !== 'object') { throw new TypeError('obj must be an object'); } if (!Array.isArray(keys)) { throw new TypeError('keys must be an array'); } if (recurse == null) { recurse = false; } if (typeof recurse !== 'boolean') { throw new TypeError('recurse must be a boolean'); } var result; if (Array.isArray(obj)) { result = []; } else { result = {}; } Object.keys(obj).forEach(function(key) { if (~keys.indexOf(key)) { return; } // recurse if requested and possible if (recurse && obj[key] != null && typeof obj[key] === 'object' && Object.keys(obj[key]).length) { result[key] = filter(obj[key], keys, recurse); } else { result[key] = obj[key]; } }); return result; }
javascript
{ "resource": "" }
q34706
arraysAppendAdapter
train
function arraysAppendAdapter(to, from, merge) { // transfer actual values from.reduce(function(target, value) { target.push(merge(undefined, value)); return target; }, to); return to; }
javascript
{ "resource": "" }
q34707
loadEnvironment
train
function loadEnvironment(environment, callback) { const errorMsgBase = 'while transforming environment, '; var transformedEnvironment = cloneDeep(environment); // eslint-disable-line const query = new Eth(transformedEnvironment.provider); query.net_version((versionError, result) => { // eslint-disable-line if (versionError) { return callback(error(`${errorMsgBase}error attempting to connect to node environment '${transformedEnvironment.name}': ${versionError}`), null); } query.accounts((accountsError, accounts) => { // eslint-disable-line if (accountsError !== null) { return callback(error(`${errorMsgBase}error while getting accounts for deployment: ${accountsError}`), null); } callback(accountsError, Object.assign({}, cloneDeep(transformedEnvironment), { accounts, defaultTxObject: transformTxObject(environment.defaultTxObject, accounts), })); }); }); }
javascript
{ "resource": "" }
q34708
transformContracts
train
function transformContracts(contracts, environmentName) { const scopedContracts = Object.assign({}, cloneDeep(contracts[environmentName] || {})); // add name property to all contracts for deployment identification Object.keys(scopedContracts).forEach((contractName) => { scopedContracts[contractName].name = contractName; }); // return new scroped contracts return scopedContracts; }
javascript
{ "resource": "" }
q34709
configError
train
function configError(config) { if (typeof config !== 'object') { return `the config method must return a config object, got type ${typeof config}`; } if (typeof config.entry === 'undefined') { return `No defined entry! 'config.entry' must be defined, got type ${typeof config.entry}.`; } if (typeof config.module !== 'object') { return `No defined deployment module! 'config.module' must be an object, got type ${typeof config.module}`; } if (typeof config.module.deployment !== 'function') { return `No defined deployment function! 'config.module.deployment' must be type Function (i.e. 'module.deployment = (deploy, contracts, done){}' ), got ${typeof config.module.deployment}`; } if (typeof config.module.environment !== 'object') { return `No defined module environment object! 'config.module.environment' must be type Object, got ${typeof config.module.environment}`; } const environment = config.module.environment; if (typeof environment.provider !== 'object') { return `No defined provider object! 'config.module.environment' must have a defined 'provider' object, got ${typeof environment.provider}`; } if (typeof environment.name !== 'string') { return `No defined environment name! 'config.module.environment.name' must be type String, got ${typeof environment.name}`; } return null; }
javascript
{ "resource": "" }
q34710
requireLoader
train
function requireLoader(loaderConfig) { const errMsgBase = `while requiring loader ${JSON.stringify(loaderConfig)} config,`; if (typeof loaderConfig !== 'object') { throw error(`${errMsgBase}, config must be object, got ${typeof loaderConfig}`); } if (typeof loaderConfig.loader !== 'string') { throw error(`${errMsgBase}, config.loader must be String, got ${JSON.stringify(loaderConfig.loader)}`); } return require(loaderConfig.loader); // eslint-disable-line }
javascript
{ "resource": "" }
q34711
loadContracts
train
function loadContracts(loaders, base, sourceMap, environment, callback) { // eslint-disable-line var outputContracts = cloneDeep(base); // eslint-disable-line const errMsgBase = 'while processing entry data, '; if (!Array.isArray(loaders)) { return callback(error(`${errMsgBase}loaders must be type Array, got ${typeof loaders}`)); } // process loaders try { loaders.forEach((loaderConfig) => { // require the loader for use const loader = requireLoader(loaderConfig); // filtered sourcemap based on regex/include const filteredSourceMap = filterSourceMap(loaderConfig.test, loaderConfig.include, sourceMap, loaderConfig.exclude); // get loaded contracts const loadedEnvironment = loader(cloneDeep(filteredSourceMap), loaderConfig, environment); // output the new contracts outputContracts = Object.assign({}, cloneDeep(outputContracts), cloneDeep(loadedEnvironment)); }); // transform final contracts output callback(null, outputContracts); } catch (loaderError) { callback(error(`${errMsgBase}loader error: ${loaderError}`)); } }
javascript
{ "resource": "" }
q34712
processOutput
train
function processOutput(plugins, outputObject, configObject, baseContracts, contracts, environment, callback) { // eslint-disable-line // the final string to be outputed let outputString = JSON.stringify(outputObject, null, 2); // eslint-disable-line // the err msg base const errMsgBase = 'while processing output with plugins, '; if (!Array.isArray(plugins)) { return callback(error(`${errMsgBase}plugins must be type Array, got ${typeof plugins}`)); } // process deployers try { plugins.forEach((plugin) => { // process deployer method outputString = plugin.process({ output: outputString, config: configObject, baseContracts, contracts, environment }); }); // return final output string callback(null, outputString); } catch (deployerError) { callback(error(`${errMsgBase}plugins error: ${deployerError}`)); } }
javascript
{ "resource": "" }
q34713
contractIsDeployed
train
function contractIsDeployed(baseContract, stagedContract) { // if bytecode and inputs match, then skip with instance if (deepEqual(typeof baseContract.address, 'string') && deepEqual(baseContract.transactionObject, stagedContract.transactionObject) && deepEqual(`0x${stripHexPrefix(baseContract.bytecode)}`, `0x${stripHexPrefix(stagedContract.bytecode)}`) && deepEqual(baseContract.inputs, stagedContract.inputs)) { return true; } return false; }
javascript
{ "resource": "" }
q34714
isTransactionObject
train
function isTransactionObject(value) { if (typeof value !== 'object') { return false; } const keys = Object.keys(value); if (keys.length > 5) { return false; } if (keys.length === 0) { return true; } if (keys.length > 0 && isDefined(value.from) || isDefined(value.to) || isDefined(value.data) || isDefined(value.gas) || isDefined(value.gasPrice)) { return true; } return false; }
javascript
{ "resource": "" }
q34715
buildDeployMethod
train
function buildDeployMethod(baseContracts, transformedEnvironment, report) { return (...args) => { let transactionObject = {}; const defaultTxObject = transformedEnvironment.defaultTxObject || {}; const contractData = args[0]; if (typeof contractData !== 'object') { const noContractError = 'A contract you are trying to deploy does not exist in your contracts object. Please check your entry, loaders and contracts object.'; return Promise.reject(error(noContractError)); } const baseContract = baseContracts[contractData.name] || {}; const contractNewArguments = args.slice(1); const contractInputs = bnToString(Array.prototype.slice.call(contractNewArguments)); const contractBytecode = `0x${stripHexPrefix(contractData.bytecode)}`; const contractABI = JSON.parse(contractData.interface); const eth = new Eth(transformedEnvironment.provider); const contract = new EthContract(eth); const contractFactory = contract(contractABI, contractBytecode, defaultTxObject); // trim callback from inputs, not args // custom tx object not handled yet..... if (typeof contractInputs[contractInputs.length - 1] === 'function') { contractInputs.pop(); } // if there is a tx object provided for just this contractInputs // then get tx object, assign over default and use as the latest tx object if (isTransactionObject(contractInputs[contractInputs.length - 1])) { const transformedTransactionObject = transformTxObject(contractInputs[contractInputs.length - 1], transformedEnvironment.accounts); contractInputs[contractInputs.length - 1] = transformedTransactionObject; transactionObject = Object.assign({}, cloneDeep(defaultTxObject), cloneDeep(transformedTransactionObject)); } else { transactionObject = Object.assign({}, cloneDeep(defaultTxObject)); } // check contract has transaction object, either default or specified if (!EthUtils.isHexString(transactionObject.from, 20)) { const invalidFromAccount = `Attempting to deploy contract '${contractData.name}' with an invalid 'from' account specified. The 'from' account must be a valid 20 byte hex prefixed Ethereum address, got value '${transactionObject.from}'. Please specify a defaultTxObject in the module.environment.defaultTxObject (i.e. 'defaultTxObject: { from: 0 }') object or in the in the deploy method.`; return Promise.reject(error(invalidFromAccount)); } // check if contract is already deployed, if so, return instance return new Promise((resolve, reject) => { const resolveAndReport = (contractInstance) => { // report the contract report(contractData.name, contractData, contractInstance.address, contractInputs, transactionObject, (contractInstance.receipt || baseContract.receipt)); // resolve deployment resolve(contractInstance); }; // if the contract is deployed, resolve with base base contract, else deploy if (contractIsDeployed(baseContract, { transactionObject, bytecode: contractBytecode, inputs: contractInputs, })) { resolveAndReport(contractFactory.at(baseContract.address)); } else { deployContract(eth, contractFactory, contractInputs, (deployError, instance) => { if (deployError) { console.log(error(`while deploying contract '${contractData.name}': `, JSON.stringify(deployError.value, null, 2))); // eslint-disable-line reject(deployError); } else { resolveAndReport(instance); } }); } }); }; }
javascript
{ "resource": "" }
q34716
singleEntrySourceMap
train
function singleEntrySourceMap(entryItem, entryData, sourceMap, callback) { // eslint-disable-line if (typeof entryItem !== 'string') { return callback(null, sourceMap); } // get input sources for this entry getInputSources(entryItem, (inputSourceError, inputSourceMap) => { // eslint-disable-line if (inputSourceError) { return callback(inputSourceError, null); } // get source data const sourceData = deepAssign({}, sourceMap, inputSourceMap); // get next entry item const nextEntryItem = entryData[entryData.indexOf(entryItem) + 1]; // recursively go through tree singleEntrySourceMap(nextEntryItem, entryData, sourceData, callback); }); }
javascript
{ "resource": "" }
q34717
entrySourceMap
train
function entrySourceMap(entry, callback) { const entryData = typeof entry === 'string' ? [entry] : entry; // get source map singleEntrySourceMap(entryData[0], entryData, {}, callback); }
javascript
{ "resource": "" }
q34718
constantTimeCompare
train
function constantTimeCompare (val1, val2) { let sentinel if (val1.length !== val2.length) return false for (let i = 0, len = val1.length; i < len; i++) { sentinel |= val1.charCodeAt(i) ^ val2.charCodeAt(i) } return sentinel === 0 }
javascript
{ "resource": "" }
q34719
settings
train
function settings (options) { var parsers var throws var name if (options && typeof options === 'function') { options = { yaml: options } } if (options && typeof options === 'object' && !Array.isArray(options)) { throws = options.throws || false name = options.name || null delete options.throws delete options.name } parsers = options options = { parsers: parsers, throws: throws, name: name } return options }
javascript
{ "resource": "" }
q34720
Match
train
function Match(elm, options, data) { this.ev = new EventEmitter(); this.data = options.data || data; this.found = {}; this.timestamps = []; this.flippedPairs = 0; // [elm, elm] this.active = []; this.options = Ul.deepMerge(options, { autoremove: true , size: { x: 4 , y: 4 } , classes: { active: "active" } , step: { x: 43 , y: 43 } }); this.blocks_count = this.options.size.x * this.options.size.y; this.count = this.blocks_count / 2; if (this.blocks_count % 2) { throw new Error("The number of blocks should be even."); } this.ui = { container: ElmSelect(elm)[0] , items: [] , template: options.templateElm ? ElmSelect(options.templateElm)[0].outerHTML : options.template }; if (!Array.isArray(this.data)) { throw new Error("Data should be an array."); } }
javascript
{ "resource": "" }
q34721
fix
train
function fix (html) { if (self.options.htmlWrap === false) { return html; } if (html.substr(0,5) !== '<div>') { html = '<div>' + html + '</div>'; } return html; }
javascript
{ "resource": "" }
q34722
report
train
function report (property, name, parse) { var rquotes = /^['"]|['"]$/g; var inspect = queries[property] || query; return function () { var self = this; var value = inspect.call(self, property); var ev = 'report.' + name; if (parse === 'bool') { value = value === 'true' || value === true; } else if (parse === 'int') { value = parseInt(value, 10); } else if (property === 'fontName') { value = value.replace(rquotes, ''); } self.emit(ev, value, name); return value; }; }
javascript
{ "resource": "" }
q34723
isValid
train
function isValid(name, value) { var tests = { indent: function (value) { return (/^(\s*|\d*)$/).test(value); }, openbrace: function (value) { return (['end-of-line', 'separate-line']).indexOf(value) !== -1; }, autosemicolon: function (value) { return typeof value === 'boolean'; } }; return Boolean(tests[name] && tests[name](value)); }
javascript
{ "resource": "" }
q34724
JSONMinifier
train
function JSONMinifier() { const self = this; self.process = ({ output }) => JSON.stringify(JSON.parse(output)); }
javascript
{ "resource": "" }
q34725
JSONExpander
train
function JSONExpander() { const self = this; self.process = ({ output }) => JSON.stringify(JSON.parse(output), null, 2); }
javascript
{ "resource": "" }
q34726
keyFilter
train
function keyFilter(obj, predicate) { var result = {}, key; // eslint-disable-line for (key in obj) { // eslint-disable-line if (obj[key] && predicate(key)) { result[key] = obj[key]; } } return result; }
javascript
{ "resource": "" }
q34727
IncludeContracts
train
function IncludeContracts( contractsSelector, propertyFilter = ['interface', 'bytecode'], environmentName = 'contracts') { const self = this; self.process = ({ output, contracts }) => { // parse output const parsedOutput = JSON.parse(output); // add contracts environment parsedOutput[environmentName] = Object.assign({}); // go through selected contracts contractsSelector.forEach((contractName) => { // if the contracts object has the selectedcontract // include it if ((contracts || {})[contractName]) { const contractObject = Object.assign({}, contracts[contractName]); // include contract data in environments output with property filter parsedOutput[environmentName][contractName] = propertyFilter ? keyFilter(contractObject, (key => propertyFilter.indexOf(key) !== -1)) : contractObject; } }); return JSON.stringify(parsedOutput); }; }
javascript
{ "resource": "" }
q34728
sync
train
function sync(className, functionName, ...datatypes) { const qsync = qtypes.QInt.from(Types.SYNC); const qclassName = qtypes.QByteArray.from(className); const qfunctionName = qtypes.QByteArray.from(functionName); return function(target, _key, descriptor) { return { enumerable: false, configurable: false, writable: false, value: function(...args) { const [ id, ...data ] = descriptor.value.apply(this, args); this.qtsocket.write([ qsync, qclassName, qtypes.QByteArray.from(id), qfunctionName, ...data.map((value, index) => datatypes[index].from(value)) ]); } }; }; }
javascript
{ "resource": "" }
q34729
rpc
train
function rpc(functionName, ...datatypes) { const qrpc = qtypes.QInt.from(Types.RPCCALL); const qfunctionName = qtypes.QByteArray.from(`2${functionName}`); return function(target, _key, descriptor) { return { enumerable: false, configurable: false, writable: false, value: function(...args) { const data = descriptor.value.apply(this, args); this.qtsocket.write([ qrpc, qfunctionName, ...data.map((value, index) => datatypes[index].from(value)) ]); } }; }; }
javascript
{ "resource": "" }
q34730
simulateMouseEvent
train
function simulateMouseEvent (event, simulatedType) { // Ignore multi-touch events if (event.originalEvent.touches.length > 1) { return; } event.preventDefault(); var touch = event.originalEvent.changedTouches[0], simulatedEvent = document.createEvent('MouseEvents'); // Initialize the simulated mouse event using the touch event's coordinates simulatedEvent.initMouseEvent( simulatedType, // type true, // bubbles true, // cancelable window, // view 1, // detail touch.screenX, // screenX touch.screenY, // screenY touch.clientX, // clientX touch.clientY, // clientY false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 0, // button null // relatedTarget ); // Dispatch the simulated event to the target element event.target.dispatchEvent(simulatedEvent); }
javascript
{ "resource": "" }
q34731
evaluate
train
function evaluate(val, context) { if ($.isFunction(val)) { var args = Array.prototype.slice.call(arguments, 2); return val.apply(context, args); } return val; }
javascript
{ "resource": "" }
q34732
train
function (details) { details = details || {}; details= $.extend({}, details, { type: "change", val: this.val() }); // prevents recursive triggering this.opts.element.data("select2-change-triggered", true); this.opts.element.trigger(details); this.opts.element.data("select2-change-triggered", false); // some validation frameworks ignore the change event and listen instead to keyup, click for selects // so here we trigger the click event manually this.opts.element.click(); // ValidationEngine ignores the change event and listens instead to blur // so here we trigger the blur event manually if so desired if (this.opts.blurOnChange) this.opts.element.blur(); }
javascript
{ "resource": "" }
q34733
train
function () { if (!this.shouldOpen()) return false; this.opening(); // Only bind the document mousemove when the dropdown is visible $document.on("mousemove.select2Event", function (e) { lastMousePosition.x = e.pageX; lastMousePosition.y = e.pageY; }); return true; }
javascript
{ "resource": "" }
q34734
train
function () { var selected; if (this.isPlaceholderOptionSelected()) { this.updateSelection(null); this.close(); this.setPlaceholder(); } else { var self = this; this.opts.initSelection.call(null, this.opts.element, function(selected){ if (selected !== undefined && selected !== null) { self.updateSelection(selected); self.close(); self.setPlaceholder(); self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val()); } }); } }
javascript
{ "resource": "" }
q34735
bnToString
train
function bnToString(objInput, baseInput, hexPrefixed) { var obj = objInput; // eslint-disable-line const base = baseInput || 10; // obj is an array if (typeof obj === 'object' && obj !== null) { if (Array.isArray(obj)) { // convert items in array obj = obj.map((item) => bnToString(item, base, hexPrefixed)); } else { if (obj.toString && (obj.lessThan || obj.dividedToIntegerBy || obj.isBN || obj.toTwos)) { return hexPrefixed ? `0x${ethUtil.padToEven(obj.toString(16))}` : obj.toString(base); } else { // eslint-disable-line // recurively converty item Object.keys(obj).forEach((key) => { obj[key] = bnToString(obj[key], base, hexPrefixed); }); } } } return obj; }
javascript
{ "resource": "" }
q34736
filterSourceMap
train
function filterSourceMap(testRegex, includeRegex, sourceMap, excludeRegex) { const outputData = Object.assign({}); const testTestRegex = testRegex || /./g; const testIncludeRegex = includeRegex || null; const testExcludeRegex = excludeRegex || null; if (typeof testTestRegex !== 'object') { throw error(`while filtering source map, ${JSON.stringify(sourceMap)}, test regex must be type object, got ${typeof testRegex}.`); } if (typeof testIncludeRegex !== 'object') { throw error(`while filtering source map, ${JSON.stringify(sourceMap)}, include regex must be type object, got ${typeof testIncludeRegex}.`); } if (typeof testExcludeRegex !== 'object') { throw error(`while filtering source map, ${JSON.stringify(sourceMap)}, exclude regex must be type object, got ${typeof testExcludeRegex}.`); } Object.keys(sourceMap).forEach((key) => { if (testTestRegex.test(key) && (testIncludeRegex === null || testIncludeRegex.test(key)) && (testExcludeRegex === null || !testExcludeRegex.test(key))) { Object.assign(outputData, { [key]: sourceMap[key] }); } }); return outputData; }
javascript
{ "resource": "" }
q34737
getTransactionSuccess
train
function getTransactionSuccess(eth, txHash, timeout = 800000, callback) { const cb = callback || function cb() {}; let count = 0; return new Promise((resolve, reject) => { const txInterval = setInterval(() => { eth.getTransactionReceipt(txHash, (err, result) => { if (err) { clearInterval(txInterval); cb(err, null); reject(err); } if (!err && result) { clearInterval(txInterval); cb(null, result); resolve(result); } }); if (count >= timeout) { clearInterval(txInterval); const errMessage = `Receipt timeout waiting for tx hash: ${txHash}`; cb(errMessage, null); reject(errMessage); } count += 7000; }, 7000); }); }
javascript
{ "resource": "" }
q34738
deployContract
train
function deployContract(eth, factory, args, callback) { factory.new.apply(factory, args).then((txHash) => { getTransactionSuccess(eth, txHash, 8000000, (receiptError, receipt) => { if (receiptError) { callback(receiptError, null); } if (receipt) { const contractInstance = factory.at(receipt.contractAddress); contractInstance.receipt = receipt; callback(null, contractInstance); } }); }).catch(callback); }
javascript
{ "resource": "" }
q34739
getInputSources
train
function getInputSources(pathname, callback) { let filesRead = 0; let sources = {}; // test file is a file, the last section contains a extention period if (String(pathname).split('/').pop().indexOf('.') !== -1) { const searchPathname = pathname.substr(0, 2) === './' ? pathname.slice(2) : pathname; fs.readFile(searchPathname, 'utf8', (readFileError, fileData) => { // eslint-disable-line if (readFileError) { return callback(error(`while while getting input sources ${readFileError}`)); } callback(null, { [searchPathname]: fileData }); }); } else { // get all file names dir.files(pathname, (filesError, files) => { // eslint-disable-line if (filesError) { return callback(error(`while while getting input sources ${filesError}`)); } // if no files in directory, then fire callback with empty sources if (files.length === 0) { callback(null, sources); } else { // read all files dir.readFiles(pathname, (readFilesError, content, filename, next) => { // eslint-disable-line if (readFilesError) { return callback(error(`while getting input sources ${readFilesError}`)); } // add input sources to output sources = Object.assign({}, sources, { [path.join('./', filename)]: content, }); // increase files readFiles filesRead += 1; // process next file if (filesRead === files.length) { callback(null, sources); } else { next(); } }); } }); } }
javascript
{ "resource": "" }
q34740
mergeHeaps
train
function mergeHeaps(a, b) { if (typeof a.head === 'undefined') { return b.head; } if (typeof b.head === 'undefined') { return a.head; } var head; var aNext = a.head; var bNext = b.head; if (a.head.degree <= b.head.degree) { head = a.head; aNext = aNext.sibling; } else { head = b.head; bNext = bNext.sibling; } var tail = head; while (aNext && bNext) { if (aNext.degree <= bNext.degree) { tail.sibling = aNext; aNext = aNext.sibling; } else { tail.sibling = bNext; bNext = bNext.sibling; } tail = tail.sibling; } tail.sibling = aNext ? aNext : bNext; return head; }
javascript
{ "resource": "" }
q34741
Node
train
function Node(key, value) { this.key = key; this.value = value; this.degree = 0; this.parent = undefined; this.child = undefined; this.sibling = undefined; }
javascript
{ "resource": "" }
q34742
train
function() { var result = new StringBuffer(); var array = this._input.split(''); // var prev = null; for (var i = 0; i < array.length; i++) { var cur = array[i]; var next = array[i + 1]; if (typeof next !== 'undefined') { var curToken = cur + next; if (this._mode.tokens.ia[curToken]) { var nextNext = array[i + 2]; if (typeof nextNext === 'undefined' || /^[-\s]$/.test(nextNext)) { result.append(this._mode.tokens.ia[curToken]); i++; continue; } } } if (this._mode.cyr2lat[cur]) { result.append(this._mode.cyr2lat[cur]); } else { result.append(cur); } // prev = cur; } return result.toString(); }
javascript
{ "resource": "" }
q34743
_regExpOrGTFO
train
function _regExpOrGTFO(expr){ var exp; if(typeof expr === 'string'){ exp = new RegExp('^'+expr+'$'); } else if (expr instanceof RegExp){ exp = expr; } else { throw new Error('Needle must be either a string or a RegExp'); } return exp; }
javascript
{ "resource": "" }
q34744
Shrinkwrap
train
function Shrinkwrap(options) { this.fuse(); options = options || {}; options.registry = 'registry' in options ? options.registry : 'http://registry.nodejitsu.com/'; options.production = 'production' in options ? options.production : process.NODE_ENV === 'production'; options.optimize = 'optimize' in options ? options.optimize : true; options.limit = 'limit' in options ? options.limit : 10; options.mirrors = 'mirrors' in options ? options.mirrors : false; this.registry = 'string' !== typeof options.registry ? options.registry : new Registry({ registry: options.registry || Registry.mirrors.nodejitsu, githulk: options.githulk, mirrors: options.mirrors }); this.production = options.production; // Don't include devDependencies. this.limit = options.limit; // Maximum concurrency. this.cache = Object.create(null); // Dependency cache. }
javascript
{ "resource": "" }
q34745
queue
train
function queue(packages, ref, depth) { packages = shrinkwrap.dedupe(packages); Shrinkwrap.dependencies.forEach(function each(key) { if (this.production && 'devDependencies' === key) return; if ('object' !== this.type(packages[key])) return; Object.keys(packages[key]).forEach(function each(name) { var range = packages[key][name] , _id = name +'@'+ range; ref.dependencies = ref.dependencies || {}; queue.push({ name: name, // Name of the module range: range, // Semver range _id: _id, // Semi unique id. parents: [ref], // Reference to the parent module. depth: depth // The depth of the reference. }); }); }, shrinkwrap); return queue; }
javascript
{ "resource": "" }
q34746
parent
train
function parent(dependent) { var node = dependent , result = []; while (node.parent) { if (!available(node.parent)) break; result.push(node.parent); node = node.parent; } return result; }
javascript
{ "resource": "" }
q34747
available
train
function available(dependencies) { if (!dependencies) return false; return Object.keys(dependencies).every(function every(key) { var dependency = dependencies[key]; if (!dependency) return false; if (dependency.name !== name) return true; if (dependency.version === version) return true; return false; }); }
javascript
{ "resource": "" }
q34748
randomString
train
function randomString(_string_length, _mode) { var string_length = _string_length; if(string_length < 3) string_length = 2; var chars = chars_all; if(_mode === 'lower_case') chars = chars_lower; else if(_mode === 'upper_case') chars = chars_upper; else if(_mode === 'nums_oly') chars = chars_nums; else if(_mode === 'especials') chars = chars_all + chars_spec; var str = ''; for (var i=0; i<string_length; i++) { var rnum = Math.floor(Math.random() * chars.length); str += chars.substring(rnum,rnum+1); } return str; }
javascript
{ "resource": "" }
q34749
randomKey
train
function randomKey(_numOfBlocks, _blockLength, _mode, _timestamp) { var numOfBlocks = _numOfBlocks; var blockLength = _blockLength; if(numOfBlocks === undefined || numOfBlocks < 3) numOfBlocks = 2; if(blockLength === undefined || blockLength < 3) blockLength = 2; var key = ""; for (var i=0; i<numOfBlocks; i++) { if(key.length == 0) key = randomString(blockLength, _mode); else key = key + "-" + randomString(blockLength, _mode); } if(_timestamp !== undefined && _timestamp === true) key = new Date().getTime() + '-' + key; return key; }
javascript
{ "resource": "" }
q34750
section
train
function section(state, startLine, endLine, silent) { var ch, level, tmp, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; if (pos >= max) { return false; } ch = state.src.charCodeAt(pos); if (ch !== 0x23 /* # */ || pos >= max) { return false; } // count heading level level = 1; ch = state.src.charCodeAt(++pos); while (ch === 0x23 /* # */ && pos < max && level <= 6) { level++; ch = state.src.charCodeAt(++pos); } if (level > 6 || (pos < max && ch !== 0x20) /* space */) { return false; } pos++; let posibleMarker = state.src.substring(pos, pos + SECTION_MARKER.length); if (posibleMarker !== SECTION_MARKER) { return false; } pos = pos + SECTION_MARKER.length; // Let's cut tails like ' ### ' from the end of string max = state.skipCharsBack(max, 0x20, pos); // space tmp = state.skipCharsBack(max, 0x23, pos); // # if (tmp > pos && state.src.charCodeAt(tmp - 1) === 0x20 /* space */) { max = tmp; } state.line = startLine + 1; let sectionHeader = state.src.slice(pos, max).trim(); let nextLine = startLine + 1; let endRecoginzed = false; let contentEndLine; let innerSectionCounter = 0; for (; nextLine < endLine; nextLine++) { let line = state.getLines(nextLine, nextLine + 1, 0, false); if (SECTION_OPEN_REGEXP.test(line)) { innerSectionCounter++; } if (line === SECTION_MARKER) { // skip inner sections if (innerSectionCounter > 0) { innerSectionCounter--; continue; } contentEndLine = nextLine - 1; endRecoginzed = true; break; } } if (!endRecoginzed) { return false; } if (silent) { return true; } state.line = contentEndLine + 2; state.tokens.push({ type: "section_open", hLevel: level, lines: [startLine, state.line], level: state.level, header: sectionHeader }); state.line = startLine + 1; state.parser.tokenize(state, startLine + 1, contentEndLine, false); state.tokens.push({ type: "section_close", hLevel: level, level: state.level }); state.line = contentEndLine + 2; return true; }
javascript
{ "resource": "" }
q34751
numberToDateName
train
function numberToDateName(value, type) { if (type == 'dow') { return locale.DOW[value - 1]; } else if (type == 'mon') { return locale.MONTH[value - 1]; } }
javascript
{ "resource": "" }
q34752
applyToShareJS
train
function applyToShareJS(cm, change) { // CodeMirror changes give a text replacement. var startPos = 0; // Get character position from # of chars in each line. var i = 0; // i goes through all lines. while (i < change.from.line) { startPos += cm.lineInfo(i).text.length + 1; // Add 1 for '\n' i++; } startPos += change.from.ch; // sharejs json path to the location of the change var textPath = ['text', startPos]; // array of operations that will be submitted var ops = []; // object to keep track of lines that were deleted var deletedLines = {}; // get an updated document var doc = ctx.get(); if (change.to.line == change.from.line && change.to.ch == change.from.ch) { // nothing was removed. } else { // change in lines (deleted lines) if(change.to.line !== change.from.line){ for (i = change.to.line; i > change.from.line; i--) { if(doc.lines[i] !== undefined){ ops.push({p:['lines', i], ld: doc.lines[i]}); deletedLines[i] = true; } } } // change in text (deletion) ops.push({p:textPath, sd: change.removed.join('\n')}); } if (change.text) { // change in text (insertion) ops.push({p:textPath, si: change.text.join('\n')}); // new lines and pasting if ((change.from.line === change.to.line && change.text.length > 1) || change.origin === 'paste') { // figure out if there should also be an included line insertion // // if the change was just to add a new line character, do a replace // // on that line and then do an insert for the next if (change.text.join('\n') === '\n') { ops.push({p:['lines', change.from.line+1], li: { client: timestamps.client, timestamp: new Date () }}); } else { /* * For the following values of change.origin, we know what we want to happen. * - null - this is a programmatic insertion * - paste, redo, undo - cm detected the indicated behavior * * For others, they'll have to fall through and be handled accordingly. * Not having this conditional here leads to things breaking... */ if (change.origin && change.origin !== 'paste' && change.origin !== 'redo' && change.origin !== 'undo') { console.warn('not sure what to do in this case', change); } else { if (newTimestamp !== doc.lines[change.from.line].timestamp || timestamps.client !== doc.lines[change.from.line].client) { // replace (delete and insert) the line with updated values ops.push({p:['lines', change.from.line], ld: doc.lines[change.from.line], li: { client: timestamps.client, timestamp: new Date () }}); } for (i = 1; i < change.text.length; i++) { ops.push({p:['lines', change.from.line+1], li: { client: timestamps.client, timestamp: new Date () }}); } } } } else { // change in lines (replace + insertion) for (var changeTextIndex = 0; changeTextIndex < change.text.length; changeTextIndex++) { var lineChange = change.text[changeTextIndex]; var lineIndex = change.from.line + changeTextIndex; if (doc.lines[lineIndex]) { // if this line was just deleted, we don't want to submit any // updates for it ... we have already updated the text appropriately, // updating this now will update the wrong line. var newTimestamp = new Date (); // the line metadata has changed (new author or new date) if (newTimestamp !== doc.lines[lineIndex].timestamp || timestamps.client !== doc.lines[lineIndex].client) { // replace (delete and insert) the line with updated values ops.push({p:['lines', lineIndex], ld: doc.lines[lineIndex], li: { client: timestamps.client, timestamp: newTimestamp }}); } } else { // the line doesn't currently exist, so insert a new line ops.push({p:['lines', lineIndex], li: { client: timestamps.client, timestamp: new Date () }}); } } } } // submit the complete list of changes ctx.submitOp(ops); // call the function again on the next change, if there is one if (change.next) { applyToShareJS(cm, change.next); } }
javascript
{ "resource": "" }
q34753
start
train
function start(CB, env) { var app = this; /* |-------------------------------------------------------------------------- | Register The Environment Variables |-------------------------------------------------------------------------- | | Here we will register all of the ENV variables into the | process so that they're globally available configuration options so | sensitive configuration information can be swept out of the code. | */ (new EnvironmentVariables(app.getEnvironmentVariablesLoader())).load(env); /* |-------------------------------------------------------------------------- | Register The Configuration Repository |-------------------------------------------------------------------------- | | The configuration repository is used to lazily load in the options for | this application from the configuration files. The files are easily | separated by their concerns so they do not become really crowded. | */ app.config = new Config( app.getConfigLoader(), env ); // Set additional configurations app.config.set('cache.etagFn', utils.compileETag(app.config.get('cache').etag)); app.config.set('middleware.queryParserFn', utils.compileQueryParser(app.config.get('middleware').queryParser)); app.config.set('request.trustProxyFn', utils.compileTrust(app.config.get('request').trustProxy)); // Expose use method globally global.use = app.use.bind(app); // Register user aliases for Positron modules app.alias(app.config.get('app.aliases', {})); /* |-------------------------------------------------------------------------- | Register Booted Start Files & Expose Globals |-------------------------------------------------------------------------- | | Once the application has been booted we will expose app globals as per | user configuration. Also there are several "start" files | we will want to include. We'll register our "booted" handler here | so the files are included after the application gets booted up. | */ app.booted(function() { // expose app globals app.exposeGlobals(); /* |-------------------------------------------------------------------------- | Load The Application Start Script |-------------------------------------------------------------------------- | | The start scripts gives this application the opportunity to do things | that should be done right after application has booted like configure | application logger, load filters etc. We'll load it here. | */ var appStartScript = app.path.app + "/start/global.js"; /* |-------------------------------------------------------------------------- | Load The Environment Start Script |-------------------------------------------------------------------------- | | The environment start script is only loaded if it exists for the app | environment currently active, which allows some actions to happen | in one environment while not in the other, keeping things clean. | */ var envStartScript = app.path.app + "/start/" + env + ".js"; /* |-------------------------------------------------------------------------- | Load The Application Routes |-------------------------------------------------------------------------- | | The Application routes are kept separate from the application starting | just to keep the file a little cleaner. We'll go ahead and load in | all of the routes now and return the application to the callers. | */ var routes = app.path.app + "/routes.js"; async.filter([appStartScript, envStartScript, routes], fs.exists, function (results) { results.forEach(function (path) { require(path); }); CB(app); }); }); /* |-------------------------------------------------------------------------- | Register The Core Service Providers |-------------------------------------------------------------------------- | | The Positron core service providers register all of the core pieces | of the Positron framework including session, auth, encryption | and more. It's simply a convenient wrapper for the registration. | */ var providers = app.config.get('app').providers; app.getProviderRepository().load(providers, function() { /* |-------------------------------------------------------------------------- | Boot The Application |-------------------------------------------------------------------------- | | Once all service providers are loaded we will call the boot method on | application which will boot all service provider's and eventually boot the | positron application. | */ app.boot(); }); }
javascript
{ "resource": "" }
q34754
parse
train
function parse( roll ) { const result = parseAny( roll ); const type = result ? result.type : ''; switch ( type ) { case Type.simple: return mapToRoll( result ); case Type.classic: return mapToRoll( result ); case Type.wod: return mapToWodRoll( result ); default: return null; } }
javascript
{ "resource": "" }
q34755
gitStatus
train
function gitStatus (options, cb) { if (typeof options === "function") { cb = options; options = {}; } spawno("git", ["status", "--porcelain", "-z"], options, (err, stdout, stderr) => { if (err || stderr) { return cb(err || stderr, stdout); } cb(null, parse(stdout)); }); }
javascript
{ "resource": "" }
q34756
getValue
train
function getValue(value, offset = 0, max = 9999) { return isNaN(value) ? NAMES[value] || null : Math.min(+value + (offset), max); }
javascript
{ "resource": "" }
q34757
setDefaultOptions
train
function setDefaultOptions(options) { const defaultOptions = { src : [ '**/*.i18n.json', '**/i18n/*.json', '!node_modules' ], destFile : 'translations.pot', headers : { 'X-Poedit-Basepath' : '..', 'X-Poedit-SourceCharset': 'UTF-8', 'X-Poedit-SearchPath-0' : '.' }, defaultHeaders: true, writeFile : true }; if (options.headers === false) { options.defaultHeaders = false; } options = Object.assign({}, defaultOptions, options); if (!options.package) { options.package = options.domain || 'unnamed project'; } return options; }
javascript
{ "resource": "" }
q34758
train
function( str ) { return str // Replaces any - or _ characters with a space .replace( /[-_]+/g, ' ') // Removes any non alphanumeric characters .replace( /[^\w\s]/g, '') // Uppercases the first character in each group // immediately following a space (delimited by spaces) .replace( / (.)/g, function($1) { return $1.toUpperCase(); }) // Removes spaces .replace( / /g, '' ); }
javascript
{ "resource": "" }
q34759
train
function( str ) { // if whole numbers, convert to integer if( /^\d+$/.test(str) ) return parseInt( str ); // if decimal, convert to float if( /^\d*\.\d+$/.test(str) ) return parseFloat( str ); // if "true" or "false", return boolean if( /^true$/.test(str) ) return true; if( /^false$/.test(str) ) return false; // else, return original string return str; }
javascript
{ "resource": "" }
q34760
train
function( MyPlugin, defaults ) { // make sure a function has been passed in to // create a plugin from. if (typeof MyPlugin === 'function') { /** * the plugin object, inherits all attributes and methods * from the base plugin and the user's plugin * * @param {object} element * @param {object} options * @return {object} instance */ var Plugin = function( element, options ) { Boilerplate.call( this, element, options || {}, defaults || {} ); MyPlugin.call( this, element, options ); return this; } // inherit prototype methods from MyPlugin Plugin.prototype = MyPlugin.prototype; // set constructor method to Plugin Plugin.prototype.constructor = Plugin; // set a couple static variables Plugin.init = Boilerplate.init; Plugin.instances = {}; Plugin.defaults = defaults || {}; /** * An externalized object used to initialize the plugin and * provides external access to plugin. * * @param {object} options * @return {object} instance */ var Boost = function( options ) { return Plugin.init.call( Plugin, this, options ); } // externalize a couple vars by attaching them to obj Boost.init = function( elems, options ) { return Plugin.init.call( Plugin, elems, options ); } Boost.instances = Plugin.instances; Boost.defaults = Plugin.defaults; // return the Boost object return Boost; } else { throw '\'Boost JS\' requires a function as first paramater.'; } }
javascript
{ "resource": "" }
q34761
train
function( element, options ) { Boilerplate.call( this, element, options || {}, defaults || {} ); MyPlugin.call( this, element, options ); return this; }
javascript
{ "resource": "" }
q34762
ioServer
train
function ioServer(port = 6466, clientCount = 1, timeoutMs = 100000) { if (global.io) { // if already started return Promise.resolve() } log.info(`Starting poly-socketio server on port: ${port}, expecting ${clientCount} IO clients`) global.io = socketIO(server) var count = clientCount global.ioPromise = new Promise((resolve, reject) => { global.io.sockets.on('connection', (socket) => { // serialize for direct communication by using join room socket.on('join', (id) => { socket.join(id) count-- log.info(`${id} ${socket.id} joined, ${count} remains`) if (count <= 0) { log.info(`All ${clientCount} IO clients have joined`) resolve(server) // resolve with the server } }) socket.on('disconnect', () => { log.info(socket.id, 'left') }) }) }) .timeout(timeoutMs) .catch((err) => { log.error(err.message) log.error("Expected number of IO clients failed to join in time") process.exit(1) }) global.io.on('connection', (socket) => { // generic pass to other script socket.on('pass', (msg, fn) => { log.debug(`IO on pass, msg: ${JSON.stringify(msg, null, 2)} fn: ${fn}`) try { // e.g. split 'hello.py' into ['hello', 'py'] // lang = 'py', module = 'hello' var tokens = msg.to.split('.'), lang = tokens.pop(), module = _.join(tokens, '.') // reset of <to> for easy calling. May be empty if just passing to client.<lang> msg.to = module global.io.sockets.in(lang).emit('take', msg) } catch (e) { log.error(e.message) } }) }) return new Promise((resolve, reject) => { server.listen(port, () => { resolve() }) }) }
javascript
{ "resource": "" }
q34763
run
train
function run() { const current = now(); const queue = timeoutQueue.slice(); let interval = INTERVAL_MAX; timeoutQueue.length = 0; // Reset if (runRafId > 0 || runTimeoutId > 0) { stop(); } for (let i = queue.length - 1; i >= 0; i--) { const item = queue[i]; if (!item.cancelled) { const duration = item.time - current; if (duration <= 0) { if (isDev) { debug('timeout triggered for "%s" at %s', item.id, new Date().toLocaleTimeString()); } item.fn.apply(item.fn, item.args); } else { // Store smallest duration if (duration < interval) { interval = duration; } timeoutQueue.push(item); } } } // Loop if (timeoutQueue.length > 0) { // Use raf if requested interval is less than cutoff if (interval < INTERVAL_CUTOFF) { runRafId = raf(run); } else { runTimeoutId = setTimeout(run, interval); } } }
javascript
{ "resource": "" }
q34764
onVisibilityChangeFactory
train
function onVisibilityChangeFactory(hidden) { return function onVisibilityChange(evt) { if (document[hidden]) { debug('disable while hidden'); stop(); } else { debug('enable while visible'); if (process.env.NODE_ENV === 'development') { const current = now(); for (let i = 0, n = timeoutQueue.length; i < n; i++) { const item = timeoutQueue[i]; if (item.time <= current) { debug('timeout should trigger for "%s"', item.id); } else { const date = new Date(); date.setMilliseconds(date.getMilliseconds() + item.time - current); debug('timeout for "%s" expected at %s', item.id, date.toLocaleTimeString()); } } } run(); } }; }
javascript
{ "resource": "" }
q34765
publishToNpm
train
function publishToNpm() { return new Promise(function(resolve, reject) { _spork('npm', ['publish'], done, _.partial(reject, new Error('failed to publish to npm'))); function done() { if (!options.quiet) { gutil.log('Published to \'' + chalk.cyan('npm') + '\''); } resolve(); } }); }
javascript
{ "resource": "" }
q34766
_spork
train
function _spork(command, args, resolve, reject) { spork(command, args, {exit: false, quiet: true}) .on('exit:code', function(code) { if (code === 0) { resolve(); } else { reject(); } }); }
javascript
{ "resource": "" }
q34767
wrapMethod
train
function wrapMethod(app,fn){ //Override original express method return function(){ let args = Array.prototype.slice.call(arguments) //Check if any middleware argument is a generator function for( let i=0; i<args.length; i++ ){ //Wrap this if necessary args[i] = controllerWrapper(args[i]) } //Call original method handler return fn.apply(app,args) } }
javascript
{ "resource": "" }
q34768
train
function(el, deep) { var sub = document.createElement(el.nodeName) , attr = el.attributes , i = attr.length; while (i--) { if (attr[i].nodeValue) { sub.setAttribute(attr[i].name, attr[i].value); } } if (el.namespaceURI) { sub.namespaceURI = el.namespaceURI; } if (el.baseURI) { sub.baseURI = el.baseURI; } if (deep) { DOM.setContent(sub, DOM.getContent(el)); } return clone; }
javascript
{ "resource": "" }
q34769
train
function(el, sub) { sub = normalize(sub); DOM.removeAllListeners(el); DOM.clearData(el); DOM.clean(el); //el.parentNode.replaceChild(sub, el); el.parentNode.insertBefore(sub, el); el.parentNode.removeChild(el); return sub; }
javascript
{ "resource": "" }
q34770
train
function(el, sub) { sub = normalize(sub); el.parentNode.insertBefore(sub, el); return sub; }
javascript
{ "resource": "" }
q34771
Repository
train
function Repository(loader, environment) { /** * The loader implementation. * * @var {FileLoader} * @protected */ this.__loader = loader; /** * The current environment. * * @var {string} * @protected */ this.__environment = environment; /** * All of the configuration items. * * @var {Array} * @protected */ this.__items = []; /** * The after load callbacks for namespaces. * * @var {Array} * @protected */ this.__afterLoad = []; // call super class constructor Repository.super_.call(this); }
javascript
{ "resource": "" }
q34772
train
function() { if (!version) return; if (note) version.notes.push(note); version.rawNote = normText( _.chain(version.notes) .map(function(note) { return '* '+note.trim(); }) .value() .join('\n') ); version.notes = _.map(version.notes, normText); changelog.versions.push(version); note = ""; version = null; }
javascript
{ "resource": "" }
q34773
register
train
function register (options, __mockSelf) { var _self = __mockSelf || self var navigator = _self.navigator if (!('serviceWorker' in navigator)) { return Promise.reject(new Error('Service Workers unsupported')) } var serviceWorker = navigator.serviceWorker.controller return Promise.resolve() .then(function () { // Get existing service worker or get registration promise if (serviceWorker) return serviceWorker else if (!options) return navigator.serviceWorker.ready }) .then(function (registration) { if (registration) { // Take this service worker that the registration returned serviceWorker = registration } else if (!registration && options) { // No registration but we have options to register one return navigator.serviceWorker .register(options.url, options) .then(function (registration) { options.forceUpdate && registration.update() }) } else if (!registration && !options) { // No existing worker, // no registration that returned one, // no options to register one throw new Error('no active service worker or configuration passed to install one') } }) .then(function () { return serviceWorker }) }
javascript
{ "resource": "" }
q34774
inspectObject
train
function inspectObject(object, options) { var result = util.inspect(object, options); console.log(result); return result; }
javascript
{ "resource": "" }
q34775
Ways
train
function Ways(pattern, runner, destroyer, dependency){ if(flow && arguments.length < 3) throw new Error('In `flow` mode you must to pass at least 3 args.'); var route = new Way(pattern, runner, destroyer, dependency); routes.push(route); return route; }
javascript
{ "resource": "" }
q34776
WorkorderDetailController
train
function WorkorderDetailController($state, WORKORDER_CONFIG, workorderStatusService) { var self = this; self.adminMode = WORKORDER_CONFIG.adminMode; self.getColorIcon = function(status) { return workorderStatusService.getStatusIconColor(status).statusColor; }; }
javascript
{ "resource": "" }
q34777
richtext
train
function richtext(state, startLine, endLine, silent, opts) { let pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine], contentEndLine; if (pos >= max) { return false; } let line = state.getLines(startLine, startLine + 1, 0, false); if (!line.startsWith(RICHTEXT_OPEN_MARKER)) { return false; } if (silent) { return true; } let nextLine = startLine + 1; let content = ""; for (; nextLine < endLine; nextLine++) { let line = state.getLines(nextLine, nextLine + 1, 0, false); if (line.trim() === RICHTEXT_CLOSE_MARKER) { contentEndLine = nextLine - 1; break; } content += line + "\n"; } state.line = contentEndLine + 2; // convert md subcontent to uu5string let uu5content = opts.markdownToUu5.render(content, state.env); state.tokens.push({ type: "UU5.RichText.Block", uu5string: uu5content }); return true; }
javascript
{ "resource": "" }
q34778
apiRequest
train
function apiRequest(args, next) { var deferred = Q.defer() , opts; opts = { json: true, headers: headers, }; if(args.version === 'v2') { opts.headers.Accept = 'application/vnd.skytap.api.v2+json'; } opts = arghelper.combine(opts, args); opts = arghelper.convertAuth(opts); opts = arghelper.convertUrlParams(opts); opts = arghelper.convertReqParams(opts); debug('apiRequest: %j', opts); // check for valid required arguments if(!(opts.url && opts.method && opts.auth && opts.auth.user && opts.auth.pass)) { var error = new Error('url, method, auth.user, and auth.pass are required arguments'); deferred.reject(error); if(next) return next(error); } // make the request request(opts, function(err, res, data) { // handle exception if(err) { deferred.reject(err); if(next) next(err); } // handle non-200 response else if (res.statusCode !== 200) { deferred.reject(data); if(next) next(data); } // handle success else { deferred.resolve(data); if(next) next(null, data); } }); return deferred.promise; }
javascript
{ "resource": "" }
q34779
train
function(template, options) { options = options || {}; options.pretty = true; var fn = jade.compile(template, options); return fn(options.locals); }
javascript
{ "resource": "" }
q34780
train
function(paginator) { var template = ''; template += '.pages\n'; template += ' - if (paginator.previousPage)\n'; template += ' span.prev_next\n'; template += ' - if (paginator.previousPage === 1)\n'; template += ' span &larr;\n'; template += ' a.previous(href="/") Previous\n'; template += ' - else\n'; template += ' span &larr;\n'; template += ' a.previous(href="/page" + paginator.previousPage + "/") Previous\n'; template += ' - if (paginator.pages > 1)\n'; template += ' span.prev_next\n'; template += ' - for (var i = 1; i <= paginator.pages; i++)\n'; template += ' - if (i === paginator.page)\n'; template += ' strong.page #{i}\n'; template += ' - else if (i !== 1)\n'; template += ' a.page(href="/page" + i + "/") #{i}\n'; template += ' - else\n'; template += ' a.page(href="/") 1\n'; template += ' - if (paginator.nextPage <= paginator.pages)\n'; template += ' a.next(href="/page" + paginator.nextPage + "/") Next\n'; template += ' span &rarr;\n'; return helpers.render(template, { locals: { paginator: paginator } }); }
javascript
{ "resource": "" }
q34781
train
function() { var template , site = this; template = '' + '- for (var i = 0; i < paginator.items.length; i++)\n' + ' !{hNews(paginator.items[i], true)}\n'; return helpers.render(template, { locals: site.applyHelpers({ paginator: site.paginator }) }); }
javascript
{ "resource": "" }
q34782
train
function(feed, summarise) { var template = '' , url = this.config.url , title = this.config.title , perPage = this.config.perPage , posts = this.posts.slice(0, perPage) , site = this; summarise = typeof summarise === 'boolean' && summarise ? 3 : summarise; perPage = site.posts.length < perPage ? site.posts.length : perPage; template += '!!!xml\n'; template += 'feed(xmlns="http://www.w3.org/2005/Atom")\n'; template += ' title #{title}\n'; template += ' link(href=feed, rel="self")\n'; template += ' link(href=url)\n'; if (posts.length > 0) template += ' updated #{dx(posts[0].date)}\n'; template += ' id #{url}\n'; template += ' author\n'; template += ' name #{title}\n'; template += ' - for (var i = 0, post = posts[i]; i < ' + perPage + '; i++, post = posts[i])\n'; template += ' entry\n'; template += ' title #{post.title}\n'; template += ' link(href=url + post.url)\n'; template += ' updated #{dx(post.date)}\n'; template += ' id #{url.replace(/\\/$/, "")}#{post.url}\n'; if (summarise) template += ' content(type="html") !{h(truncateParagraphs(post.content, summarise, ""))}\n'; else template += ' content(type="html") !{h(post.content)}\n'; return helpers.render(template, { locals: site.applyHelpers({ paginator: site.paginator , posts: posts , title: title , url: url , feed: feed , summarise: summarise })}); }
javascript
{ "resource": "" }
q34783
train
function() { var allTags = []; for (var key in this.posts) { if (this.posts[key].tags) { for (var i = 0; i < this.posts[key].tags.length; i++) { var tag = this.posts[key].tags[i]; if (allTags.indexOf(tag) === -1) allTags.push(tag); } } } allTags.sort(function(a, b) { a = a.toLowerCase(); b = b.toLowerCase(); if (a < b) return -1; if (a > b) return 1; return 0; }); return allTags; }
javascript
{ "resource": "" }
q34784
train
function(tag) { var posts = []; for (var key in this.posts) { if (this.posts[key].tags && this.posts[key].tags.indexOf(tag) !== -1) { posts.push(this.posts[key]); } } return posts; }
javascript
{ "resource": "" }
q34785
train
function(text, length, moreText) { var t = text.split('</p>'); return t.length < length ? text : t.slice(0, length).join('</p>') + '</p>' + moreText; }
javascript
{ "resource": "" }
q34786
train
function(paths) { return ( gulp .src(paths.src.path) .pipe(rework( reworkUrl(function (url) { return isRelative(url) ? path.basename(url) : url; }) )) .pipe($.if(config.sourcemaps, $.sourcemaps.init({ loadMaps: true }))) .pipe($.concat(paths.changeExtension(paths.output.name, '.css'))) .pipe($.if(config.production, $.cssnano(config.css.cssnano.pluginOptions))) .pipe($.if(config.sourcemaps, $.sourcemaps.write('.'))) .pipe(gulp.dest(paths.output.baseDir)) ); }
javascript
{ "resource": "" }
q34787
logMissingPackages
train
function logMissingPackages(bundle) { var missing = _(bundle.packages).reject('installed') .map('name').uniq().value(); if ( ! missing.length) return; console.log('') console.log( colors.black.bgRed('!!! ' + bundle.name + ' is missing ' + colors.bold(missing.length) + ' package(s)') ); _.forEach(missing, function (name) { console.log(' - ' + name); }); console.log(' Try running ' + colors.cyan('bower install ' + missing.join(' '))); console.log(''); }
javascript
{ "resource": "" }
q34788
buildRooms
train
function buildRooms(baseRoom, dir, depth, attachments) { depth++; // group attachments attachments = _.chain(attachments) .clone() .concat(baseRoom.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file)))) .uniq() .value(); baseRoom.items.forEach((room, i) => { let itemPath = path.join(dir, i.toString()); fs.ensureDirSync(itemPath); if (!room.hasFiles) { buildRooms(room, itemPath, depth, attachments); } else { const roomsFiles = room.parsedFiles.map(file => { file.destination = path.join(itemPath, 'files', file.parse.base); file.content = fs.readFileSync(file.file, 'utf8'); file.mode = file.parse.ext.replace('.', ''); fs.copySync(file.file, file.destination); return file; }); // room attachments attachments = _.chain(attachments) .clone() .concat(room.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file)))) .uniq() .value(); const css_paths = _.chain(attachments) .concat(roomsFiles.map(file => path.relative(targetDir, file.destination))) .filter(file => _.endsWith(file, '.css')) .map(file => normalizePath(file, false)) .value(); const js_paths = _.chain(attachments) .concat(roomsFiles.map(file => path.relative(targetDir, file.destination))) .filter(file => _.endsWith(file, '.js')) .map(file => normalizePath(file, false)) .value(); // iframe.html fs.writeFileSync( path.join(itemPath, 'iframe.html'), handlebars.compile(iframe)({ depth, css_paths, js_paths, html: roomsFiles[0], }) ); // index.html fs.writeFileSync( path.join(itemPath, 'index.html'), handlebars.compile(index)({ depth, roomsFiles, settings, root, room, css_paths, js_paths, hasCSS: css_paths.length > 0, hasJS: js_paths.length > 0, }) ); } }); }
javascript
{ "resource": "" }
q34789
train
function(url) { var done = _onImportScript(url) loadScript( url, function runScript(err, code) { if (err) return done(err) executeNormal(code, url, done) } ) }
javascript
{ "resource": "" }
q34790
train
function(url) { var done = _onImportScript(url) loadScript( url, function runScript(err, code) { if (err) return done(err) executeJailed(code, url, done) } ) }
javascript
{ "resource": "" }
q34791
train
function(code, url, done) { var vm = require('vm') var sandbox = {} var expose = [ 'application', 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval' ] for (var i = 0; i < expose.length; i++) { sandbox[expose[i]] = global[expose[i]] } code = '"use strict";\n' + code try { vm.runInNewContext(code, vm.createContext(sandbox), url) done() } catch (e) { done(e) } }
javascript
{ "resource": "" }
q34792
train
function(url, done) { var receive = function(res) { if (res.statusCode != 200) { var msg = 'Failed to load ' + url + '\n' + 'HTTP responce status code: ' + res.statusCode printError(msg) done(new Error(msg)) } else { var content = '' res .on('end', function() { done(null, content) }) .on('readable', function() { var chunk = res.read() content += chunk.toString() }) } } try { require(url.indexOf('https') === 0 ? 'https' : 'http').get(url, receive).on('error', done) } catch (e) { done(e) } }
javascript
{ "resource": "" }
q34793
printError
train
function printError() { var _log = [new Date().toGMTString().concat(' jailed:sandbox')].concat([].slice.call(arguments)) console.error.apply(null, _log) }
javascript
{ "resource": "" }
q34794
random
train
function random(_length) { var string_length = _length; if(string_length < 0) string_length = 1; var chars = "0123456789"; var num = ''; for (var i=0; i<string_length; i++) { var rnum = Math.floor(Math.random() * chars.length); num += chars.substring(rnum,rnum+1); } return num*1; }
javascript
{ "resource": "" }
q34795
randomBetween
train
function randomBetween(_min, _max) { var max, min; if(_min > _max){ min = _max; max = _min; } else if(_min === _max){ return _min; } else{ max = _max; min = _min; } var r = Math.floor(Math.random() * max) + min; if(r > max) return max; if(r < min) return min; else return r; }
javascript
{ "resource": "" }
q34796
train
function (data) { if (this.silent) { return; } data = this.prefix ? this.prefix + '.' + data : data; var buffer = new Buffer(data); this.client.send(buffer, 0, buffer.length, this.port, this.host); }
javascript
{ "resource": "" }
q34797
train
function(obj) { if (obj instanceof Cell) { return { inside: obj.inside }; } else { return { back : serialize(obj.back), front : serialize(obj.front), plane: obj.plane, shp: obj.shp, complemented: obj.complemented, }; } }
javascript
{ "resource": "" }
q34798
Middleware
train
function Middleware(...middleware) { return (ctr) => { if (middleware != undefined) { let c = exports.globalKCState.getOrInsertController(ctr); c.middleware = middleware.concat(c.middleware); } }; }
javascript
{ "resource": "" }
q34799
ActionMiddleware
train
function ActionMiddleware(...middleware) { return function (target, propertyKey, descriptor) { if (middleware != undefined) { let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey); m.middleware = middleware.concat(m.middleware); } }; }
javascript
{ "resource": "" }