_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q12500
buildIncompleteRedeem
train
function buildIncompleteRedeem(network, txid, address, value) { const bitcoinNetwork = bitcoin.networks[network]; // NB: storemen address validation requires that vout is 0 const vout = 0; const txb = new bitcoin.TransactionBuilder(bitcoinNetwork); txb.setVersion(1); txb.addInput(hex.stripPrefix(txid), vout); txb.addOutput(address, parseInt(value)); return txb.buildIncomplete(); }
javascript
{ "resource": "" }
q12501
buildRedeemTx
train
function buildRedeemTx(network, txid, value, redeemScript, x, publicKey, signedSigHash, toAddress) { const bitcoinNetwork = bitcoin.networks[network]; // if toAddress is not supplied, derive it from the publicKey if (! toAddress) { const { address } = bitcoin.payments.p2pkh({ network: bitcoinNetwork, pubkey: Buffer.from(publicKey, 'hex'), }); toAddress = address; } const tx = btcUtil.buildIncompleteRedeem(network, txid, toAddress, value); const signature = bitcoin.script.signature.encode( new Buffer.from(signedSigHash, 'base64'), bitcoin.Transaction.SIGHASH_ALL ); const scriptSig = bitcoin.payments.p2sh({ redeem: { input: bitcoin.script.compile([ signature, Buffer.from(publicKey, 'hex'), Buffer.from(x, 'hex'), bitcoin.opcodes.OP_TRUE, ]), output: new Buffer.from(redeemScript, 'hex'), }, network: bitcoinNetwork, }).input; tx.setInputScript(0, scriptSig); return tx.toHex(); }
javascript
{ "resource": "" }
q12502
solveLinearIntersect
train
function solveLinearIntersect(a,b, c, d,e, f) { // ax + by = c; // dx + ey = d; console.log('WORKED: ', arguments); if(a === 0) { var y = c/b; var x = (d-e*y)/x; return [x, y]; } var denom = e-d/a * b; if(denom === 0) { // Either infinite solutions or no solutions return [undefined, undefined]; } var y = (f-d*c/a)/denom; var x = (c-b*y) / a; return [x, y]; }
javascript
{ "resource": "" }
q12503
fromString
train
function fromString(str) { const bytes = []; for (let n = 0, l = str.length; n < l; n++) { const hex = Number(str.charCodeAt(n)).toString(16); bytes.push(hex); } return '0x' + bytes.join(''); }
javascript
{ "resource": "" }
q12504
isValidAtomicRule
train
function isValidAtomicRule(rule) { const decls = rule.nodes.filter(node => node.type === "decl"); if (decls.length < 0) { return { isValid: true }; } for (let i = 1; i < decls.length; i++) { const current = decls[i].prop; const prev = decls[i - 1].prop; if (current < prev) { const loc = { start: { line: decls[i - 1].source.start.line, column: decls[i - 1].source.start.column - 1 }, end: { line: decls[i].source.end.line, column: decls[i].source.end.column - 1 } }; return { isValid: false, loc }; } } return { isValid: true }; }
javascript
{ "resource": "" }
q12505
html
train
function html(obj, indents) { indents = indents || 1; function indent() { return Array(indents).join(' '); } if ('string' == typeof obj) { var str = escape(obj); if (urlRegex().test(obj)) { str = '<a href="' + str + '">' + str + '</a>'; } return span('string value', '"' + str + '"'); } if ('number' == typeof obj) { return span('number', obj); } if ('boolean' == typeof obj) { return span('boolean', obj); } if (null === obj) { return span('null', 'null'); } var buf; if (Array.isArray(obj)) { ++indents; buf = '[\n' + obj.map(function(val){ return indent() + html(val, indents); }).join(',\n'); --indents; buf += '\n' + indent() + ']'; return buf; } buf = '{'; var keys = Object.keys(obj); var len = keys.length; if (len) buf += '\n'; ++indents; buf += keys.map(function(key){ var val = obj[key]; key = '"' + key + '"'; key = span('string key', key); return indent() + key + ': ' + html(val, indents); }).join(',\n'); --indents; if (len) buf += '\n' + indent(); buf += '}'; return buf; }
javascript
{ "resource": "" }
q12506
train
function(sort) { this._array = []; this._sort = sort; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return this._array.length }, }); if (typeof this._sort !== 'function') { this._sort = function(a, b) { return a - b; } } }
javascript
{ "resource": "" }
q12507
autoStartLine
train
function autoStartLine(name) { var pre = new Array(Math.floor((60 - name.length) / 2) - 3).join('-'); var post = new Array(60 - pre.length - name.length).join('-'); return signature + 'S' + pre + ' Auto Start: ' + name + ' ' + post + '\n'; }
javascript
{ "resource": "" }
q12508
makeBackup
train
function makeBackup(filePath) { var dateString = new Date().toISOString().replace(/:/g, '.').replace('Z', '').replace('T', ' '); try { fs.mkdirSync(path.join(path.dirname(filePath), 'BACKUP')); } catch(err) { if (err.code != 'EEXIST') { throw err } } fs.writeFileSync(path.join(path.dirname(filePath), 'BACKUP', dateString + ' ' + path.basename(filePath) ), fs.readFileSync(path.normalize(filePath))); }
javascript
{ "resource": "" }
q12509
getPart
train
function getPart(name, fileContent, options) { if (!name || !options) { throw new Error('name and options are required.'); } var parts = fileContent.match(getRegularExpression(name)); if ( parts ) { // Aranan bölüm varsa var fileContentDigest = calculateMD5(parts[3], options); return { all : parts[0], startLine : parts[1], warningLine : parts[2], content : parts[3], md5Line : parts[4], oldDigest : parts[5], newDigest : fileContentDigest, isChanged : fileContentDigest != parts[5], endLine : parts[6] } } else { return null; } }
javascript
{ "resource": "" }
q12510
fileExists
train
function fileExists(file) { try { var targetStat = fs.statSync(file); if (targetStat.isDirectory() ) { throw new Error("File exists but it's a driectory: " + file); } } catch(err) { if (err.code == 'ENOENT') { // No such file or directory return false; } else { throw err; } } return true; }
javascript
{ "resource": "" }
q12511
walk
train
function walk (newNode, oldNode) { // if (DEBUG) { // console.log( // 'walk\nold\n %s\nnew\n %s', // oldNode && oldNode.outerHTML, // newNode && newNode.outerHTML // ) // } if (!oldNode) { return newNode } else if (!newNode) { return null } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) { return oldNode } else if (newNode.tagName !== oldNode.tagName) { return newNode } else { _$morph_11(newNode, oldNode) updateChildren(newNode, oldNode) return oldNode } }
javascript
{ "resource": "" }
q12512
Link
train
function Link (rel, value) { if (!(this instanceof Link)) { return new Link(rel, value); } if (!rel) throw new Error('Required <link> attribute "rel"'); this.rel = rel; if (typeof value === 'object') { // If value is a hashmap, just copy properties if (!value.href) throw new Error('Required <link> attribute "href"'); var expectedAttributes = ['rel', 'href', 'name', 'hreflang', 'title', 'templated', 'icon', 'align', 'method']; for (var attr in value) { if (value.hasOwnProperty(attr)) { if (!~expectedAttributes.indexOf(attr)) { // Unexpected attribute: ignore it continue; } this[attr] = value[attr]; } } } else { // value is a scalar: use its value as href if (!value) throw new Error('Required <link> attribute "href"'); this.href = String(value); } }
javascript
{ "resource": "" }
q12513
Resource
train
function Resource (object, uri) { // new Resource(resource) === resource if (object instanceof Resource) { return object; } // Still work if "new" is omitted if (!(this instanceof Resource)) { return new Resource(object, uri); } // Initialize _links and _embedded properties this._links = {}; this._embedded = {}; // Copy properties from object // we copy AFTER initializing _links and _embedded so that user // **CAN** (but should not) overwrite them for (var property in object) { if (object.hasOwnProperty(property)) { this[property] = object[property]; } } // Use uri or object.href to initialize the only required <link>: rel = self uri = uri || this.href; if (uri === this.href) { delete this.href; } // If we have a URI, add this link // If not, we won't have a valid object (this may lead to a fatal error later) if (uri) this.link(new Link('self', uri)); }
javascript
{ "resource": "" }
q12514
resourceToJsonObject
train
function resourceToJsonObject (resource) { var result = {}; for (var prop in resource) { if (prop === '_links') { if (Object.keys(resource._links).length > 0) { // Note: we need to copy data to remove "rel" property without corrupting original Link object result._links = Object.keys(resource._links).reduce(function (links, rel) { if (Array.isArray(resource._links[rel])) { links[rel] = new Array() for (var i=0; i < resource._links[rel].length; i++) links[rel].push(resource._links[rel][i].toJSON()) } else { var link = resource._links[rel].toJSON(); links[rel] = link; delete link.rel; } return links; }, {}); } } else if (prop === '_embedded') { if (Object.keys(resource._embedded).length > 0) { // Note that we do not reformat _embedded // which means we voluntarily DO NOT RESPECT the following constraint: // > Relations with one corresponding Resource/Link have a single object // > value, relations with multiple corresponding HAL elements have an // > array of objects as their value. // Come on, resource one is *really* dumb. result._embedded = {}; for (var rel in resource._embedded) { result._embedded[rel] = resource._embedded[rel].map(resourceToJsonObject); } } } else if (resource.hasOwnProperty(prop)) { result[prop] = resource[prop]; } } return result; }
javascript
{ "resource": "" }
q12515
resourceToXml
train
function resourceToXml (resource, rel, currentIndent, nextIndent) { // Do not add line feeds if no indentation is asked var LF = (currentIndent || nextIndent) ? '\n' : ''; // Resource tag var xml = currentIndent + '<resource'; // Resource attributes: rel, href, name if (rel) xml += ' rel="' + escapeXml(rel) + '"'; if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"'; if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"'; xml += '>' + LF; // Add <link> tags for (var rel in resource._links) { if (!resource.href && rel === 'self') continue; xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF; } // Add embedded for (var embed in resource._embedded) { // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF) var rel = embed.replace(/s$/, ''); resource._embedded[embed].forEach(function (res) { xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF; }); } // Add properties as tags for (var prop in resource) { if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') { xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF; } } // Close tag and return the shit xml += currentIndent + '</resource>'; return xml; }
javascript
{ "resource": "" }
q12516
init
train
function init() { // Retrieve any arguments passed in via the command line args = cliConfig.getArguments(); // Supply usage info if help argument was passed if (args.help) { console.log(cliConfig.getUsage()); process.exit(0); } getClientAuth(function(data) { parseClientAuth(data, function(err, data) { if (err) { console.error(err.message); process.exit(0); } writeEdgerc(data, function(err) { if (err) { if (err.errno == -13) { console.error("Unable to access " + err.path + ". Please make sure you " + "have permission to access this file or perhaps try running the " + "command as sudo."); process.exit(0); } } console.log("The section '" + args.section + "' has been succesfully added to " + args.path + "\n"); }); }); }); }
javascript
{ "resource": "" }
q12517
getClientAuth
train
function getClientAuth(callback) { console.log("This script will create a section named '" + args.section + "'" + "in the local file " + args.path + ".\n"); // Read the client authorization file. If not found, notify user. if (args.file) { clientAuthData = fs.readFileSync(args.file, 'utf8'); console.log("+++ Found authorization file: " + args.file); callback(clientAuthData); } else { // Present user with input dialogue requesting copy and paste of // client auth data. var input = []; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var msg = "After authorizing your client in the OPEN API Administration " + "tool, \nexport the credentials and paste the contents of the export file " + "below (making sure to include the final blank line). \nThen enter " + "control-D to continue: \n\n>>>\n"; rl.setPrompt(msg); rl.prompt(); rl.on('line', function(cmd) { input.push(cmd); }); rl.on('close', function(cmd) { if (input.length < 1) { // Data was not input, assumed early exit from the program. console.log("Kill command received without input. Exiting program."); process.exit(0); } console.log("\n<<<\n\n"); clientAuthData = input.join('\n'); callback(clientAuthData); }); } }
javascript
{ "resource": "" }
q12518
parseClientAuth
train
function parseClientAuth(data, callback) { authParser.parseAuth(data, function(err, data) { if (err) callback(err, null); callback(null, data); }); }
javascript
{ "resource": "" }
q12519
writeEdgerc
train
function writeEdgerc(data, callback) { try { edgercWriter.writeEdgercSection( args.path, args.section, data["URL:"], data["Secret:"], data["Tokens:"], data["token:"], data["max-body"] ); } catch (err) { callback(err); } return callback(); }
javascript
{ "resource": "" }
q12520
groupBy
train
function groupBy(handlebars) { var helpers = { /** * @method group * @param {Array} list * @param {Object} options * @param {Object} options.hash * @param {String} options.hash.by * @return {String} Rendered partial. */ group: function (list, options) { options = options || {}; var fn = options.fn || noop, inverse = options.inverse || noop, hash = options.hash, prop = hash && hash.by, keys = [], groups = {}; if (!prop || !list || !list.length) { return inverse(this); } function groupKey(item) { var key = get(item, prop); if (keys.indexOf(key) === -1) { keys.push(key); } if (!groups[key]) { groups[key] = { value: key, items: [] }; } groups[key].items.push(item); } function renderGroup(buffer, key) { return buffer + fn(groups[key]); } list.forEach(groupKey); return keys.reduce(renderGroup, ''); } }; handlebars.registerHelper(helpers); return handlebars; }
javascript
{ "resource": "" }
q12521
markDuplicateVariableNames
train
function markDuplicateVariableNames (row, i, rows) { var ast = row[kAst] var scope = scan.scope(ast) if (scope) { scope.forEach(function (binding, name) { binding[kShouldRename] = rows.usedGlobalVariables.has(name) rows.usedGlobalVariables.add(name) }) } }
javascript
{ "resource": "" }
q12522
detectCycles
train
function detectCycles (rows) { var cyclicalModules = new Set() var checked = new Set() rows.forEach(function (module) { var visited = [] check(module) function check (row) { var i = visited.indexOf(row) if (i !== -1) { checked.add(row) for (; i < visited.length; i++) { cyclicalModules.add(visited[i]) } return } if (checked.has(row)) return visited.push(row) Object.keys(row.deps).forEach(function (k) { var dep = row.deps[k] var other = rows.byId[dep] if (other) check(other, visited) }) visited.pop() } }) // mark cyclical dependencies for (var i = 0; i < rows.length; i++) { rows[i][kEvaluateOnDemand] = cyclicalModules.has(rows[i]) } return cyclicalModules.size > 0 }
javascript
{ "resource": "" }
q12523
createSectionObj
train
function createSectionObj( host, secret, accessToken, clientToken, maxBody) { var section = {}; section.client_secret = secret; section.host = host; section.access_token = accessToken; section.client_token = clientToken; section["max-body"] = maxBody ? maxBody : "131072"; return section; }
javascript
{ "resource": "" }
q12524
VideoConverter
train
function VideoConverter(options) { var _this = this; this.name = function() { return options.name; }; this.extName = function () { return options.ext; }; /** * Generate a stream from the video converter * @param size * @returns {*} */ this.toStream = function (size) { var factory = ps.factory(false, !options.streamEncoding, function (input, output, callback) { var stream = this; var ffm = _this.convert(input, size, output, callback); ['start','progress','error'].forEach(function(event) { ffm.on(event, function() { stream.emit.apply(stream,[event].concat(arguments)); }); }); }); factory.videoConverter = this; return factory; }; this.convert = function (input, size, output, callback) { var ffm = ffmpeg(input).outputOptions(options.args); ffm.on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); if (size) { var match = size.match(/(\d+)x(\d+)/); if (match) { ffm.addOutputOptions("-vf", scale(match[1], match[2])); } else { throw new Error("Illegal size specification: "+size); } } ffm.output(output); ffm.on("error", function (error, stdout, stderr) { error.stderr = stderr; callback(error); }); ffm.run(); if (typeof(output) === "string") { // If 'output' is a file, the callback must be called after ffmpeg has finished (only then is the file ready) ffm.on("end", function () { callback(); }); } else { callback(); } return ffm; } }
javascript
{ "resource": "" }
q12525
initAsyncResource
train
function initAsyncResource(asyncId, type, triggerAsyncId, resource) { if (wakingup) { return; } wakingup = true; setImmediate(() => { EventLoop.wakeupBackgroundThread(); wakingup = false; }); }
javascript
{ "resource": "" }
q12526
getUrl
train
function getUrl(version = current) { const name = `native-ext-v${version}-${os}-${arch}.${ext}`; return `https://github.com/NiklasGollenstede/native-ext/releases/download/v${version}/`+ name; }
javascript
{ "resource": "" }
q12527
train
function(satoshi) { //validate arg var satoshiType = typeof satoshi; if (satoshiType === 'string') { satoshi = toNumber(satoshi); satoshiType = 'number'; } if (satoshiType !== 'number'){ throw new TypeError('toBitcoin must be called on a number or string, got ' + satoshiType); } if (!Number.isInteger(satoshi)) { throw new TypeError('toBitcoin must be called on a whole number or string format whole number'); } var bigSatoshi = new Big(satoshi); return Number(bigSatoshi.div(conversion)); }
javascript
{ "resource": "" }
q12528
train
function(bitcoin) { //validate arg var bitcoinType = typeof bitcoin; if (bitcoinType === 'string') { bitcoin = toNumber(bitcoin); bitcoinType = 'number'; } if (bitcoinType !== 'number'){ throw new TypeError('toSatoshi must be called on a number or string, got ' + bitcoinType); } var bigBitcoin = new Big(bitcoin); return Number(bigBitcoin.times(conversion)); }
javascript
{ "resource": "" }
q12529
createArguments
train
function createArguments() { var cli = commandLineArgs([{ name: 'file', alias: 'f', type: String, defaultValue: "", description: "Full path to the credentials file.", required: true }, { name: 'section', alias: 's', type: String, defaultValue: "default", description: "Title of the section that will be added to the .edgerc file." }, { name: 'path', alias: 'p', type: String, defaultValue: os.homedir() + "/.edgerc", description: "Full path to the .edgerc file." }, { name: 'help', alias: 'h', description: "Display help and usage information." }]); return cli; }
javascript
{ "resource": "" }
q12530
Device
train
function Device(id, version, label, type, node_id, senders, receivers) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * [Device type]{@link deviceTypes} URN. * @type {string} * @readonly */ this.type = this.generateType(type); /** * Globally unique UUID identifier for the {@link Node} which initially created * the Device. * @type {string} * @readonly */ this.node_id = this.generateNodeID(node_id); /** * UUIDs of [Senders]{@link Sender} attached to the Device. * @type {string[]} * @readonly */ this.senders = this.generateSenders(senders); /** * UUIDs of [Receivers]{@link Receiver} attached to the Device. * @type {string[]} * @readonly */ this.receivers = this.generateReceivers(receivers); return immutable(this, { prototype: Device.prototype }); }
javascript
{ "resource": "" }
q12531
pack
train
function pack(payload_obj) { var payload_plist = plist.build(payload_obj) , payload_buf = new Buffer(payload_plist); var header = { len: payload_buf.length + 16, version: 1, request: 8, tag: 1 }; var header_buf = new Buffer(16); header_buf.fill(0); header_buf.writeUInt32LE(header.len, 0); header_buf.writeUInt32LE(header.version, 4); header_buf.writeUInt32LE(header.request, 8); header_buf.writeUInt32LE(header.tag, 12); return Buffer.concat([header_buf, payload_buf]); }
javascript
{ "resource": "" }
q12532
UsbmuxdError
train
function UsbmuxdError(message, number) { this.name = 'UsbmuxdError'; this.message = message; if (number) { this.number = number; this.message += ', Err #' + number; } if (number === 2) this.message += ": Device isn't connected"; if (number === 3) this.message += ": Port isn't available or open"; if (number === 5) this.message += ": Malformed request"; }
javascript
{ "resource": "" }
q12533
createListener
train
function createListener() { var conn = net.connect(address) , req = protocol.listen; /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.listen('Response: \n%o', msg); // first response always acknowledges / denies the request: if (msg.MessageType === 'Result' && msg.Number !== 0) { conn.emit('error', new UsbmuxdError('Listen failed', msg.Number)); conn.end(); } // subsequent responses report on connected device status: if (msg.MessageType === 'Attached') { devices[msg.Properties.SerialNumber] = msg.Properties; conn.emit('attached', msg.Properties.SerialNumber); } if (msg.MessageType === 'Detached') { // given msg.DeviceID, find matching device and remove it Object.keys(devices).forEach(function(key) { if (devices[key].DeviceID === msg.DeviceID) { conn.emit('detached', devices[key].SerialNumber); delete devices[key]; } }); } }); debug.listen('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); return conn; }
javascript
{ "resource": "" }
q12534
connect
train
function connect(deviceID, devicePort) { return Q.Promise(function(resolve, reject) { var conn = net.connect(address) , req = protocol.connect(deviceID, devicePort); /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.connect('Response: \n%o', msg); if (msg.MessageType === 'Result' && msg.Number === 0) { conn.removeListener('data', parse); resolve(conn); return; } // anything other response means it failed reject(new UsbmuxdError('Tunnel failed', msg.Number)); conn.end(); }); debug.connect('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); }); }
javascript
{ "resource": "" }
q12535
Relay
train
function Relay(devicePort, relayPort, opts) { if (!(this instanceof Relay)) return new Relay(arguments); this._devicePort = devicePort; this._relayPort = relayPort; opts = opts || {}; this._udid = opts.udid; this._startListener(opts.timeout); this._startServer(); }
javascript
{ "resource": "" }
q12536
initAngular
train
function initAngular(angular) { // Define the layerXDKController const controllers = angular.module('layerXDKControllers', []); // Setup the properties for the given widget that is being generated function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); } // Gather all UI Components Object.keys(ComponentsHash) .forEach((componentName) => { const component = ComponentsHash[componentName]; // Get the camel case controller name const controllerName = componentName.replace(/-(.)/g, (str, value) => value.toUpperCase()); controllers.directive(controllerName, () => ({ restrict: 'E', link: (scope, elem, attrs) => { const functionProps = component.properties; setupProps(scope, elem[0], attrs, functionProps); }, })); }); }
javascript
{ "resource": "" }
q12537
setupProps
train
function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); }
javascript
{ "resource": "" }
q12538
setupDomNodes
train
function setupDomNodes() { this.nodes = {}; this._findNodesWithin(this, (node, isComponent) => { const layerId = node.getAttribute && node.getAttribute('layer-id'); if (layerId) this.nodes[layerId] = node; if (isComponent) { if (!node.properties) node.properties = {}; node.properties.parentComponent = this; } }); }
javascript
{ "resource": "" }
q12539
_findNodesWithin
train
function _findNodesWithin(node, callback) { const children = node.childNodes; for (let i = 0; i < children.length; i++) { const innerNode = children[i]; if (innerNode instanceof HTMLElement) { const isLUIComponent = Boolean(ComponentsHash[innerNode.tagName.toLowerCase()]); const result = callback(innerNode, isLUIComponent); if (result) return result; // If its not a custom webcomponent with children that it manages and owns, iterate on it if (!isLUIComponent) { const innerResult = this._findNodesWithin(innerNode, callback); if (innerResult) return innerResult; } } } }
javascript
{ "resource": "" }
q12540
getTemplate
train
function getTemplate() { const tagName = this.tagName.toLocaleLowerCase(); if (ComponentsHash[tagName].style) { const styleNode = document.createElement('style'); styleNode.id = 'style-' + this.tagName.toLowerCase(); styleNode.innerHTML = ComponentsHash[tagName].style; document.getElementsByTagName('head')[0].appendChild(styleNode); ComponentsHash[tagName].style = ''; // insure it doesn't get added to head a second time } return ComponentsHash[tagName].template; }
javascript
{ "resource": "" }
q12541
trigger
train
function trigger(eventName, details) { const evt = new CustomEvent(eventName, { detail: details, bubbles: true, cancelable: true, }); this.dispatchEvent(evt); return !evt.defaultPrevented; }
javascript
{ "resource": "" }
q12542
toggleClass
train
function toggleClass(...args) { const cssClass = args[0]; const enable = (args.length === 2) ? args[1] : !this.classList.contains(cssClass); this.classList[enable ? 'add' : 'remove'](cssClass); }
javascript
{ "resource": "" }
q12543
createElement
train
function createElement(tagName, properties) { const node = document.createElement(tagName); node.parentComponent = this; const ignore = ['parentNode', 'name', 'classList', 'noCreate']; Object.keys(properties).forEach((propName) => { if (ignore.indexOf(propName) === -1) node[propName] = properties[propName]; }); if (properties.classList) properties.classList.forEach(className => node.classList.add(className)); if (properties.parentNode) properties.parentNode.appendChild(node); if (properties.name) this.nodes[properties.name] = node; if (!properties.noCreate) { if (typeof CustomElements !== 'undefined') CustomElements.upgradeAll(node); if (node._onAfterCreate) node._onAfterCreate(); } return node; }
javascript
{ "resource": "" }
q12544
destroy
train
function destroy() { if (this.properties._internalState.onDestroyCalled) return; if (this.parentNode) { this.parentNode.removeChild(this); } Object.keys(this.nodes || {}).forEach((name) => { if (this.nodes[name] && this.nodes[name].destroy) this.nodes[name].destroy(); }); this.onDestroy(); }
javascript
{ "resource": "" }
q12545
_registerAll
train
function _registerAll() { if (!registerAllCalled) { registerAllCalled = true; Object.keys(ComponentsHash) .filter(tagName => typeof ComponentsHash[tagName] !== 'function') .forEach(tagName => _registerComponent(tagName)); } }
javascript
{ "resource": "" }
q12546
onRender
train
function onRender() { try { // Setup the layer-sender-name if (this.nodes.sender) { this.nodes.sender.innerHTML = this.item.sender.displayName; } if (this.nodes.avatar) { this.nodes.avatar.users = [this.item.sender]; } // Setup the layer-date if (this.nodes.date && !this.item.isNew()) { if (this.dateRenderer) this.nodes.date.dateRenderer = this.dateRenderer; this.nodes.date.date = this.item.sentAt; } // Setup the layer-message-status if (this.nodes.status && this.messageStatusRenderer) { this.nodes.status.messageStatusRenderer = this.messageStatusRenderer; } // Setup the layer-delete if (this.nodes.delete) { this.nodes.delete.enabled = this.getDeleteEnabled ? this.getDeleteEnabled(this.properties.item) : true; } // Generate the renderer for this Message's MessageParts. this._applyContentTag(); // Render all mutable data this.onRerender(); } catch (err) { logger.error('layer-message-item.render(): ', err); } }
javascript
{ "resource": "" }
q12547
Versionned
train
function Versionned(id, version, label) { /** * Globally unique UUID identifier for the resource. * @type {string} * @readonly */ this.id = this.generateID(id); /** * String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) * indicating precisely when an attribute of the resource last changed. * @type {string} * @readonly */ this.version = this.generateVersion(version); /** * Freeform string label for the resource. * @type {string} * @readonly */ this.label = this.generateLabel(label); return immutable(this, {prototype: Versionned.prototype}); }
javascript
{ "resource": "" }
q12548
initClass
train
function initClass(newClass, className, namespace) { // Make sure our new class has a name property try { if (newClass.name !== className) newClass.altName = className; } catch (e) { // No-op } // Make sure our new class has a _supportedEvents, _ignoredEvents, _inObjectIgnore and EVENTS properties if (!newClass._supportedEvents) newClass._supportedEvents = Root._supportedEvents; if (!newClass._ignoredEvents) newClass._ignoredEvents = Root._ignoredEvents; if (newClass.mixins) { newClass.mixins.forEach((mixin) => { if (mixin.events) newClass._supportedEvents = newClass._supportedEvents.concat(mixin.events); Object.keys(mixin.staticMethods || {}) .forEach(methodName => (newClass[methodName] = mixin.staticMethods[methodName])); if (mixin.properties) { Object.keys(mixin.properties).forEach((key) => { newClass.prototype[key] = mixin.properties[key]; }); } if (mixin.methods) { Object.keys(mixin.methods).forEach((key) => { newClass.prototype[key] = mixin.methods[key]; }); } }); } // Generate a list of properties for this class; we don't include any // properties from Layer.Core.Root const keys = Object.keys(newClass.prototype).filter(key => newClass.prototype.hasOwnProperty(key) && !Root.prototype.hasOwnProperty(key) && typeof newClass.prototype[key] !== 'function'); // Define getters/setters for any property that has __adjust or __update methods defined keys.forEach(name => defineProperty(newClass, name)); if (namespace) namespace[className] = newClass; }
javascript
{ "resource": "" }
q12549
Receiver
train
function Receiver(id, version, label, description, format, caps, tags, device_id, transport, subscription) { // Globally unique identifier for the Receiver this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed. this.version = this.generateVersion(version); // Freeform string label for the Receiver this.label = this.generateLabel(label); // Detailed description of the Receiver this.description = this.generateDescription(description); // Type of Flow accepted by the Receiver as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering sources. // Values should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Device ID which this Receiver forms part of. this.device_id = this.generateDeviceID(device_id); // Transport type accepted by the Receiver in URN format this.transport = this.generateTransport(transport); // Object containing the 'sender_id' currently subscribed to. Sender_id // should be null on initialisation. this.subscription = this.generateSubscription(subscription); return immutable(this, { prototype : Receiver.prototype }); }
javascript
{ "resource": "" }
q12550
registerResources
train
function registerResources(rs) { registerPromise = registerPromise.then(() => { return Promise.all(rs.map((r) => { return Promise.denodeify(pushResource)(r); })); }); }
javascript
{ "resource": "" }
q12551
info
train
function info() { if (argv.verbose !== 1) return; var args = Array.prototype.slice.call(arguments); if (!args[args.length-1]) args.pop(); // if last arg is undefined, remove it console.log.apply(console, args); }
javascript
{ "resource": "" }
q12552
onErr
train
function onErr(err) { // local port is in use if (err.code === 'EADDRINUSE') { panic('Local port is in use \nFailing...'); } // usbmux not there if (err.code === 'ECONNREFUSED' || err.code === 'EADDRNOTAVAIL') { panic('Usbmuxd not found at', usbmux.address, '\nFailing...'); } // other panic('%s \nFailing...', err); }
javascript
{ "resource": "" }
q12553
listenForDevices
train
function listenForDevices() { console.log('Listening for connected devices... \n'); usbmux.createListener() .on('error', onErr) .on('attached', function(udid) { console.log('Device found: ', udid); }) .on('detached', function(udid) { console.log('Device removed: ', udid); }); }
javascript
{ "resource": "" }
q12554
startRelay
train
function startRelay(portPair) { var devicePort = portPair[0] , relayPort = portPair[1]; console.log('Starting relay from local port: %s -> device port: %s', relayPort, devicePort); new usbmux.Relay(devicePort, relayPort, {udid: argv.udid}) .on('error', onErr) .on('warning', console.log.bind(console, 'Warning: device not found...')) .on('ready', info.bind(this, 'Device ready: ')) .on('attached', info.bind(this, 'Device attached: ')) .on('detached', info.bind(this, 'Device detached: ')) .on('connect', info.bind(this, 'New connection to relay started.')) .on('disconnect', info.bind(this, 'Connection to relay closed.')) .on('close', info.bind(this, 'Relay has closed.')); }
javascript
{ "resource": "" }
q12555
Source
train
function Source(id, version, label, description, format, caps, tags, device_id, parents) { // Globally unique identifier for the Source this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed this.version = this.generateVersion(version); // Freeform string label for the Source this.label = this.generateLabel(label); // Detailed description of the Source this.description = this.generateDescription(description); // Format of the data coming from the Source as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering Sources. Values // should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Globally unique identifier for the Device which initially created the Source this.device_id = this.generateDeviceID(device_id); // Array of UUIDs representing the Source IDs of Grains which came together at // the input to this Source (may change over the lifetime of this Source) this.parents = this.generateParents(parents); return immutable(this, { prototype: Source.prototype }); }
javascript
{ "resource": "" }
q12556
validStore
train
function validStore(store) { return store && typeof store.getNodes === 'function' && typeof store.getNode === 'function' && typeof store.getDevices === 'function' && typeof store.getDevice === 'function' && typeof store.getSources === 'function' && typeof store.getSource === 'function' && typeof store.getSenders === 'function' && typeof store.getSender === 'function' && typeof store.getReceivers === 'function' && typeof store.getReceiver === 'function' && typeof store.getFlows === 'function' && typeof store.getFlow === 'function'; // TODO add more of the required methods ... or drop this check? }
javascript
{ "resource": "" }
q12557
checkSkip
train
function checkSkip (skip, keys) { if (skip && typeof skip === 'string') skip = +skip; if (!skip || Number(skip) !== skip || skip % 1 !== 0 || skip < 0) skip = 0; if (skip > keys.length) skip = keys.length; return skip; }
javascript
{ "resource": "" }
q12558
checkLimit
train
function checkLimit (limit, keys) { if (limit && typeof limit === 'string') limit = +limit; if (!limit || Number(limit) !== limit || limit % 1 !== 0 || limit > keys.length) limit = keys.length; if (limit < 0) limit = 0; return limit; }
javascript
{ "resource": "" }
q12559
getCollection
train
function getCollection(items, query, cb, argsLength) { var skip = 0, limit = Number.MAX_SAFE_INTEGER; setImmediate(function() { if (argsLength === 1) { cb = query; } else { skip = (query.skip) ? query.skip : 0; limit = (query.limit) ? query.limit : Number.MAX_SAFE_INTEGER; } var sortedKeys = Object.keys(items); var qKeys = remove(remove(Object.keys(query), /skip/), /limit/); qKeys.forEach(function (k) { try { var re = new RegExp(query[k]); sortedKeys = sortedKeys.filter(function (l) { return items[l][k].toString().match(re); }); } catch (e) { console.error(`Problem filtering collection for parameter ${k}.`, e.message); } }); skip = checkSkip(skip, sortedKeys); limit = checkLimit(limit, sortedKeys); if (sortedKeys.length === 0 || limit === 0 || skip >= sortedKeys.length) { return cb(null, [], sortedKeys.length, 1, 1, 0); } var pages = Math.ceil(sortedKeys.length / limit); var pageOf = Math.ceil(skip / limit) + 1; var itemArray = new Array(); for ( var x = skip ; x < Math.min(skip + limit, sortedKeys.length) ; x++ ) { itemArray.push(items[sortedKeys[x]]); } cb(null, itemArray, sortedKeys.length, pageOf, pages, itemArray.length); }); }
javascript
{ "resource": "" }
q12560
Node
train
function Node(id, version, label, href, hostname, caps, services) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * HTTP access href for the Node's API. * @type {string} * @readonly */ this.href = this.generateHref(href); /** * Node hostname - set to null when not present. * @type {string} * @readonly */ this.hostname = this.generateHostname(hostname); /** * [Capabilities]{@link capabilities} (not yet defined). * @type {Object} * @readonly */ this.caps = this.generateCaps(caps); /** * Array of objects containing a URN format type and href. * @type {Object[]} * @readonly */ this.services = this.generateServices(services); return immutable(this, { prototype : Node.prototype }); }
javascript
{ "resource": "" }
q12561
Flow
train
function Flow(id, version, label, description, format, tags, source_id, parents) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * Detailed description of the Flow. * @type {string} * @readonly */ this.description = this.generateDescription(description); /** * [Format]{@link formats} of the data coming from the Flow as a URN. * @type {string} * @readonly */ this.format = this.generateFormat(format); /** * Key value set of freeform string tags to aid in filtering Flows. Can be * empty. * @type {Array.<string, string[]>} * @readonly */ this.tags = this.generateTags(tags); // Treating as a required property /** * Globally unique UUID identifier for the [source]{@link Source} which initially * created the Flow. * @type {string} * @readonly */ this.source_id = this.generateSourceID(source_id); /** * Array of UUIDs representing the Flow IDs of Grains which came together to * generate this Flow. (May change over the lifetime of this Flow.) */ this.parents = this.generateParents(parents); return immutable(this, { prototype: Flow.prototype }); }
javascript
{ "resource": "" }
q12562
generateNames
train
function generateNames(model, prefix, name) { if (name === void 0) { name = ""; } model.fullPackageName = prefix + (name != "." ? name : ""); // Copies the settings (I'm lazy) model.properties = argv.properties; model.explicitRequired = argv.explicitRequired; model.camelCaseProperties = argv.camelCaseProperties; model.camelCaseGetSet = argv.camelCaseGetSet; model.underscoreGetSet = argv.underscoreGetSet; model.generateBuilders = argv.generateBuilders; var newDefinitions = {}; // Generate names for messages // Recursive call for all messages var key; for (key in model.messages) { var message = model.messages[key]; newDefinitions[message.name] = "Builder"; generateNames(message, model.fullPackageName, "." + (model.name ? model.name : "")); } // Generate names for enums for (key in model.enums) { var currentEnum = model.enums[key]; newDefinitions[currentEnum.name] = ""; currentEnum.fullPackageName = model.fullPackageName + (model.name ? "." + model.name : ""); } // For fields of types which are defined in the same message, // update the field type in consequence for (key in model.fields) { var field = model.fields[key]; if (typeof newDefinitions[field.type] !== "undefined") { field.type = model.name + "." + field.type; } } model.oneofsArray = []; for (key in model.oneofs) { var oneof = model.oneofs[key]; model.oneofsArray.push({ name: key, value: oneof }); } // Add the new definitions in the model for generate builders var definitions = []; for (key in newDefinitions) { definitions.push({ name: key, type: ((model.name ? (model.name + ".") : "") + key) + newDefinitions[key] }); } model.definitions = definitions; }
javascript
{ "resource": "" }
q12563
_allocate
train
function _allocate(bytes) { var address = Module._malloc(bytes.length); Module.HEAPU8.set(bytes, address); return address; }
javascript
{ "resource": "" }
q12564
doRun
train
function doRun() { if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening Module['calledRun'] = true; if (ABORT) return; ensureInitRuntime(); preMain(); if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); if (Module['_main'] && shouldRunNow) Module['callMain'](args); postRun(); }
javascript
{ "resource": "" }
q12565
wrapReplEval
train
function wrapReplEval(replServer) { const defaultEval = replServer.eval; return function(code, context, file, cb) { return defaultEval.call(this, code, context, file, (err, result) => { if (!result || !result.then) { return cb(err, result); } result.then(resolved => { resolvePromises(result, resolved); cb(null, resolved); }).catch(err => { resolvePromises(result, err); console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m'); if (err && err.message) { console.log('\x1b[31m' + err.message + '\x1b[0m'); } // Application errors are not REPL errors cb(null, err); }); }); function resolvePromises(promise, resolved) { Object.keys(context).forEach(key => { // Replace any promise handles in the REPL context with the resolved promise if (context[key] === promise) { context[key] = resolved; } }); } }; }
javascript
{ "resource": "" }
q12566
getNextId
train
function getNextId(db, collectionName, fieldName, callback) { if (typeof fieldName == "function") { callback = fieldName; fieldName = null; } fieldName = fieldName || getOption(collectionName, "field"); var collection = db.collection(defaultSettings.collection); var step = getOption(collectionName, "step"); collection.findAndModify( {_id: collectionName, field: fieldName}, null, {$inc: {seq: step}}, {upsert: true, new: true}, function (err, result) { if (err) { if (err.code == 11000) { process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback)); } else { callback(err); } } else { if (result.value && result.value.seq) { callback(null, result.value.seq); } else { callback(null, result.seq); } } } ); }
javascript
{ "resource": "" }
q12567
mkNumber
train
function mkNumber(val) { var sign = 1; if (val.charAt(0) == '-') { sign = -1; val = val.substring(1); } if (Lang.NUMBER_DEC.test(val)) return sign * parseInt(val, 10); else if (Lang.NUMBER_HEX.test(val)) return sign * parseInt(val.substring(2), 16); else if (Lang.NUMBER_OCT.test(val)) return sign * parseInt(val.substring(1), 8); else if (val === 'inf') return sign * Infinity; else if (val === 'nan') return NaN; else if (Lang.NUMBER_FLT.test(val)) return sign * parseFloat(val); throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val); }
javascript
{ "resource": "" }
q12568
setOption
train
function setOption(options, name, value) { if (typeof options[name] === 'undefined') options[name] = value; else { if (!Array.isArray(options[name])) options[name] = [ options[name] ]; options[name].push(value); } }
javascript
{ "resource": "" }
q12569
train
function(builder, parent, name) { /** * Builder reference. * @type {!ProtoBuf.Builder} * @expose */ this.builder = builder; /** * Parent object. * @type {?ProtoBuf.Reflect.T} * @expose */ this.parent = parent; /** * Object name in namespace. * @type {string} * @expose */ this.name = name; /** * Fully qualified class name * @type {string} * @expose */ this.className; }
javascript
{ "resource": "" }
q12570
train
function(builder, parent, name, options, syntax) { T.call(this, builder, parent, name); /** * @override */ this.className = "Namespace"; /** * Children inside the namespace. * @type {!Array.<ProtoBuf.Reflect.T>} */ this.children = []; /** * Options. * @type {!Object.<string, *>} */ this.options = options || {}; /** * Syntax level (e.g., proto2 or proto3). * @type {!string} */ this.syntax = syntax || "proto2"; }
javascript
{ "resource": "" }
q12571
train
function(type, resolvedType, isMapKey, syntax) { /** * Element type, as a string (e.g., int32). * @type {{name: string, wireType: number}} */ this.type = type; /** * Element type reference to submessage or enum definition, if needed. * @type {ProtoBuf.Reflect.T|null} */ this.resolvedType = resolvedType; /** * Element is a map key. * @type {boolean} */ this.isMapKey = isMapKey; /** * Syntax level of defining message type, e.g., proto2 or proto3. * @type {string} */ this.syntax = syntax; if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0) throw Error("Invalid map key type: " + type.name); }
javascript
{ "resource": "" }
q12572
mkLong
train
function mkLong(value, unsigned) { if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean' && value.low === value.low && value.high === value.high) return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned); if (typeof value === 'string') return ProtoBuf.Long.fromString(value, unsigned || false, 10); if (typeof value === 'number') return ProtoBuf.Long.fromNumber(value, unsigned || false); throw Error("not convertible to Long"); }
javascript
{ "resource": "" }
q12573
train
function(builder, parent, name, options, isGroup, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Message"; /** * Extensions range. * @type {!Array.<number>|undefined} * @expose */ this.extensions = undefined; /** * Runtime message class. * @type {?function(new:ProtoBuf.Builder.Message)} * @expose */ this.clazz = null; /** * Whether this is a legacy group or not. * @type {boolean} * @expose */ this.isGroup = !!isGroup; // The following cached collections are used to efficiently iterate over or look up fields when decoding. /** * Cached fields. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>} * @private */ this._fields = null; /** * Cached fields by id. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsById = null; /** * Cached fields by name. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsByName = null; }
javascript
{ "resource": "" }
q12574
train
function(values, var_args) { ProtoBuf.Builder.Message.call(this); // Create virtual oneof properties for (var i=0, k=oneofs.length; i<k; ++i) this[oneofs[i].name] = null; // Create fields and set default values for (i=0, k=fields.length; i<k; ++i) { var field = fields[i]; this[field.name] = field.repeated ? [] : (field.map ? new ProtoBuf.Map(field) : null); if ((field.required || T.syntax === 'proto3') && field.defaultValue !== null) this[field.name] = field.defaultValue; } if (arguments.length > 0) { var value; // Set field values from a values object if (arguments.length === 1 && values !== null && typeof values === 'object' && /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) && /* not a repeated field */ !Array.isArray(values) && /* not a Map */ !(values instanceof ProtoBuf.Map) && /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) && /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) && /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) { this.$set(values); } else // Set field values from arguments, in declaration order for (i=0, k=arguments.length; i<k; ++i) if (typeof (value = arguments[i]) !== 'undefined') this.$set(fields[i].name, value); // May throw } }
javascript
{ "resource": "" }
q12575
cloneRaw
train
function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) { if (obj === null || typeof obj !== 'object') { // Convert enum values to their respective names if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) { var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj); if (name !== null) return name; } // Pass-through string, number, boolean, null... return obj; } // Convert ByteBuffers to raw buffer or strings if (ByteBuffer.isByteBuffer(obj)) return binaryAsBase64 ? obj.toBase64() : obj.toBuffer(); // Convert Longs to proper objects or strings if (ProtoBuf.Long.isLong(obj)) return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj); var clone; // Clone arrays if (Array.isArray(obj)) { clone = []; obj.forEach(function(v, k) { clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType); }); return clone; } clone = {}; // Convert maps to objects if (obj instanceof ProtoBuf.Map) { var it = obj.entries(); for (var e = it.next(); !e.done; e = it.next()) clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType); return clone; } // Everything else is a non-null object var type = obj.$type, field = undefined; for (var i in obj) if (obj.hasOwnProperty(i)) { if (type && (field = type.getChild(i))) clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType); else clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings); } return clone; }
javascript
{ "resource": "" }
q12576
skipTillGroupEnd
train
function skipTillGroupEnd(expectedId, buf) { var tag = buf.readVarint32(), // Throws on OOB wireType = tag & 0x07, id = tag >>> 3; switch (wireType) { case ProtoBuf.WIRE_TYPES.VARINT: do tag = buf.readUint8(); while ((tag & 0x80) === 0x80); break; case ProtoBuf.WIRE_TYPES.BITS64: buf.offset += 8; break; case ProtoBuf.WIRE_TYPES.LDELIM: tag = buf.readVarint32(); // reads the varint buf.offset += tag; // skips n bytes break; case ProtoBuf.WIRE_TYPES.STARTGROUP: skipTillGroupEnd(id, buf); break; case ProtoBuf.WIRE_TYPES.ENDGROUP: if (id === expectedId) return false; else throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)"); case ProtoBuf.WIRE_TYPES.BITS32: buf.offset += 4; break; default: throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType); } return true; }
javascript
{ "resource": "" }
q12577
train
function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) { T.call(this, builder, message, name); /** * @override */ this.className = "Message.Field"; /** * Message field required flag. * @type {boolean} * @expose */ this.required = rule === "required"; /** * Message field repeated flag. * @type {boolean} * @expose */ this.repeated = rule === "repeated"; /** * Message field map flag. * @type {boolean} * @expose */ this.map = rule === "map"; /** * Message field key type. Type reference string if unresolved, protobuf * type if resolved. Valid only if this.map === true, null otherwise. * @type {string|{name: string, wireType: number}|null} * @expose */ this.keyType = keytype || null; /** * Message field type. Type reference string if unresolved, protobuf type if * resolved. In a map field, this is the value type. * @type {string|{name: string, wireType: number}} * @expose */ this.type = type; /** * Resolved type reference inside the global namespace. * @type {ProtoBuf.Reflect.T|null} * @expose */ this.resolvedType = null; /** * Unique message field id. * @type {number} * @expose */ this.id = id; /** * Message field options. * @type {!Object.<string,*>} * @dict * @expose */ this.options = options || {}; /** * Default value. * @type {*} * @expose */ this.defaultValue = null; /** * Enclosing OneOf. * @type {?ProtoBuf.Reflect.Message.OneOf} * @expose */ this.oneof = oneof || null; /** * Syntax level of this definition (e.g., proto3). * @type {string} * @expose */ this.syntax = syntax || 'proto2'; /** * Original field name. * @type {string} * @expose */ this.originalName = this.name; // Used to revert camelcase transformation on naming collisions /** * Element implementation. Created in build() after types are resolved. * @type {ProtoBuf.Element} * @expose */ this.element = null; /** * Key element implementation, for map fields. Created in build() after * types are resolved. * @type {ProtoBuf.Element} * @expose */ this.keyElement = null; // Convert field names to camel case notation if the override is set if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField)) this.name = ProtoBuf.Util.toCamelCase(this.name); }
javascript
{ "resource": "" }
q12578
train
function(builder, message, rule, type, name, id, options) { Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options); /** * Extension reference. * @type {!ProtoBuf.Reflect.Extension} * @expose */ this.extension; }
javascript
{ "resource": "" }
q12579
train
function(builder, parent, name, options, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Enum"; /** * Runtime enum object. * @type {Object.<string,number>|null} * @expose */ this.object = null; }
javascript
{ "resource": "" }
q12580
train
function(builder, enm, name, id) { T.call(this, builder, enm, name); /** * @override */ this.className = "Enum.Value"; /** * Unique enum value id. * @type {number} * @expose */ this.id = id; }
javascript
{ "resource": "" }
q12581
train
function(builder, root, name, options) { Namespace.call(this, builder, root, name, options); /** * @override */ this.className = "Service"; /** * Built runtime service class. * @type {?function(new:ProtoBuf.Builder.Service)} */ this.clazz = null; }
javascript
{ "resource": "" }
q12582
train
function(rpcImpl) { ProtoBuf.Builder.Service.call(this); /** * Service implementation. * @name ProtoBuf.Builder.Service#rpcImpl * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} * @expose */ this.rpcImpl = rpcImpl || function(name, msg, callback) { // This is what a user has to implement: A function receiving the method name, the actual message to // send (type checked) and the callback that's either provided with the error as its first // argument or null and the actual response message. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async! }; }
javascript
{ "resource": "" }
q12583
train
function(builder, svc, name, options) { T.call(this, builder, svc, name); /** * @override */ this.className = "Service.Method"; /** * Options. * @type {Object.<string, *>} * @expose */ this.options = options || {}; }
javascript
{ "resource": "" }
q12584
train
function(builder, svc, name, request, response, request_stream, response_stream, options) { Method.call(this, builder, svc, name, options); /** * @override */ this.className = "Service.RPCMethod"; /** * Request message name. * @type {string} * @expose */ this.requestName = request; /** * Response message name. * @type {string} * @expose */ this.responseName = response; /** * Whether requests are streamed * @type {bool} * @expose */ this.requestStream = request_stream; /** * Whether responses are streamed * @type {bool} * @expose */ this.responseStream = response_stream; /** * Resolved request message type. * @type {ProtoBuf.Reflect.Message} * @expose */ this.resolvedRequestType = null; /** * Resolved response message type. * @type {ProtoBuf.Reflect.Message} * @expose */ this.resolvedResponseType = null; }
javascript
{ "resource": "" }
q12585
train
function(options) { /** * Namespace. * @type {ProtoBuf.Reflect.Namespace} * @expose */ this.ns = new Reflect.Namespace(this, null, ""); // Global namespace /** * Namespace pointer. * @type {ProtoBuf.Reflect.T} * @expose */ this.ptr = this.ns; /** * Resolved flag. * @type {boolean} * @expose */ this.resolved = false; /** * The current building result. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null} * @expose */ this.result = null; /** * Imported files. * @type {Array.<string>} * @expose */ this.files = {}; /** * Import root override. * @type {?string} * @expose */ this.importRoot = null; /** * Options. * @type {!Object.<string, *>} * @expose */ this.options = options || {}; }
javascript
{ "resource": "" }
q12586
propagateSyntax
train
function propagateSyntax(parent) { if (parent['messages']) { parent['messages'].forEach(function(child) { child["syntax"] = parent["syntax"]; propagateSyntax(child); }); } if (parent['enums']) { parent['enums'].forEach(function(child) { child["syntax"] = parent["syntax"]; }); } }
javascript
{ "resource": "" }
q12587
train
function(field, contents) { if (!field.map) throw Error("field is not a map"); /** * The field corresponding to this map. * @type {!ProtoBuf.Reflect.Field} */ this.field = field; /** * Element instance corresponding to key type. * @type {!ProtoBuf.Reflect.Element} */ this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax); /** * Element instance corresponding to value type. * @type {!ProtoBuf.Reflect.Element} */ this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax); /** * Internal map: stores mapping of (string form of key) -> (key, value) * pair. * * We provide map semantics for arbitrary key types, but we build on top * of an Object, which has only string keys. In order to avoid the need * to convert a string key back to its native type in many situations, * we store the native key value alongside the value. Thus, we only need * a one-way mapping from a key type to its string form that guarantees * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1 * === K2). * * @type {!Object<string, {key: *, value: *}>} */ this.map = {}; /** * Returns the number of elements in the map. */ Object.defineProperty(this, "size", { get: function() { return Object.keys(this.map).length; } }); // Fill initial contents from a raw object. if (contents) { var keys = Object.keys(contents); for (var i = 0; i < keys.length; i++) { var key = this.keyElem.valueFromString(keys[i]); var val = this.valueElem.verifyValue(contents[keys[i]]); this.map[this.keyElem.valueToString(key)] = { key: key, value: val }; } } }
javascript
{ "resource": "" }
q12588
getCompressedStream
train
function getCompressedStream(req, res) { var encoding = req.headers['accept-encoding'] || ''; var stream; var contentEncodingHeader = res.getHeader('Content-Encoding'); if ((contentEncodingHeader === 'gzip') || /\bgzip\b/.test(encoding)) { if (!contentEncodingHeader) { res.setHeader('Content-Encoding', 'gzip'); } stream = zlib.createGzip(); stream.pipe(res); } else if ((contentEncodingHeader === 'deflate') || /\bdeflate\b/.test(encoding)) { if (!contentEncodingHeader) { res.setHeader('Content-Encoding', 'deflate'); } stream = zlib.createDeflate(); stream.pipe(res); } return stream; }
javascript
{ "resource": "" }
q12589
concatStreams
train
function concatStreams(array) { var concat = new stream.PassThrough(); function pipe(i) { if (i < array.length - 1) { array[i].pipe(concat, {end: false}); array[i].on('end', function () { pipe(i + 1) }); } else { array[i].pipe(concat); } } if (array.length > 0) { pipe(0); } return concat; }
javascript
{ "resource": "" }
q12590
augmentServer
train
function augmentServer(server, opts) { server.templateReader = opts.templateReader || templateReader; server.documentRoot = opts.documentRoot || p.join(process.cwd(), 'web'); server.saveRequestChunks = !!opts.saveRequestChunks; server.template = template; server.stack = []; server.stackInsertion = 0; defaultRoute.forEach(function(mkfn) { server.handle(mkfn(server)); }); server.stackInsertion = 0; server.on('request', function(req, res) { listener(server, req, res) }); }
javascript
{ "resource": "" }
q12591
listener
train
function listener(server, req, res) { augmentReqRes(req, res, server); var ask = new Ask(server, req, res); req.ask = ask; // Legacy. bubble(ask, 0); }
javascript
{ "resource": "" }
q12592
bubble
train
function bubble(ask, layer) { ask.server.stack[layer](ask.req, ask.res, function next() { if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1); else { ask.res.statusCode = 500; ask.res.end('Internal Server Error\n'); } }); }
javascript
{ "resource": "" }
q12593
genericUnit
train
function genericUnit (server) { var processors = []; server.handler = function (f) { processors.push(f); }; return function genericLayer (req, res, next) { for (var i = 0; i < processors.length; i++) { var keep = processors[i](req.ask); if (keep) { return; } // Don't call next, nor the rest. } next(); // We never catch that request. }; }
javascript
{ "resource": "" }
q12594
socketUnit
train
function socketUnit (server) { var io = server.io; // Client-side: <script src="/$socket.io/socket.io.js"></script> return function socketLayer (req, res, next) { // Socket.io doesn't care about anything but /$socket.io now. if (req.path.slice(1, 11) !== '$socket.io') next(); }; }
javascript
{ "resource": "" }
q12595
wsUnit
train
function wsUnit (server) { var chanPool = server.wsChannels = {}; // Main WebSocket API: // ws(channel :: String, conListener :: function(socket)) server.ws = function ws (channel, conListener) { if (channel[0] !== '/') { channel = '/$websocket:' + channel; // Deprecated API. } if (chanPool[channel] !== undefined) { chanPool[channel].close(); } chanPool[channel] = new WebSocket.Server({ server: server, path: channel, }); chanPool[channel].on('connection', conListener); return chanPool[channel]; }; // WebSocket broadcast API. // webBroadcast(channel :: String, recvListener :: function(data, end)) server.wsBroadcast = function wsBroadcast (channel, recvListener) { if (channel[0] === '/') { return server.ws(channel, function (socket) { socket.on('message', function wsBroadcastRecv (data, flags) { recvListener({data: data, flags: flags}, { send: function wsBroadcastSend (dataBack) { chanPool[channel].clients.forEach(function (s) { s.send(dataBack); }); }, }); }); }); } else { // Deprecated API return server.ws(channel, function (socket) { socket.on('message', function wsBroadcastRecv (data, flags) { recvListener(data, function wsBroadcastSend (dataBack) { chanPool[channel].clients.forEach(function (s) { s.send(dataBack); }); }); }); }); } }; return function wsLayer (req, res, next) { // This doesn't actually get run, since ws overrides it at the root. if (chanPool[req.path] === undefined) return next(); }; }
javascript
{ "resource": "" }
q12596
ajaxUnit
train
function ajaxUnit (server) { var ajax = server.ajax = new EventEmitter(); // Register events to be fired before loading the ajax data. var ajaxReq = server.ajaxReq = new EventEmitter(); return function ajaxLayer (req, res, next) { if (req.path[1] !== '$') { return next(); } var action = req.path.slice(2); if (ajax.listeners(action).length <= 0) { return next(); } res.setHeader('Content-Type', mime.json); ajaxReq.emit(action, req.ask); // Get all data requests. getQueries(req, function(err) { if (err == null) { ajax.emit(action, req.query, function ajaxEnd(data) { res.compressed().end(JSON.stringify(data || {})); }, req.ask); } else { log('While parsing', req.url + ':\n' + err , 'error'); return next(); } }); }; }
javascript
{ "resource": "" }
q12597
staticUnit
train
function staticUnit (server) { return function staticLayer (req, res, next) { respondWithFile(req, res, req.path, next); }; }
javascript
{ "resource": "" }
q12598
routeUnit
train
function routeUnit (server) { var regexes = []; var callbacks = []; function route (paths, literalCall) { regexes.push(RegExp(paths)); callbacks.push(literalCall); } server.route = route; return function routeLayer (req, res, next) { var matched = null; var cbindex = -1; for (var i = 0; i < regexes.length; i++) { matched = req.path.match (regexes[i]); if (matched !== null) { cbindex = i; break; } } if (cbindex >= 0) { catchpath(req, res, matched, callbacks[cbindex], server.templateReader); } else { next(); } }; }
javascript
{ "resource": "" }
q12599
removeJob
train
function removeJob(self,id) { if(id === undefined) { id = self.queue.shift().id ; } else { // Search queue for id and remove if exists for(var i=0;i<self.queue.length;i++) { if(self.queue[i].id === id) { self.queue.splice(i,1) ; break ; } } } return new Promise(function(resolve,reject) { if(self.db === null) reject('Open queue database before starting queue') ; if(self.debug) console.log('About to delete') ; if(self.debug) console.log('Removing job: '+id) ; if(self.debug) console.log('From table: '+table) ; if(self.debug) console.log('With queue length: '+self.length) ; self.db.run("DELETE FROM " + table + " WHERE id = ?", id, function(err) { if(err !== null) reject(err) ; if(this.changes) // Number of rows affected (0 == false) resolve(id) ; reject("Job id "+id+" was not removed from queue") ; }); }) ; }
javascript
{ "resource": "" }