id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
31,500
Incroud/cassanova
lib/query.js
processPartitionKeys
function processPartitionKeys(keys){ var result = "(", j, len, keyGroup; if(typeof keys === 'string'){ return result += keys + ")"; } len = keys.length; for(j = 0; j< keys.length; j++){ keyGroup = keys[j]; if(keyGroup instanceof Array){ result += "("; result += keyGroup.join(", "); result += ")"; }else{ result += keyGroup; } result += (j < len-1) ? ", " : ""; } result += ")"; return result; }
javascript
function processPartitionKeys(keys){ var result = "(", j, len, keyGroup; if(typeof keys === 'string'){ return result += keys + ")"; } len = keys.length; for(j = 0; j< keys.length; j++){ keyGroup = keys[j]; if(keyGroup instanceof Array){ result += "("; result += keyGroup.join(", "); result += ")"; }else{ result += keyGroup; } result += (j < len-1) ? ", " : ""; } result += ")"; return result; }
[ "function", "processPartitionKeys", "(", "keys", ")", "{", "var", "result", "=", "\"(\"", ",", "j", ",", "len", ",", "keyGroup", ";", "if", "(", "typeof", "keys", "===", "'string'", ")", "{", "return", "result", "+=", "keys", "+", "\")\"", ";", "}", ...
An internal method, it processes primary partition keys into a CQL statement. @param {Object} keys A string, Array or multi-dimensional Array @return {String} A CQL formatted string of the partition key
[ "An", "internal", "method", "it", "processes", "primary", "partition", "keys", "into", "a", "CQL", "statement", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/query.js#L22-L47
31,501
Incroud/cassanova
lib/query.js
function(collection, blacklist){ var obj, result = [], prop, i, j, collLen, listLen; blacklist = blacklist || ["__columns"]; if(!collection || !collection.length){ return result; } collLen = collection.length; for(i=0; i<collLen; i++){ obj = collection[i]; //delete null properties for(prop in obj){ if(obj[prop] === null){ delete obj[prop]; } } listLen = blacklist.length; for(j=0; j<listLen; j++){ delete obj[blacklist[j]]; } //These are javascript objects and not json, so we have to do this magic to strip it of get methods. result.push(JSON.parse(JSON.stringify(obj))); } return result; }
javascript
function(collection, blacklist){ var obj, result = [], prop, i, j, collLen, listLen; blacklist = blacklist || ["__columns"]; if(!collection || !collection.length){ return result; } collLen = collection.length; for(i=0; i<collLen; i++){ obj = collection[i]; //delete null properties for(prop in obj){ if(obj[prop] === null){ delete obj[prop]; } } listLen = blacklist.length; for(j=0; j<listLen; j++){ delete obj[blacklist[j]]; } //These are javascript objects and not json, so we have to do this magic to strip it of get methods. result.push(JSON.parse(JSON.stringify(obj))); } return result; }
[ "function", "(", "collection", ",", "blacklist", ")", "{", "var", "obj", ",", "result", "=", "[", "]", ",", "prop", ",", "i", ",", "j", ",", "collLen", ",", "listLen", ";", "blacklist", "=", "blacklist", "||", "[", "\"__columns\"", "]", ";", "if", ...
Removes black-listed properties from the data
[ "Removes", "black", "-", "listed", "properties", "from", "the", "data" ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/query.js#L664-L700
31,502
hoodiehq/pouchdb-hoodie-sync
lib/one.js
one
function one (state, eventName, handler) { state.emitter.once(eventName, handler) return state.api }
javascript
function one (state, eventName, handler) { state.emitter.once(eventName, handler) return state.api }
[ "function", "one", "(", "state", ",", "eventName", ",", "handler", ")", "{", "state", ".", "emitter", ".", "once", "(", "eventName", ",", "handler", ")", "return", "state", ".", "api", "}" ]
binds event only once to handler @param {String} eventName push, pull, connect, disconnect @param {Function} handler function once bound to event @return {Promise}
[ "binds", "event", "only", "once", "to", "handler" ]
c489baf813020c7f0cbd111224432cb6718c90de
https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/one.js#L10-L14
31,503
jugglingdb/connect-jugglingdb
index.js
JugglingStore
function JugglingStore(schema, options) { options = options || {}; Store.call(this, options); this.maxAge = options.maxAge || defaults.maxAge; var coll = this.collection = schema.define('Session', { sid: { type: String, index: true }, expires: { type: Date, index: true }, session: schema.constructor.JSON }, { table: options.table || defaults.table }); coll.validatesUniquenessOf('sid'); // destroy all expired sessions after each create/update coll.afterSave = function(next) { coll.iterate({where: { expires: {lte: new Date()} }}, function(obj, nexti, i) { obj.destroy(nexti); }, next); }; }
javascript
function JugglingStore(schema, options) { options = options || {}; Store.call(this, options); this.maxAge = options.maxAge || defaults.maxAge; var coll = this.collection = schema.define('Session', { sid: { type: String, index: true }, expires: { type: Date, index: true }, session: schema.constructor.JSON }, { table: options.table || defaults.table }); coll.validatesUniquenessOf('sid'); // destroy all expired sessions after each create/update coll.afterSave = function(next) { coll.iterate({where: { expires: {lte: new Date()} }}, function(obj, nexti, i) { obj.destroy(nexti); }, next); }; }
[ "function", "JugglingStore", "(", "schema", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "Store", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "maxAge", "=", "options", ".", "maxAge", "||", "defaults", ...
Initialize JugglingStore with the given `options`. @param {JugglingDB.Schema} schema @param {Object} options @api public
[ "Initialize", "JugglingStore", "with", "the", "given", "options", "." ]
b088660f6d69bd52dfd79c8523034cd0d2673694
https://github.com/jugglingdb/connect-jugglingdb/blob/b088660f6d69bd52dfd79c8523034cd0d2673694/index.js#L30-L58
31,504
rangle/koast
lib/app/app-maker.js
validateRouteDefinition
function validateRouteDefinition(routeDef) { var expectedKeys = ['route', 'type', 'module', 'path']; var expectedTypes = ['static', 'module']; var expectedTypeMap = { 'static': 'path', 'module': 'module' }; var keys = Object.keys(routeDef); var EXPECTED_NUMBER_OF_PROPERTIES = 3; //Handle warnings first; if (routeDef.route && routeDef.route.substr(0, 1) !== '/') { log.warn('Route path does not start with a slash:', routeDef.route); } if(keys.length !== EXPECTED_NUMBER_OF_PROPERTIES) { throw new Error('Route definition does not contain all required properties'); } _.map(keys, function compareAgainstExpected(key) { if (expectedKeys.indexOf(key) === -1) { throw new Error('Unexpected property found in route definition. Please check the spelling'); } }); if (expectedTypes.indexOf(routeDef.type) === -1) { throw new Error('Unknown type of route. Please check your configuration'); } if (keys.indexOf(expectedTypeMap[routeDef.type]) === -1) { throw new Error('Route type ' + routeDef.type + ' requires ' + expectedTypeMap[routeDef.type] + ' to be defined'); } return true; }
javascript
function validateRouteDefinition(routeDef) { var expectedKeys = ['route', 'type', 'module', 'path']; var expectedTypes = ['static', 'module']; var expectedTypeMap = { 'static': 'path', 'module': 'module' }; var keys = Object.keys(routeDef); var EXPECTED_NUMBER_OF_PROPERTIES = 3; //Handle warnings first; if (routeDef.route && routeDef.route.substr(0, 1) !== '/') { log.warn('Route path does not start with a slash:', routeDef.route); } if(keys.length !== EXPECTED_NUMBER_OF_PROPERTIES) { throw new Error('Route definition does not contain all required properties'); } _.map(keys, function compareAgainstExpected(key) { if (expectedKeys.indexOf(key) === -1) { throw new Error('Unexpected property found in route definition. Please check the spelling'); } }); if (expectedTypes.indexOf(routeDef.type) === -1) { throw new Error('Unknown type of route. Please check your configuration'); } if (keys.indexOf(expectedTypeMap[routeDef.type]) === -1) { throw new Error('Route type ' + routeDef.type + ' requires ' + expectedTypeMap[routeDef.type] + ' to be defined'); } return true; }
[ "function", "validateRouteDefinition", "(", "routeDef", ")", "{", "var", "expectedKeys", "=", "[", "'route'", ",", "'type'", ",", "'module'", ",", "'path'", "]", ";", "var", "expectedTypes", "=", "[", "'static'", ",", "'module'", "]", ";", "var", "expectedTy...
Validate the incoming route configurations are valie. @param routeDef @example { 'route': '/alwaysStartWithSlash', 'type': 'static' || 'module', 'module' || 'path': 'filePath' } @return true if valid otherwise throw an error.
[ "Validate", "the", "incoming", "route", "configurations", "are", "valie", "." ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/app/app-maker.js#L73-L107
31,505
entrinsik-org/utils
lib/constant-aggregate-expression.js
ConstantAggregateExpression
function ConstantAggregateExpression(number) { if(!Number.isFinite(number)) this.number = parseFloat(number); else this.number = number; }
javascript
function ConstantAggregateExpression(number) { if(!Number.isFinite(number)) this.number = parseFloat(number); else this.number = number; }
[ "function", "ConstantAggregateExpression", "(", "number", ")", "{", "if", "(", "!", "Number", ".", "isFinite", "(", "number", ")", ")", "this", ".", "number", "=", "parseFloat", "(", "number", ")", ";", "else", "this", ".", "number", "=", "number", ";", ...
Represent a constant number for use an an argument to a aggregation calculation @param number {number} @constructor
[ "Represent", "a", "constant", "number", "for", "use", "an", "an", "argument", "to", "a", "aggregation", "calculation" ]
da2bff77afd0c3316148d7b79b2416d021a9b53a
https://github.com/entrinsik-org/utils/blob/da2bff77afd0c3316148d7b79b2416d021a9b53a/lib/constant-aggregate-expression.js#L11-L16
31,506
gbv/jskos-tools
lib/identifiers.js
reduceSet
function reduceSet(set) { return set.map(member => member && member.uri).filter(Boolean) }
javascript
function reduceSet(set) { return set.map(member => member && member.uri).filter(Boolean) }
[ "function", "reduceSet", "(", "set", ")", "{", "return", "set", ".", "map", "(", "member", "=>", "member", "&&", "member", ".", "uri", ")", ".", "filter", "(", "Boolean", ")", "}" ]
Reduce JSKOS set to members with URI.
[ "Reduce", "JSKOS", "set", "to", "members", "with", "URI", "." ]
da8672203362ea874f4ab9cdd34b990369987075
https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/identifiers.js#L10-L12
31,507
gbv/jskos-tools
lib/identifiers.js
mappingContent
function mappingContent(mapping) { const { from, to, type } = mapping let result = { from: reduceBundle(from || {}), to: reduceBundle(to || {}), type: [ type && type[0] || "http://www.w3.org/2004/02/skos/core#mappingRelation" ] } for (let side of ["from", "to"]) { if ((result[side][memberField(result[side])] || []).length == 0) { let scheme = mapping[side + "Scheme"] if (scheme && scheme.uri) { // Create new object to remove all unnecessary properties. result[side + "Scheme"] = { uri: scheme.uri } } } } return result }
javascript
function mappingContent(mapping) { const { from, to, type } = mapping let result = { from: reduceBundle(from || {}), to: reduceBundle(to || {}), type: [ type && type[0] || "http://www.w3.org/2004/02/skos/core#mappingRelation" ] } for (let side of ["from", "to"]) { if ((result[side][memberField(result[side])] || []).length == 0) { let scheme = mapping[side + "Scheme"] if (scheme && scheme.uri) { // Create new object to remove all unnecessary properties. result[side + "Scheme"] = { uri: scheme.uri } } } } return result }
[ "function", "mappingContent", "(", "mapping", ")", "{", "const", "{", "from", ",", "to", ",", "type", "}", "=", "mapping", "let", "result", "=", "{", "from", ":", "reduceBundle", "(", "from", "||", "{", "}", ")", ",", "to", ":", "reduceBundle", "(", ...
Reduce mapping to reduced fields from, to, and type.
[ "Reduce", "mapping", "to", "reduced", "fields", "from", "to", "and", "type", "." ]
da8672203362ea874f4ab9cdd34b990369987075
https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/identifiers.js#L29-L48
31,508
gbv/jskos-tools
lib/identifiers.js
mappingMembers
function mappingMembers(mapping) { const { from, to } = mapping const memberUris = [ from, to ].filter(Boolean) .map(bundle => reduceSet(bundle[memberField(bundle)] || [])) return [].concat(...memberUris).sort() }
javascript
function mappingMembers(mapping) { const { from, to } = mapping const memberUris = [ from, to ].filter(Boolean) .map(bundle => reduceSet(bundle[memberField(bundle)] || [])) return [].concat(...memberUris).sort() }
[ "function", "mappingMembers", "(", "mapping", ")", "{", "const", "{", "from", ",", "to", "}", "=", "mapping", "const", "memberUris", "=", "[", "from", ",", "to", "]", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "bundle", "=>", "reduceSet", "...
Get a sorted list of member URIs.
[ "Get", "a", "sorted", "list", "of", "member", "URIs", "." ]
da8672203362ea874f4ab9cdd34b990369987075
https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/identifiers.js#L51-L56
31,509
hoodiehq/pouchdb-hoodie-sync
lib/on.js
on
function on (state, eventName, handler) { state.emitter.on(eventName, handler) return state.api }
javascript
function on (state, eventName, handler) { state.emitter.on(eventName, handler) return state.api }
[ "function", "on", "(", "state", ",", "eventName", ",", "handler", ")", "{", "state", ".", "emitter", ".", "on", "(", "eventName", ",", "handler", ")", "return", "state", ".", "api", "}" ]
binds event to handler @param {String} eventName push, pull, connect, disconnect @param {Function} handler function bound to event @return {Promise}
[ "binds", "event", "to", "handler" ]
c489baf813020c7f0cbd111224432cb6718c90de
https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/on.js#L10-L14
31,510
Pinoccio/client-node-pinoccio
lib/commands/bridge/index.js
bridgeCommand
function bridgeCommand(command,cb){ if(!connected) return setImmediate(function(){ cb('killed'); }); if(!connected.pings) connected.pings = {}; var id = ++pingid; var timer; connected.pings[id] = function(err,data){ clearTimeout(timer); delete connected.pings[id] cb(err,data); }; connected.send({command:command,cb:id}); // set 5 second time limit for callback. timer = setTimeout(function(){ cb("timeout"); },5000); }
javascript
function bridgeCommand(command,cb){ if(!connected) return setImmediate(function(){ cb('killed'); }); if(!connected.pings) connected.pings = {}; var id = ++pingid; var timer; connected.pings[id] = function(err,data){ clearTimeout(timer); delete connected.pings[id] cb(err,data); }; connected.send({command:command,cb:id}); // set 5 second time limit for callback. timer = setTimeout(function(){ cb("timeout"); },5000); }
[ "function", "bridgeCommand", "(", "command", ",", "cb", ")", "{", "if", "(", "!", "connected", ")", "return", "setImmediate", "(", "function", "(", ")", "{", "cb", "(", "'killed'", ")", ";", "}", ")", ";", "if", "(", "!", "connected", ".", "pings", ...
rpc to worker process for commands.
[ "rpc", "to", "worker", "process", "for", "commands", "." ]
9ee7b254639190a228dce6a4db9680f2c1bf1ca5
https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/commands/bridge/index.js#L200-L218
31,511
Pinoccio/client-node-pinoccio
lib/commands/bridge/index.js
deviceScan
function deviceScan(){ shuffle(Object.keys(watchs.boards)).forEach(function(id){ plugHandler({event:'plug',device:watchs.boards[id]}); }); }
javascript
function deviceScan(){ shuffle(Object.keys(watchs.boards)).forEach(function(id){ plugHandler({event:'plug',device:watchs.boards[id]}); }); }
[ "function", "deviceScan", "(", ")", "{", "shuffle", "(", "Object", ".", "keys", "(", "watchs", ".", "boards", ")", ")", ".", "forEach", "(", "function", "(", "id", ")", "{", "plugHandler", "(", "{", "event", ":", "'plug'", ",", "device", ":", "watchs...
find the next eligble bridge scout.
[ "find", "the", "next", "eligble", "bridge", "scout", "." ]
9ee7b254639190a228dce6a4db9680f2c1bf1ca5
https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/commands/bridge/index.js#L497-L501
31,512
hoodiehq/pouchdb-hoodie-sync
lib/sync.js
sync
function sync (state, docsOrIds) { var syncedObjects = [] var errors = state.db.constructor.Errors return Promise.resolve(state.remote) .then(function (remote) { return new Promise(function (resolve, reject) { if (Array.isArray(docsOrIds)) { docsOrIds = docsOrIds.map(toId) } else { docsOrIds = docsOrIds && [toId(docsOrIds)] } if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) { return Promise.reject(errors.NOT_AN_OBJECT) } var replication = state.db.sync(remote, { doc_ids: docsOrIds, include_docs: true }) /* istanbul ignore next */ replication.catch(function () { // handled trough 'error' event }) replication.on('complete', function () { resolve(syncedObjects) }) replication.on('error', reject) replication.on('change', function (change) { syncedObjects = syncedObjects.concat(change.change.docs) for (var i = 0; i < change.change.docs.length; i++) { state.emitter.emit(change.direction, change.change.docs[i]) } }) }) }) }
javascript
function sync (state, docsOrIds) { var syncedObjects = [] var errors = state.db.constructor.Errors return Promise.resolve(state.remote) .then(function (remote) { return new Promise(function (resolve, reject) { if (Array.isArray(docsOrIds)) { docsOrIds = docsOrIds.map(toId) } else { docsOrIds = docsOrIds && [toId(docsOrIds)] } if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) { return Promise.reject(errors.NOT_AN_OBJECT) } var replication = state.db.sync(remote, { doc_ids: docsOrIds, include_docs: true }) /* istanbul ignore next */ replication.catch(function () { // handled trough 'error' event }) replication.on('complete', function () { resolve(syncedObjects) }) replication.on('error', reject) replication.on('change', function (change) { syncedObjects = syncedObjects.concat(change.change.docs) for (var i = 0; i < change.change.docs.length; i++) { state.emitter.emit(change.direction, change.change.docs[i]) } }) }) }) }
[ "function", "sync", "(", "state", ",", "docsOrIds", ")", "{", "var", "syncedObjects", "=", "[", "]", "var", "errors", "=", "state", ".", "db", ".", "constructor", ".", "Errors", "return", "Promise", ".", "resolve", "(", "state", ".", "remote", ")", "."...
syncs one or multiple objects between local and remote database @param {StringOrObject} docsOrIds object or ID of object or array of objects/ids (all optional) @return {Promise}
[ "syncs", "one", "or", "multiple", "objects", "between", "local", "and", "remote", "database" ]
c489baf813020c7f0cbd111224432cb6718c90de
https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/sync.js#L13-L55
31,513
bem-contrib/md-to-bemjson
packages/remark-bemjson/lib/exports.js
createExport
function createExport(exportOptions, content) { if (!content) return content; const type = exportOptions.type; const name = exportOptions.name; const exportFunction = exportFabric(type); return exportFunction(name, content); }
javascript
function createExport(exportOptions, content) { if (!content) return content; const type = exportOptions.type; const name = exportOptions.name; const exportFunction = exportFabric(type); return exportFunction(name, content); }
[ "function", "createExport", "(", "exportOptions", ",", "content", ")", "{", "if", "(", "!", "content", ")", "return", "content", ";", "const", "type", "=", "exportOptions", ".", "type", ";", "const", "name", "=", "exportOptions", ".", "name", ";", "const",...
Create export for one of provided modules @param {Object} exportOptions - export type and name @param {ExportType} exportOptions.type - export type @param {String} [exportOptions.name] - export name, required for browser modules @param {String} content - bemjson content @returns {String}
[ "Create", "export", "for", "one", "of", "provided", "modules" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/remark-bemjson/lib/exports.js#L33-L41
31,514
soajs/soajs.core.drivers
infra/google/kubernetes/index.js
createVpcNetwork
function createVpcNetwork(mCb) { let networksOptions = Object.assign({}, options); networksOptions.params = { name, returnGlobalOperation: true }; networks.add(networksOptions, (error, globalOperationResponse) => { if (error) return cb(error); //assign network name to deployment entry oneDeployment.options.network = name; //check if network is ready then update firewall rules checkVpcNetwork(globalOperationResponse, mCb); }); function checkVpcNetwork(globalOperationResponse, mCb) { function globalOperations(miniCB) { options.soajs.log.debug("Checking network Create Status"); //Ref https://cloud.google.com/compute/docs/reference/latest/globalOperations/get let request = getConnector(options.infra.api); delete request.projectId; request.operation = globalOperationResponse.name; v1Compute().globalOperations.get(request, (error, response) => { if (error) { return miniCB(error); } if (!response || response.status !== "DONE") { setTimeout(function () { globalOperations(miniCB); }, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5000); } else { return miniCB(null, response); } }); } globalOperations(function (err) { if (err) { return mCb(err); } else { //Ref: https://cloud.google.com/compute/docs/reference/latest/firewalls/insert let firewallRules = getFirewallRules(oneDeployment.options.network); let request = getConnector(options.infra.api); async.eachSeries(firewallRules, (oneRule, vCb) => { options.soajs.log.debug("Registering new firewall rule:", oneRule.name); request.resource = oneRule; v1Compute().firewalls.insert(request, vCb); }, mCb); } }); } }
javascript
function createVpcNetwork(mCb) { let networksOptions = Object.assign({}, options); networksOptions.params = { name, returnGlobalOperation: true }; networks.add(networksOptions, (error, globalOperationResponse) => { if (error) return cb(error); //assign network name to deployment entry oneDeployment.options.network = name; //check if network is ready then update firewall rules checkVpcNetwork(globalOperationResponse, mCb); }); function checkVpcNetwork(globalOperationResponse, mCb) { function globalOperations(miniCB) { options.soajs.log.debug("Checking network Create Status"); //Ref https://cloud.google.com/compute/docs/reference/latest/globalOperations/get let request = getConnector(options.infra.api); delete request.projectId; request.operation = globalOperationResponse.name; v1Compute().globalOperations.get(request, (error, response) => { if (error) { return miniCB(error); } if (!response || response.status !== "DONE") { setTimeout(function () { globalOperations(miniCB); }, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5000); } else { return miniCB(null, response); } }); } globalOperations(function (err) { if (err) { return mCb(err); } else { //Ref: https://cloud.google.com/compute/docs/reference/latest/firewalls/insert let firewallRules = getFirewallRules(oneDeployment.options.network); let request = getConnector(options.infra.api); async.eachSeries(firewallRules, (oneRule, vCb) => { options.soajs.log.debug("Registering new firewall rule:", oneRule.name); request.resource = oneRule; v1Compute().firewalls.insert(request, vCb); }, mCb); } }); } }
[ "function", "createVpcNetwork", "(", "mCb", ")", "{", "let", "networksOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "networksOptions", ".", "params", "=", "{", "name", ",", "returnGlobalOperation", ":", "true", "}", ";", ...
method used to create a google vpc network @returns {*}
[ "method", "used", "to", "create", "a", "google", "vpc", "network" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L95-L150
31,515
soajs/soajs.core.drivers
infra/google/kubernetes/index.js
useVpcNetwork
function useVpcNetwork(mCb) { //assign network name to deployment entry oneDeployment.options.network = name; function patchFirewall() { let firewallRules = getFirewallRules(oneDeployment.options.network); let request = getConnector(options.infra.api); request.filter = `network eq .*${oneDeployment.options.network}`; request.project = options.infra.api.project; //list firewalls //Ref: https://cloud.google.com/compute/docs/reference/rest/v1/firewalls/list v1Compute().firewalls.list(request, function (error, firewalls) { if (error) return mCb(error); if (!firewalls.items) firewalls.items = []; async.eachSeries(firewallRules, (oneRule, vCb) => { let foundFirewall = firewalls.items.find((oneEntry) => { return oneEntry.name === oneRule.name }); if (foundFirewall) { options.soajs.log.debug("Firewall rule:", oneRule.name, "already exists, skipping"); return vCb(); } else { options.soajs.log.debug("Creating firewall rule:", oneRule.name); request.resource = oneRule; return v1Compute().firewalls.insert(request, vCb); } }, mCb); }); } patchFirewall(); }
javascript
function useVpcNetwork(mCb) { //assign network name to deployment entry oneDeployment.options.network = name; function patchFirewall() { let firewallRules = getFirewallRules(oneDeployment.options.network); let request = getConnector(options.infra.api); request.filter = `network eq .*${oneDeployment.options.network}`; request.project = options.infra.api.project; //list firewalls //Ref: https://cloud.google.com/compute/docs/reference/rest/v1/firewalls/list v1Compute().firewalls.list(request, function (error, firewalls) { if (error) return mCb(error); if (!firewalls.items) firewalls.items = []; async.eachSeries(firewallRules, (oneRule, vCb) => { let foundFirewall = firewalls.items.find((oneEntry) => { return oneEntry.name === oneRule.name }); if (foundFirewall) { options.soajs.log.debug("Firewall rule:", oneRule.name, "already exists, skipping"); return vCb(); } else { options.soajs.log.debug("Creating firewall rule:", oneRule.name); request.resource = oneRule; return v1Compute().firewalls.insert(request, vCb); } }, mCb); }); } patchFirewall(); }
[ "function", "useVpcNetwork", "(", "mCb", ")", "{", "//assign network name to deployment entry", "oneDeployment", ".", "options", ".", "network", "=", "name", ";", "function", "patchFirewall", "(", ")", "{", "let", "firewallRules", "=", "getFirewallRules", "(", "oneD...
method used to use an existing google vpc network @returns {*}
[ "method", "used", "to", "use", "an", "existing", "google", "vpc", "network" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L156-L192
31,516
soajs/soajs.core.drivers
infra/google/kubernetes/index.js
getClusterVersion
function getClusterVersion(request, mCb) { delete request.project; v1Container().projects.zones.getServerconfig(request, function (err, response) { if (err) { return mCb(err); } let version; if (response && response.validMasterVersions && Array.isArray(response.validMasterVersions) && response.validMasterVersions.length > 0) { response.validMasterVersions.forEach(function (oneVersion) { if (oneVersion.substring(0, 3) === "1.7") { version = oneVersion; options.soajs.log.debug("Initial Cluster version set to :", version); } }); } else if (response && response.defaultClusterVersion && !version) { version = response.defaultClusterVersion; options.soajs.log.debug("Initial Cluster version set to default version :", version); } else { return mCb({"code": 410, "msg": "Invalid or no kubernetes cluster version found!"}) } return mCb(null, version); }); }
javascript
function getClusterVersion(request, mCb) { delete request.project; v1Container().projects.zones.getServerconfig(request, function (err, response) { if (err) { return mCb(err); } let version; if (response && response.validMasterVersions && Array.isArray(response.validMasterVersions) && response.validMasterVersions.length > 0) { response.validMasterVersions.forEach(function (oneVersion) { if (oneVersion.substring(0, 3) === "1.7") { version = oneVersion; options.soajs.log.debug("Initial Cluster version set to :", version); } }); } else if (response && response.defaultClusterVersion && !version) { version = response.defaultClusterVersion; options.soajs.log.debug("Initial Cluster version set to default version :", version); } else { return mCb({"code": 410, "msg": "Invalid or no kubernetes cluster version found!"}) } return mCb(null, version); }); }
[ "function", "getClusterVersion", "(", "request", ",", "mCb", ")", "{", "delete", "request", ".", "project", ";", "v1Container", "(", ")", ".", "projects", ".", "zones", ".", "getServerconfig", "(", "request", ",", "function", "(", "err", ",", "response", "...
method used to get cluster version @returns {*}
[ "method", "used", "to", "get", "cluster", "version" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L292-L316
31,517
soajs/soajs.core.drivers
infra/google/kubernetes/index.js
deleteNetwork
function deleteNetwork() { setTimeout(function () { //cluster failed, delete network if it was not provided by the user let networksOptions = Object.assign({}, options); networksOptions.params = {name: oneDeployment.options.network}; networks.delete(networksOptions, (error) => { if (error) { options.soajs.log.error(error); } else { options.soajs.log.debug("VPC Network Deleted Successfully."); } }); }, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5 * 60 * 1000); }
javascript
function deleteNetwork() { setTimeout(function () { //cluster failed, delete network if it was not provided by the user let networksOptions = Object.assign({}, options); networksOptions.params = {name: oneDeployment.options.network}; networks.delete(networksOptions, (error) => { if (error) { options.soajs.log.error(error); } else { options.soajs.log.debug("VPC Network Deleted Successfully."); } }); }, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5 * 60 * 1000); }
[ "function", "deleteNetwork", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "//cluster failed, delete network if it was not provided by the user", "let", "networksOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "network...
delete vpc Network after a certain timeout @returns {*}
[ "delete", "vpc", "Network", "after", "a", "certain", "timeout" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L322-L335
31,518
soajs/soajs.core.drivers
infra/google/kubernetes/index.js
function (options, region, verbose, mCb) { infraExtras.getRegion(options, region, verbose, (err, resR) => { if (err) { infraExtras.getZone(options, region, verbose, (err, resZ) => { if (err) { return mCb(err); } else { return mCb(null, resZ); } }); } else { return mCb(null, resR); } }); }
javascript
function (options, region, verbose, mCb) { infraExtras.getRegion(options, region, verbose, (err, resR) => { if (err) { infraExtras.getZone(options, region, verbose, (err, resZ) => { if (err) { return mCb(err); } else { return mCb(null, resZ); } }); } else { return mCb(null, resR); } }); }
[ "function", "(", "options", ",", "region", ",", "verbose", ",", "mCb", ")", "{", "infraExtras", ".", "getRegion", "(", "options", ",", "region", ",", "verbose", ",", "(", "err", ",", "resR", ")", "=>", "{", "if", "(", "err", ")", "{", "infraExtras", ...
This method checks tif the cluster is zonal or regional @param options @param region @param verbose @param mCb @returns {*}
[ "This", "method", "checks", "tif", "the", "cluster", "is", "zonal", "or", "regional" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L466-L480
31,519
soajs/soajs.core.drivers
infra/google/kubernetes/index.js
function (options, cb) { //call google api and get the machines let cluster = options.infra.stack; //Ref: https://cloud.google.com/compute/docs/reference/latest/instances/list let request = getConnector(options.infra.api); request.clusterId = cluster.id; request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*"; let response = { "env": options.soajs.registry.code, "stackId": cluster.id, "stackName": cluster.id, "templateProperties": { "region": cluster.options.zone //"keyPair": "keyPair" //todo: what is this for ???? }, "machines": [], }; driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => { if (err) { return cb(err) } //loop over all the zone ang get the ip of each location found in the zone //if zonal we only have to loop once async.each(zones, function (oneZone, callback) { request.zone = oneZone; v1Compute().instances.list(request, (error, instances) => { if (error) { return callback(error); } if (instances && instances.items) { //extract name and ip from response instances.items.forEach((oneInstance) => { let machineIP; oneInstance.networkInterfaces.forEach((oneNetInterface) => { if (oneNetInterface.accessConfigs) { oneNetInterface.accessConfigs.forEach((oneAC) => { if (oneAC.name === 'external-nat') { machineIP = oneAC.natIP; } }); } }); if (machineIP) { response.machines.push({ "name": oneInstance.name, "ip": machineIP, "zone": oneZone }); } }); } callback(); }); }, function (err) { if (err) { return cb(err) } else { return cb(null, response); } }); }); }
javascript
function (options, cb) { //call google api and get the machines let cluster = options.infra.stack; //Ref: https://cloud.google.com/compute/docs/reference/latest/instances/list let request = getConnector(options.infra.api); request.clusterId = cluster.id; request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*"; let response = { "env": options.soajs.registry.code, "stackId": cluster.id, "stackName": cluster.id, "templateProperties": { "region": cluster.options.zone //"keyPair": "keyPair" //todo: what is this for ???? }, "machines": [], }; driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => { if (err) { return cb(err) } //loop over all the zone ang get the ip of each location found in the zone //if zonal we only have to loop once async.each(zones, function (oneZone, callback) { request.zone = oneZone; v1Compute().instances.list(request, (error, instances) => { if (error) { return callback(error); } if (instances && instances.items) { //extract name and ip from response instances.items.forEach((oneInstance) => { let machineIP; oneInstance.networkInterfaces.forEach((oneNetInterface) => { if (oneNetInterface.accessConfigs) { oneNetInterface.accessConfigs.forEach((oneAC) => { if (oneAC.name === 'external-nat') { machineIP = oneAC.natIP; } }); } }); if (machineIP) { response.machines.push({ "name": oneInstance.name, "ip": machineIP, "zone": oneZone }); } }); } callback(); }); }, function (err) { if (err) { return cb(err) } else { return cb(null, response); } }); }); }
[ "function", "(", "options", ",", "cb", ")", "{", "//call google api and get the machines", "let", "cluster", "=", "options", ".", "infra", ".", "stack", ";", "//Ref: https://cloud.google.com/compute/docs/reference/latest/instances/list", "let", "request", "=", "getConnector...
This method returns the project cluster id and zone that was used to create a deployment at the google. @param options @param cb
[ "This", "method", "returns", "the", "project", "cluster", "id", "and", "zone", "that", "was", "used", "to", "create", "a", "deployment", "at", "the", "google", "." ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/google/kubernetes/index.js#L1020-L1084
31,520
soajs/soajs.core.drivers
infra/aws/index.js
function (options, cb) { options.soajs.log.debug("Checking if Cluster is healthy ..."); let stack = options.infra.stack; let containerOptions = Object.assign({}, options); containerOptions.technology = (containerOptions && containerOptions.params && containerOptions.params.technology) ? containerOptions.params.technology : defaultDriver; //get the environment record if (options.soajs.registry.deployer.container[stack.technology].remote.nodes && options.soajs.registry.deployer.container[stack.technology].remote.nodes !== '') { let machineIp = options.soajs.registry.deployer.container[stack.technology].remote.nodes; return cb(null, machineIp); } else { let out = false; async.series({ "pre": (mCb) => { runCorrespondingDriver('getDeployClusterStatusPre', containerOptions, mCb); }, "exec": (mCb) => { ClusterDriver.getDeployClusterStatus(options, (error, response) => { if (response) { out = response; containerOptions.out = out; } return mCb(error, response); }); }, "post": (mCb) => { if (out) { runCorrespondingDriver('getDeployClusterStatusPost', containerOptions, mCb); } else { return mCb(); } } }, (error) => { return cb(error, out); }); } }
javascript
function (options, cb) { options.soajs.log.debug("Checking if Cluster is healthy ..."); let stack = options.infra.stack; let containerOptions = Object.assign({}, options); containerOptions.technology = (containerOptions && containerOptions.params && containerOptions.params.technology) ? containerOptions.params.technology : defaultDriver; //get the environment record if (options.soajs.registry.deployer.container[stack.technology].remote.nodes && options.soajs.registry.deployer.container[stack.technology].remote.nodes !== '') { let machineIp = options.soajs.registry.deployer.container[stack.technology].remote.nodes; return cb(null, machineIp); } else { let out = false; async.series({ "pre": (mCb) => { runCorrespondingDriver('getDeployClusterStatusPre', containerOptions, mCb); }, "exec": (mCb) => { ClusterDriver.getDeployClusterStatus(options, (error, response) => { if (response) { out = response; containerOptions.out = out; } return mCb(error, response); }); }, "post": (mCb) => { if (out) { runCorrespondingDriver('getDeployClusterStatusPost', containerOptions, mCb); } else { return mCb(); } } }, (error) => { return cb(error, out); }); } }
[ "function", "(", "options", ",", "cb", ")", "{", "options", ".", "soajs", ".", "log", ".", "debug", "(", "\"Checking if Cluster is healthy ...\"", ")", ";", "let", "stack", "=", "options", ".", "infra", ".", "stack", ";", "let", "containerOptions", "=", "O...
This method takes the id of the stack as an input and check if the stack has been deployed it returns the ip that can be used to access the machine @param options @param cb @returns {*}
[ "This", "method", "takes", "the", "id", "of", "the", "stack", "as", "an", "input", "and", "check", "if", "the", "stack", "has", "been", "deployed", "it", "returns", "the", "ip", "that", "can", "be", "used", "to", "access", "the", "machine" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/index.js#L74-L113
31,521
digitalbazaar/http-signature-middleware
lib/Middleware.js
_timestampBeforeNow
function _timestampBeforeNow(timestamp) { if(!(typeof timestamp === 'string' && dateRegEx.test(timestamp))) { throw new TypeError('`revoked` timestamp must be a string.'); } const now = new Date(); const tsDate = new Date(timestamp); return tsDate < now; }
javascript
function _timestampBeforeNow(timestamp) { if(!(typeof timestamp === 'string' && dateRegEx.test(timestamp))) { throw new TypeError('`revoked` timestamp must be a string.'); } const now = new Date(); const tsDate = new Date(timestamp); return tsDate < now; }
[ "function", "_timestampBeforeNow", "(", "timestamp", ")", "{", "if", "(", "!", "(", "typeof", "timestamp", "===", "'string'", "&&", "dateRegEx", ".", "test", "(", "timestamp", ")", ")", ")", "{", "throw", "new", "TypeError", "(", "'`revoked` timestamp must be ...
returns true if the given timestamp is before the current time
[ "returns", "true", "if", "the", "given", "timestamp", "is", "before", "the", "current", "time" ]
993b7d4f19d73b4fe79a0b4e4f5dc850316195de
https://github.com/digitalbazaar/http-signature-middleware/blob/993b7d4f19d73b4fe79a0b4e4f5dc850316195de/lib/Middleware.js#L155-L162
31,522
Incroud/cassanova
index.js
Cassanova
function Cassanova(){ this.tables = {}; this.models = {}; this.schemas = {}; this.client = null; this.options = null; EventEmitter.call(this); }
javascript
function Cassanova(){ this.tables = {}; this.models = {}; this.schemas = {}; this.client = null; this.options = null; EventEmitter.call(this); }
[ "function", "Cassanova", "(", ")", "{", "this", ".", "tables", "=", "{", "}", ";", "this", ".", "models", "=", "{", "}", ";", "this", ".", "schemas", "=", "{", "}", ";", "this", ".", "client", "=", "null", ";", "this", ".", "options", "=", "nul...
Cassanova. An object modeler for Cassandra CQL built upon the node-cassandra-cql driver.
[ "Cassanova", ".", "An", "object", "modeler", "for", "Cassandra", "CQL", "built", "upon", "the", "node", "-", "cassandra", "-", "cql", "driver", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/index.js#L15-L23
31,523
Incroud/cassanova
CQL.js
function(callback){ var filePath; output("Processing arguments..."); if(program.cql){ batchQueries.push(program.cql.toString().trim()); } if((!program.keyspace || program.keyspace.length === 0)){ output("A keyspace has not been defined. CQL will fail if the keyspace is not defined in the statement."); } if((!program.files || program.files.length === 0) && (!program.cql || program.cql.length === 0)){ return callback("Need a file to load or cql to run. Use -f=filename or --files=filename,filename or -cql='someCQLStatement;' or --cql='someCQLStatement;'. Run node CQL --help for mode information.", false); }else if(process.env.NODE_ENV === 'production' && !program.production){ return callback("CQL cannot be run while the NODE_ENV is set to production.", false); }else if(program.production && process.env.NODE_ENV === 'production'){ output("***** Preparing to run scripts in production mode *****"); output("***** You have " + productionRunDelay + " seconds to think about what your doing before the scripts will execute. *****"); output("***** CTRL+C to Exit *****"); barTimer = setInterval(function () { bar.tick(); if (bar.complete) { output("***** OK! Here we go... *****"); output("***** Running scripts in production mode *****"); clearInterval(barTimer); return callback(null, true); } }, 1000); return; }else if(program.production && process.env.NODE_ENV !== 'production'){ return callback("NODE_ENV is set not set to production, but you attempted to run in production mode.", false); } callback(null, true); }
javascript
function(callback){ var filePath; output("Processing arguments..."); if(program.cql){ batchQueries.push(program.cql.toString().trim()); } if((!program.keyspace || program.keyspace.length === 0)){ output("A keyspace has not been defined. CQL will fail if the keyspace is not defined in the statement."); } if((!program.files || program.files.length === 0) && (!program.cql || program.cql.length === 0)){ return callback("Need a file to load or cql to run. Use -f=filename or --files=filename,filename or -cql='someCQLStatement;' or --cql='someCQLStatement;'. Run node CQL --help for mode information.", false); }else if(process.env.NODE_ENV === 'production' && !program.production){ return callback("CQL cannot be run while the NODE_ENV is set to production.", false); }else if(program.production && process.env.NODE_ENV === 'production'){ output("***** Preparing to run scripts in production mode *****"); output("***** You have " + productionRunDelay + " seconds to think about what your doing before the scripts will execute. *****"); output("***** CTRL+C to Exit *****"); barTimer = setInterval(function () { bar.tick(); if (bar.complete) { output("***** OK! Here we go... *****"); output("***** Running scripts in production mode *****"); clearInterval(barTimer); return callback(null, true); } }, 1000); return; }else if(program.production && process.env.NODE_ENV !== 'production'){ return callback("NODE_ENV is set not set to production, but you attempted to run in production mode.", false); } callback(null, true); }
[ "function", "(", "callback", ")", "{", "var", "filePath", ";", "output", "(", "\"Processing arguments...\"", ")", ";", "if", "(", "program", ".", "cql", ")", "{", "batchQueries", ".", "push", "(", "program", ".", "cql", ".", "toString", "(", ")", ".", ...
Verifies the arguments are valid and ant require arguments are handled. @param {Function} callback Callback to async with error or success
[ "Verifies", "the", "arguments", "are", "valid", "and", "ant", "require", "arguments", "are", "handled", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L61-L100
31,524
Incroud/cassanova
CQL.js
function(callback){ var opts = {}; output("Connecting to database..."); //We need to be able to do anything with any keyspace. We just need a db connection. Just send //in the hosts, username and password, stripping the keyspace. opts.username = process.env.CASS_USER || config.db.username; opts.password = process.env.CASS_PASS || config.db.password; opts.hosts = config.db.hosts; opts.port = config.db.port; Cassanova.connect(opts, function(err, result){ if(err){ err.hosts = opts.hosts; } callback(err, result); }); }
javascript
function(callback){ var opts = {}; output("Connecting to database..."); //We need to be able to do anything with any keyspace. We just need a db connection. Just send //in the hosts, username and password, stripping the keyspace. opts.username = process.env.CASS_USER || config.db.username; opts.password = process.env.CASS_PASS || config.db.password; opts.hosts = config.db.hosts; opts.port = config.db.port; Cassanova.connect(opts, function(err, result){ if(err){ err.hosts = opts.hosts; } callback(err, result); }); }
[ "function", "(", "callback", ")", "{", "var", "opts", "=", "{", "}", ";", "output", "(", "\"Connecting to database...\"", ")", ";", "//We need to be able to do anything with any keyspace. We just need a db connection. Just send", "//in the hosts, username and password, stripping th...
Starts Cassanova. @param {Function} callback Callback to async with error or success
[ "Starts", "Cassanova", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L137-L153
31,525
Incroud/cassanova
CQL.js
function(callback){ var result, i; if(!files || files.length === 0){ return callback(null, true); } output("Processing queries..."); for(i=0; i<files.length; i++){ while((result = cqlRegex.exec(files[i])) !== null) { batchQueries.push(result[1].replace(/\s+/g, ' ').trim()); } } callback(null, true); }
javascript
function(callback){ var result, i; if(!files || files.length === 0){ return callback(null, true); } output("Processing queries..."); for(i=0; i<files.length; i++){ while((result = cqlRegex.exec(files[i])) !== null) { batchQueries.push(result[1].replace(/\s+/g, ' ').trim()); } } callback(null, true); }
[ "function", "(", "callback", ")", "{", "var", "result", ",", "i", ";", "if", "(", "!", "files", "||", "files", ".", "length", "===", "0", ")", "{", "return", "callback", "(", "null", ",", "true", ")", ";", "}", "output", "(", "\"Processing queries......
Processes the queries from the files loaded and builds the batch of individual statements to run. @param {Function} callback Callback to async with error or success
[ "Processes", "the", "queries", "from", "the", "files", "loaded", "and", "builds", "the", "batch", "of", "individual", "statements", "to", "run", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L159-L176
31,526
Incroud/cassanova
CQL.js
function(callback){ output("Initializing queries..."); if(program.keyspace){ batchQueries.unshift("USE " + program.keyspace + ";"); } if(batchQueries && batchQueries.length > 0){ output("Running queries..."); executeQuery(batchQueries.shift(), callback); }else{ callback("No queries to run.", null); } }
javascript
function(callback){ output("Initializing queries..."); if(program.keyspace){ batchQueries.unshift("USE " + program.keyspace + ";"); } if(batchQueries && batchQueries.length > 0){ output("Running queries..."); executeQuery(batchQueries.shift(), callback); }else{ callback("No queries to run.", null); } }
[ "function", "(", "callback", ")", "{", "output", "(", "\"Initializing queries...\"", ")", ";", "if", "(", "program", ".", "keyspace", ")", "{", "batchQueries", ".", "unshift", "(", "\"USE \"", "+", "program", ".", "keyspace", "+", "\";\"", ")", ";", "}", ...
Initializes the query batch to execute. @param {Function} callback Callback to async with error or success
[ "Initializes", "the", "query", "batch", "to", "execute", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L182-L196
31,527
Incroud/cassanova
CQL.js
function(eQuery, callback){ output("Executing:\t\t" + eQuery); Cassanova.execute(eQuery, function(err) { if (err){ return callback(err, null); } else { if(batchQueries.length > 0){ executeQuery(batchQueries.shift(), callback); }else{ callback(null, true); process.nextTick(function(){ process.exit(1); }); } } }); }
javascript
function(eQuery, callback){ output("Executing:\t\t" + eQuery); Cassanova.execute(eQuery, function(err) { if (err){ return callback(err, null); } else { if(batchQueries.length > 0){ executeQuery(batchQueries.shift(), callback); }else{ callback(null, true); process.nextTick(function(){ process.exit(1); }); } } }); }
[ "function", "(", "eQuery", ",", "callback", ")", "{", "output", "(", "\"Executing:\\t\\t\"", "+", "eQuery", ")", ";", "Cassanova", ".", "execute", "(", "eQuery", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "...
A recursive method, that executes each query. @param {String} eQuery The cql string to be executed. @param {Function} callback Callback to async with error or success
[ "A", "recursive", "method", "that", "executes", "each", "query", "." ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/CQL.js#L203-L222
31,528
pex-gl/pex-sys
Event.js
Event
function Event(type, data){ this._sender = null; this._type = type; this._data = data; for(var prop in data) { this[prop] = data[prop]; } this._stopPropagation = false; }
javascript
function Event(type, data){ this._sender = null; this._type = type; this._data = data; for(var prop in data) { this[prop] = data[prop]; } this._stopPropagation = false; }
[ "function", "Event", "(", "type", ",", "data", ")", "{", "this", ".", "_sender", "=", "null", ";", "this", ".", "_type", "=", "type", ";", "this", ".", "_data", "=", "data", ";", "for", "(", "var", "prop", "in", "data", ")", "{", "this", "[", "...
Base Event class. @param {String} type - The type @param {Object} [data] - The data @constructor @class
[ "Base", "Event", "class", "." ]
1a2f4f01b6ce5966aee42716355e2888159501dd
https://github.com/pex-gl/pex-sys/blob/1a2f4f01b6ce5966aee42716355e2888159501dd/Event.js#L8-L18
31,529
soajs/soajs.core.drivers
Gruntfile.js
function () { var cwd = process.cwd(); var rootPath = cwd; var newRootPath = null; while (!fs.existsSync(path.join(process.cwd(), "node_modules/grunt"))) { process.chdir(".."); newRootPath = process.cwd(); if (newRootPath === rootPath) { return; } rootPath = newRootPath; } process.chdir(cwd); return rootPath; }
javascript
function () { var cwd = process.cwd(); var rootPath = cwd; var newRootPath = null; while (!fs.existsSync(path.join(process.cwd(), "node_modules/grunt"))) { process.chdir(".."); newRootPath = process.cwd(); if (newRootPath === rootPath) { return; } rootPath = newRootPath; } process.chdir(cwd); return rootPath; }
[ "function", "(", ")", "{", "var", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "var", "rootPath", "=", "cwd", ";", "var", "newRootPath", "=", "null", ";", "while", "(", "!", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "process", ...
Function that find the root path where grunt plugins are installed. @method findRoot @return String rootPath
[ "Function", "that", "find", "the", "root", "path", "where", "grunt", "plugins", "are", "installed", "." ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/Gruntfile.js#L14-L28
31,530
soajs/soajs.core.drivers
Gruntfile.js
function (grunt, rootPath, tasks) { tasks.forEach(function (name) { if (name === 'grunt-cli') return; var cwd = process.cwd(); process.chdir(rootPath); // load files from proper root, I don't want to install everything locally per module! grunt.loadNpmTasks(name); process.chdir(cwd); }); }
javascript
function (grunt, rootPath, tasks) { tasks.forEach(function (name) { if (name === 'grunt-cli') return; var cwd = process.cwd(); process.chdir(rootPath); // load files from proper root, I don't want to install everything locally per module! grunt.loadNpmTasks(name); process.chdir(cwd); }); }
[ "function", "(", "grunt", ",", "rootPath", ",", "tasks", ")", "{", "tasks", ".", "forEach", "(", "function", "(", "name", ")", "{", "if", "(", "name", "===", "'grunt-cli'", ")", "return", ";", "var", "cwd", "=", "process", ".", "cwd", "(", ")", ";"...
Function load the npm tasks from the root path @method loadTasks @param grunt {Object} The grunt instance @param tasks {Array} Array of tasks as string
[ "Function", "load", "the", "npm", "tasks", "from", "the", "root", "path" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/Gruntfile.js#L36-L44
31,531
SonoIo/node-eve
lib/build.js
function (next) { minify( outputCommonsJsFile, _.extend({optimize: true},uglifyOptions), function(err){ if ( err ){ return next(err); } return next(); } ); }
javascript
function (next) { minify( outputCommonsJsFile, _.extend({optimize: true},uglifyOptions), function(err){ if ( err ){ return next(err); } return next(); } ); }
[ "function", "(", "next", ")", "{", "minify", "(", "outputCommonsJsFile", ",", "_", ".", "extend", "(", "{", "optimize", ":", "true", "}", ",", "uglifyOptions", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "next", ...
Minify commons components
[ "Minify", "commons", "components" ]
6b7cefecdcf425f30e888ede9e71908850b5447d
https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L347-L360
31,532
SonoIo/node-eve
lib/build.js
function (next) { minify( outputJsFile, _.extend({optimize: true},uglifyOptions), function(err){ if ( err ){ return next(err); } if ( isForPublish ){ publisher( outputJsFile, function (err) { return next(err); }, options.forceminified ); }else { return next(); } } ); }
javascript
function (next) { minify( outputJsFile, _.extend({optimize: true},uglifyOptions), function(err){ if ( err ){ return next(err); } if ( isForPublish ){ publisher( outputJsFile, function (err) { return next(err); }, options.forceminified ); }else { return next(); } } ); }
[ "function", "(", "next", ")", "{", "minify", "(", "outputJsFile", ",", "_", ".", "extend", "(", "{", "optimize", ":", "true", "}", ",", "uglifyOptions", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", ...
Minify bundle app
[ "Minify", "bundle", "app" ]
6b7cefecdcf425f30e888ede9e71908850b5447d
https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L362-L387
31,533
SonoIo/node-eve
lib/build.js
function (next) { for (var i = 0; i < mapFiles.length; i++) { fs.unlinkSync(mapFiles[i]); // console.log( path.resolve(mapFiles[i]) ); } return next(); }
javascript
function (next) { for (var i = 0; i < mapFiles.length; i++) { fs.unlinkSync(mapFiles[i]); // console.log( path.resolve(mapFiles[i]) ); } return next(); }
[ "function", "(", "next", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "mapFiles", ".", "length", ";", "i", "++", ")", "{", "fs", ".", "unlinkSync", "(", "mapFiles", "[", "i", "]", ")", ";", "// console.log( path.resolve(mapFiles[i]) );", ...
Remove source map files
[ "Remove", "source", "map", "files" ]
6b7cefecdcf425f30e888ede9e71908850b5447d
https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L389-L395
31,534
SonoIo/node-eve
lib/build.js
minify
function minify( file, options, done ){ if (_.isFunction(options)){ done = options; options = {}; } if (!_.isObject(options)) options = {}; if (!_.isFunction(done)) done = function(){}; const canOptimize = options.optimize; delete options.optimize; console.log(" minify file %s...".grey, file); try { var code = fs.readFileSync( file, {encoding: 'utf8'} ); var minify = UglifyJS.minify( code, options ); } catch (e) { return done( new Error(`Error on parse file ${e.filename}`) ); } if ( !minify || minify.error ) { if ( minify && minify.error ) return done( new Error(minify.error.message) ); return done(new Error('Minify error bundle.js') ); } try{ if ( canOptimize ){ console.log(" optimize file %s...".grey, file ); code = optimizeJs(minify.code); }else{ code = minify.code; } }catch(e){ console.error("Error on parse file %s", e.filename); return next(e); } fs.writeFile( file, code, function (err) { if ( err ) return done(err); return done(); } ); }
javascript
function minify( file, options, done ){ if (_.isFunction(options)){ done = options; options = {}; } if (!_.isObject(options)) options = {}; if (!_.isFunction(done)) done = function(){}; const canOptimize = options.optimize; delete options.optimize; console.log(" minify file %s...".grey, file); try { var code = fs.readFileSync( file, {encoding: 'utf8'} ); var minify = UglifyJS.minify( code, options ); } catch (e) { return done( new Error(`Error on parse file ${e.filename}`) ); } if ( !minify || minify.error ) { if ( minify && minify.error ) return done( new Error(minify.error.message) ); return done(new Error('Minify error bundle.js') ); } try{ if ( canOptimize ){ console.log(" optimize file %s...".grey, file ); code = optimizeJs(minify.code); }else{ code = minify.code; } }catch(e){ console.error("Error on parse file %s", e.filename); return next(e); } fs.writeFile( file, code, function (err) { if ( err ) return done(err); return done(); } ); }
[ "function", "minify", "(", "file", ",", "options", ",", "done", ")", "{", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "done", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "!", "_", ".", "isObject", "...
End bundle Function for minified
[ "End", "bundle", "Function", "for", "minified" ]
6b7cefecdcf425f30e888ede9e71908850b5447d
https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L427-L477
31,535
SonoIo/node-eve
lib/build.js
publisher
function publisher(outputJsFile, done, forceMinified){ // Check if JSCrambler configs file exist const time = process.hrtime(); const jscramblerConfigs = path.resolve('jscrambler.json'); fs.stat( jscramblerConfigs, function (err) { if ( err ){ let newTime = console.log(' obfuscating code with jScrambler was not executed, because the configs file `jscrambler.json` is not present into project\'s directory.'.yellow); console.log('Publication finished!'.gray); // +beautifyTime( process.hrtime(time) ).green + '\u0007' return done(err); } console.log(' obfuscating code with jScrambler...'.gray); try { var configs = require(jscramblerConfigs); } catch (e) { return done(' Error on obfuscation! The file configs is not a valid JSON'.red); } if ( !_.isObject(configs.keys) || _.isEmpty(configs.keys.accessKey) || _.isEmpty(configs.keys.secretKey) || _.isEmpty(configs.applicationId) ){ return done( new Error(' Error on obfuscation! Jcrambler\'s configs missed. Ex.: accessKey, secretKey or applicationId.') ); } // Set the file for obfuscation if ( !_.isArray(configs.filesSrc) ) configs.filesSrc = []; if ( configs.filesSrc.indexOf(outputJsFile) == -1 ) configs.filesSrc.push(outputJsFile); configs.filesDest = path.dirname( packageJSONFile ); // The project's dirname /* { keys: { accessKey: 'YOUR_JSCRAMBLER_ACCESS_KEY', secretKey: 'YOUR_JSCRAMBLER_SECRET_KEY' }, host: 'api4.jscrambler.com', port: 443, applicationId: 'YOUR_APPLICATION_ID', filesSrc: [ '/path/to/src/*.html', '/path/to/src/*.js' ], filesDest: '/path/to/destDir/', params: { stringSplitting: { chunk: 1 } } } */ const symbolTable = path.join( configs.filesDest, "symbolTable.json"); jscrambler .protectAndDownload(configs) .then(function () { try{ const st = fs.statSync( symbolTable ); fs.unlinkSync(symbolTable); }catch(e){} if ( !forceMinified ){ console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007'); return done(); } minify(outputJsFile,{},function(err){ if (err){ return done(err); } console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007'); return done(); }); }) .catch(function (err) { let message = ' Error on obfuscation! Error while obfuscating the code with jScrambler'; if ( err && err.message ) message = ` Error on obfuscation! jScrambler: ${err.message}`; done( new Error(message) ); }); }); }
javascript
function publisher(outputJsFile, done, forceMinified){ // Check if JSCrambler configs file exist const time = process.hrtime(); const jscramblerConfigs = path.resolve('jscrambler.json'); fs.stat( jscramblerConfigs, function (err) { if ( err ){ let newTime = console.log(' obfuscating code with jScrambler was not executed, because the configs file `jscrambler.json` is not present into project\'s directory.'.yellow); console.log('Publication finished!'.gray); // +beautifyTime( process.hrtime(time) ).green + '\u0007' return done(err); } console.log(' obfuscating code with jScrambler...'.gray); try { var configs = require(jscramblerConfigs); } catch (e) { return done(' Error on obfuscation! The file configs is not a valid JSON'.red); } if ( !_.isObject(configs.keys) || _.isEmpty(configs.keys.accessKey) || _.isEmpty(configs.keys.secretKey) || _.isEmpty(configs.applicationId) ){ return done( new Error(' Error on obfuscation! Jcrambler\'s configs missed. Ex.: accessKey, secretKey or applicationId.') ); } // Set the file for obfuscation if ( !_.isArray(configs.filesSrc) ) configs.filesSrc = []; if ( configs.filesSrc.indexOf(outputJsFile) == -1 ) configs.filesSrc.push(outputJsFile); configs.filesDest = path.dirname( packageJSONFile ); // The project's dirname /* { keys: { accessKey: 'YOUR_JSCRAMBLER_ACCESS_KEY', secretKey: 'YOUR_JSCRAMBLER_SECRET_KEY' }, host: 'api4.jscrambler.com', port: 443, applicationId: 'YOUR_APPLICATION_ID', filesSrc: [ '/path/to/src/*.html', '/path/to/src/*.js' ], filesDest: '/path/to/destDir/', params: { stringSplitting: { chunk: 1 } } } */ const symbolTable = path.join( configs.filesDest, "symbolTable.json"); jscrambler .protectAndDownload(configs) .then(function () { try{ const st = fs.statSync( symbolTable ); fs.unlinkSync(symbolTable); }catch(e){} if ( !forceMinified ){ console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007'); return done(); } minify(outputJsFile,{},function(err){ if (err){ return done(err); } console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007'); return done(); }); }) .catch(function (err) { let message = ' Error on obfuscation! Error while obfuscating the code with jScrambler'; if ( err && err.message ) message = ` Error on obfuscation! jScrambler: ${err.message}`; done( new Error(message) ); }); }); }
[ "function", "publisher", "(", "outputJsFile", ",", "done", ",", "forceMinified", ")", "{", "// Check if JSCrambler configs file exist", "const", "time", "=", "process", ".", "hrtime", "(", ")", ";", "const", "jscramblerConfigs", "=", "path", ".", "resolve", "(", ...
Function for publisher and obfuscation method
[ "Function", "for", "publisher", "and", "obfuscation", "method" ]
6b7cefecdcf425f30e888ede9e71908850b5447d
https://github.com/SonoIo/node-eve/blob/6b7cefecdcf425f30e888ede9e71908850b5447d/lib/build.js#L481-L574
31,536
Pinoccio/client-node-pinoccio
lib/api.js
function(token,options){ options = options||{}; options.token = token; var obj = { type:"rest" ,args:{ url: '/v1/sync', data: options, method: 'get' } }; var s = through(); repipe(s,function(err,last,done){ o.log('repipe got error? ',err,' should i repipe?'); if(err && err.code != 'E_MDM') return done(err); getConnection(function(err,con){ if(err) return done(err); var dbstream = con.mdm.createReadStream(obj); var noendstream = dbstream.pipe(through(function(data){ this.queue(data); },function(){ if(options.tail || options.tail == undefined) { // repipe resumes the stream on error events! var error = new Error("never end bro!"); error.code = "E_MDM"; this.emit("error",error); } else { this.queue(null); } })); dbstream.on('error',function(err){ noendstream.emit("error",err) }); done(false,noendstream); }); }); s.on('data',function(d){ // on reconnect start sync from where i left off. obj.args.data.start = d.time; }) return s; }
javascript
function(token,options){ options = options||{}; options.token = token; var obj = { type:"rest" ,args:{ url: '/v1/sync', data: options, method: 'get' } }; var s = through(); repipe(s,function(err,last,done){ o.log('repipe got error? ',err,' should i repipe?'); if(err && err.code != 'E_MDM') return done(err); getConnection(function(err,con){ if(err) return done(err); var dbstream = con.mdm.createReadStream(obj); var noendstream = dbstream.pipe(through(function(data){ this.queue(data); },function(){ if(options.tail || options.tail == undefined) { // repipe resumes the stream on error events! var error = new Error("never end bro!"); error.code = "E_MDM"; this.emit("error",error); } else { this.queue(null); } })); dbstream.on('error',function(err){ noendstream.emit("error",err) }); done(false,noendstream); }); }); s.on('data',function(d){ // on reconnect start sync from where i left off. obj.args.data.start = d.time; }) return s; }
[ "function", "(", "token", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "token", "=", "token", ";", "var", "obj", "=", "{", "type", ":", "\"rest\"", ",", "args", ":", "{", "url", ":", "'/v1/sync'", ",", ...
sync the account's data in realtime
[ "sync", "the", "account", "s", "data", "in", "realtime" ]
9ee7b254639190a228dce6a4db9680f2c1bf1ca5
https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/api.js#L60-L110
31,537
Pinoccio/client-node-pinoccio
lib/api.js
function(token,o){ /* o.troop o.scout o.reports = [led,..] o.start = now o.end = then o.tail defaults true with no end */ o.token = token; var obj = { type:"rest" ,args:{ url: '/v1/stats', data: o, method: 'get' } }; var s = through(); repipe(s,function(err,last,done){ if(err && err.code != 'E_MDM') return done(err); if(last) o.start = last.key; getConnection(function(err,con){ if(err) return done(err); done(false,con.mdm.createReadStream(obj)); }); }); return s; // resume! }
javascript
function(token,o){ /* o.troop o.scout o.reports = [led,..] o.start = now o.end = then o.tail defaults true with no end */ o.token = token; var obj = { type:"rest" ,args:{ url: '/v1/stats', data: o, method: 'get' } }; var s = through(); repipe(s,function(err,last,done){ if(err && err.code != 'E_MDM') return done(err); if(last) o.start = last.key; getConnection(function(err,con){ if(err) return done(err); done(false,con.mdm.createReadStream(obj)); }); }); return s; // resume! }
[ "function", "(", "token", ",", "o", ")", "{", "/*\n o.troop\n o.scout\n o.reports = [led,..]\n o.start = now\n o.end = then\n o.tail defaults true with no end\n */", "o", ".", "token", "=", "token", ";", "var", "obj", "=", "{", "type...
stream stats data
[ "stream", "stats", "data" ]
9ee7b254639190a228dce6a4db9680f2c1bf1ca5
https://github.com/Pinoccio/client-node-pinoccio/blob/9ee7b254639190a228dce6a4db9680f2c1bf1ca5/lib/api.js#L112-L145
31,538
lddubeau/karma-typescript-agile-preprocessor
index.js
_serveFile
function _serveFile(requestedFile, done) { requestedFile.path = transformPath(requestedFile.path); log.debug(`Fetching ${requestedFile.path} from buffer`); // We get a requestedFile with an sha when Karma is watching files on // disk, and the file requested changed. When this happens, we need to // recompile the whole lot. if (requestedFile.sha) { delete requestedFile.sha; // Hack used to prevent infinite loop. enqueueForServing(requestedFile, done); // eslint-disable-next-line no-use-before-define compile(); return; } const normalized = _normalize(requestedFile.path); const compiled = compilationResults[normalized]; if (compiled) { delete compilationResults[normalized]; done(null, compiled.contents.toString()); return; } // If the file was not found in the stream, then maybe it is not compiled // or it is a definition file. log.debug(`${requestedFile.originalPath} was not found. Maybe it was \ not compiled or it is a definition file.`); done(null, dummyFile("This file was not compiled")); }
javascript
function _serveFile(requestedFile, done) { requestedFile.path = transformPath(requestedFile.path); log.debug(`Fetching ${requestedFile.path} from buffer`); // We get a requestedFile with an sha when Karma is watching files on // disk, and the file requested changed. When this happens, we need to // recompile the whole lot. if (requestedFile.sha) { delete requestedFile.sha; // Hack used to prevent infinite loop. enqueueForServing(requestedFile, done); // eslint-disable-next-line no-use-before-define compile(); return; } const normalized = _normalize(requestedFile.path); const compiled = compilationResults[normalized]; if (compiled) { delete compilationResults[normalized]; done(null, compiled.contents.toString()); return; } // If the file was not found in the stream, then maybe it is not compiled // or it is a definition file. log.debug(`${requestedFile.originalPath} was not found. Maybe it was \ not compiled or it is a definition file.`); done(null, dummyFile("This file was not compiled")); }
[ "function", "_serveFile", "(", "requestedFile", ",", "done", ")", "{", "requestedFile", ".", "path", "=", "transformPath", "(", "requestedFile", ".", "path", ")", ";", "log", ".", "debug", "(", "`", "${", "requestedFile", ".", "path", "}", "`", ")", ";",...
Used to fetch files from buffer.
[ "Used", "to", "fetch", "files", "from", "buffer", "." ]
c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba
https://github.com/lddubeau/karma-typescript-agile-preprocessor/blob/c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba/index.js#L80-L109
31,539
lddubeau/karma-typescript-agile-preprocessor
index.js
processServeQueue
function processServeQueue() { while (serveQueue.length) { const item = serveQueue.shift(); _serveFile(item.file, item.done); // It is possible start compiling while in release. if (state.compilationCompleted !== _currentState) { break; } } }
javascript
function processServeQueue() { while (serveQueue.length) { const item = serveQueue.shift(); _serveFile(item.file, item.done); // It is possible start compiling while in release. if (state.compilationCompleted !== _currentState) { break; } } }
[ "function", "processServeQueue", "(", ")", "{", "while", "(", "serveQueue", ".", "length", ")", "{", "const", "item", "=", "serveQueue", ".", "shift", "(", ")", ";", "_serveFile", "(", "item", ".", "file", ",", "item", ".", "done", ")", ";", "// It is ...
Responsible for flushing the cache and notifying karma.
[ "Responsible", "for", "flushing", "the", "cache", "and", "notifying", "karma", "." ]
c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba
https://github.com/lddubeau/karma-typescript-agile-preprocessor/blob/c80eb2ab72bd46f227d1df2bca8da5fbbb5960ba/index.js#L112-L121
31,540
bem-contrib/md-to-bemjson
packages/mdast-util-to-bemjson/lib/traverse.js
traverse
function traverse(transform, node, parent) { const type = node && node.type; assert(type, `Expected node, got '${node}'`); const baseHandler = transform.handlers[type] || transform.handlers.default; const userHandler = transform.userHandlers[type] || transform.userHandlers.default; const starHandler = transform.userHandlers['*']; const userBaseHandler = userHandler ? userHandler.bind({ __base: baseHandler }) : baseHandler; const handler = starHandler ? starHandler.bind({ __base: userBaseHandler }) : userBaseHandler; return handler(transform, node, parent); }
javascript
function traverse(transform, node, parent) { const type = node && node.type; assert(type, `Expected node, got '${node}'`); const baseHandler = transform.handlers[type] || transform.handlers.default; const userHandler = transform.userHandlers[type] || transform.userHandlers.default; const starHandler = transform.userHandlers['*']; const userBaseHandler = userHandler ? userHandler.bind({ __base: baseHandler }) : baseHandler; const handler = starHandler ? starHandler.bind({ __base: userBaseHandler }) : userBaseHandler; return handler(transform, node, parent); }
[ "function", "traverse", "(", "transform", ",", "node", ",", "parent", ")", "{", "const", "type", "=", "node", "&&", "node", ".", "type", ";", "assert", "(", "type", ",", "`", "${", "node", "}", "`", ")", ";", "const", "baseHandler", "=", "transform",...
Traverse MDAST tree @param {*} transform - transform function @param {Object} node - MDAST node @param {Object} [parent] - MDAST parent node @returns {*}
[ "Traverse", "MDAST", "tree" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/traverse.js#L13-L25
31,541
Incroud/cassanova
lib/table.js
Table
function Table(name, schema){ if(!name || typeof name !== "string"){ throw new Error("Attempting to instantiate a table without a valid name."); } if(!schema || !(schema instanceof Schema)){ throw new Error("Attempting to instantiate a table without a valid schema."); } this.name = name; this.schema = schema; }
javascript
function Table(name, schema){ if(!name || typeof name !== "string"){ throw new Error("Attempting to instantiate a table without a valid name."); } if(!schema || !(schema instanceof Schema)){ throw new Error("Attempting to instantiate a table without a valid schema."); } this.name = name; this.schema = schema; }
[ "function", "Table", "(", "name", ",", "schema", ")", "{", "if", "(", "!", "name", "||", "typeof", "name", "!==", "\"string\"", ")", "{", "throw", "new", "Error", "(", "\"Attempting to instantiate a table without a valid name.\"", ")", ";", "}", "if", "(", "...
Cassanova.Table @param {String} name The name of the table. Must match the name of the table in Cassandra @param {Schema} schema The table associated with the model.
[ "Cassanova", ".", "Table" ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/table.js#L10-L20
31,542
hoodiehq/pouchdb-hoodie-sync
lib/connect.js
connect
function connect (state) { return Promise.resolve(state.remote) .then(function (remote) { if (state.replication) { return } state.replication = state.db.sync(remote, { create_target: true, live: true, retry: true }) state.replication.on('error', function (error) { state.emitter.emit('error', error) }) state.replication.on('change', function (change) { for (var i = 0; i < change.change.docs.length; i++) { state.emitter.emit(change.direction, change.change.docs[i]) } }) state.emitter.emit('connect') }) }
javascript
function connect (state) { return Promise.resolve(state.remote) .then(function (remote) { if (state.replication) { return } state.replication = state.db.sync(remote, { create_target: true, live: true, retry: true }) state.replication.on('error', function (error) { state.emitter.emit('error', error) }) state.replication.on('change', function (change) { for (var i = 0; i < change.change.docs.length; i++) { state.emitter.emit(change.direction, change.change.docs[i]) } }) state.emitter.emit('connect') }) }
[ "function", "connect", "(", "state", ")", "{", "return", "Promise", ".", "resolve", "(", "state", ".", "remote", ")", ".", "then", "(", "function", "(", "remote", ")", "{", "if", "(", "state", ".", "replication", ")", "{", "return", "}", "state", "."...
connects local and remote database @return {Promise}
[ "connects", "local", "and", "remote", "database" ]
c489baf813020c7f0cbd111224432cb6718c90de
https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/connect.js#L10-L36
31,543
soajs/soajs.core.drivers
infra/aws/docker/index.js
function (options, cb) { options.soajs.log.debug("Generating docker token"); crypto.randomBytes(1024, function (err, buffer) { if (err) { return cb(err); } options.soajs.registry.deployer.container.docker.remote.apiProtocol = 'https'; options.soajs.registry.deployer.container.docker.remote.apiPort = 32376; options.soajs.registry.deployer.container.docker.remote.auth = { token: buffer.toString('hex') }; return cb(null, true); }); }
javascript
function (options, cb) { options.soajs.log.debug("Generating docker token"); crypto.randomBytes(1024, function (err, buffer) { if (err) { return cb(err); } options.soajs.registry.deployer.container.docker.remote.apiProtocol = 'https'; options.soajs.registry.deployer.container.docker.remote.apiPort = 32376; options.soajs.registry.deployer.container.docker.remote.auth = { token: buffer.toString('hex') }; return cb(null, true); }); }
[ "function", "(", "options", ",", "cb", ")", "{", "options", ".", "soajs", ".", "log", ".", "debug", "(", "\"Generating docker token\"", ")", ";", "crypto", ".", "randomBytes", "(", "1024", ",", "function", "(", "err", ",", "buffer", ")", "{", "if", "("...
Execute Deploy Cluster Pre Operation @param options @param cb @returns {*}
[ "Execute", "Deploy", "Cluster", "Pre", "Operation" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/docker/index.js#L23-L37
31,544
soajs/soajs.core.drivers
infra/aws/docker/index.js
function (options, cb) { let outIP = options.out; let stack = options.infra.stack; if (outIP && stack.options.ElbName) { options.soajs.log.debug("Creating SOAJS network."); dockerUtils.getDeployer(options, (error, deployer) => { if(error){ return cb(error); } deployer.listNetworks({}, (err, networks) => { if (err) { return cb(err); } let found = false; networks.forEach((oneNetwork) => { if (oneNetwork.Name === 'soajsnet') { found = true; } }); if(found){ return cb(null, true); } else{ let networkParams = { Name: 'soajsnet', Driver: 'overlay', Internal: false, Attachable: true, CheckDuplicate: true, EnableIPv6: false, IPAM: { Driver: 'default' } }; deployer.createNetwork(networkParams, (err) => { return cb(err, true); }); } }); }); } else { return cb(null, false); } }
javascript
function (options, cb) { let outIP = options.out; let stack = options.infra.stack; if (outIP && stack.options.ElbName) { options.soajs.log.debug("Creating SOAJS network."); dockerUtils.getDeployer(options, (error, deployer) => { if(error){ return cb(error); } deployer.listNetworks({}, (err, networks) => { if (err) { return cb(err); } let found = false; networks.forEach((oneNetwork) => { if (oneNetwork.Name === 'soajsnet') { found = true; } }); if(found){ return cb(null, true); } else{ let networkParams = { Name: 'soajsnet', Driver: 'overlay', Internal: false, Attachable: true, CheckDuplicate: true, EnableIPv6: false, IPAM: { Driver: 'default' } }; deployer.createNetwork(networkParams, (err) => { return cb(err, true); }); } }); }); } else { return cb(null, false); } }
[ "function", "(", "options", ",", "cb", ")", "{", "let", "outIP", "=", "options", ".", "out", ";", "let", "stack", "=", "options", ".", "infra", ".", "stack", ";", "if", "(", "outIP", "&&", "stack", ".", "options", ".", "ElbName", ")", "{", "options...
This method deploys the default soajsnet for docker @param options @param cb @returns {*}
[ "This", "method", "deploys", "the", "default", "soajsnet", "for", "docker" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/docker/index.js#L64-L114
31,545
hoodiehq/pouchdb-hoodie-sync
lib/disconnect.js
disconnect
function disconnect (state) { if (state.replication) { state.replication.cancel() delete state.replication state.emitter.emit('disconnect') } return Promise.resolve() }
javascript
function disconnect (state) { if (state.replication) { state.replication.cancel() delete state.replication state.emitter.emit('disconnect') } return Promise.resolve() }
[ "function", "disconnect", "(", "state", ")", "{", "if", "(", "state", ".", "replication", ")", "{", "state", ".", "replication", ".", "cancel", "(", ")", "delete", "state", ".", "replication", "state", ".", "emitter", ".", "emit", "(", "'disconnect'", ")...
disconnects local and remote database @return {Promise}
[ "disconnects", "local", "and", "remote", "database" ]
c489baf813020c7f0cbd111224432cb6718c90de
https://github.com/hoodiehq/pouchdb-hoodie-sync/blob/c489baf813020c7f0cbd111224432cb6718c90de/lib/disconnect.js#L10-L18
31,546
rangle/koast
lib/authentication/maintenance.js
addJwtHandling
function addJwtHandling(secrets, app) { if (!secrets.authTokenSecret) { log.error( 'Cannot setup token authentication because token secret is not configured.' ); return; } app.use(expressJwt({ secret: secrets.authTokenSecret })); app.use(function (req, res, next) { if (req.user && req.user.data) { req.user.isAuthenticated = true; req.user.meta = req.user.meta || {}; } next(); }); app.use(function (err, req, res, next) { if (err.name === 'UnauthorizedError') { if (err.code === 'credentials_required') { // If the caller did not provide credentials, we'll just consider this // an unauthenticated request. next(); } else { res.status(401).send('Invalid token: ' + err.message); } } }); }
javascript
function addJwtHandling(secrets, app) { if (!secrets.authTokenSecret) { log.error( 'Cannot setup token authentication because token secret is not configured.' ); return; } app.use(expressJwt({ secret: secrets.authTokenSecret })); app.use(function (req, res, next) { if (req.user && req.user.data) { req.user.isAuthenticated = true; req.user.meta = req.user.meta || {}; } next(); }); app.use(function (err, req, res, next) { if (err.name === 'UnauthorizedError') { if (err.code === 'credentials_required') { // If the caller did not provide credentials, we'll just consider this // an unauthenticated request. next(); } else { res.status(401).send('Invalid token: ' + err.message); } } }); }
[ "function", "addJwtHandling", "(", "secrets", ",", "app", ")", "{", "if", "(", "!", "secrets", ".", "authTokenSecret", ")", "{", "log", ".", "error", "(", "'Cannot setup token authentication because token secret is not configured.'", ")", ";", "return", ";", "}", ...
Adds the handling of Json Web Tokens. If a request comes with a JWT, we set the user accordingly. Improper or expired JWT results in a 401. If no JWT is submitted, however, we let this through, just without setting the user field on the request.
[ "Adds", "the", "handling", "of", "Json", "Web", "Tokens", ".", "If", "a", "request", "comes", "with", "a", "JWT", "we", "set", "the", "user", "accordingly", ".", "Improper", "or", "expired", "JWT", "results", "in", "a", "401", ".", "If", "no", "JWT", ...
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/maintenance.js#L25-L58
31,547
rangle/koast
lib/authentication/maintenance.js
addSessionHandling
function addSessionHandling(secrets, app) { var connection = dbUtils.getConnectionNow(); var sessionStore = new MongoStore({ db: connection.db }); app.use(cookieParser()); app.use(session({ secret: secrets.cookieSecret, maxAge: 3600000, // 1 hour store: sessionStore })); app.use(passport.initialize()); exports.usingSessions = true; app.use(passport.session()); passport.serializeUser(function (user, done) { var data = user.data || user; done(null, { data: data, isAuthenticated: true, meta: {} }); }); passport.deserializeUser(function (obj, done) { done(null, obj); }); }
javascript
function addSessionHandling(secrets, app) { var connection = dbUtils.getConnectionNow(); var sessionStore = new MongoStore({ db: connection.db }); app.use(cookieParser()); app.use(session({ secret: secrets.cookieSecret, maxAge: 3600000, // 1 hour store: sessionStore })); app.use(passport.initialize()); exports.usingSessions = true; app.use(passport.session()); passport.serializeUser(function (user, done) { var data = user.data || user; done(null, { data: data, isAuthenticated: true, meta: {} }); }); passport.deserializeUser(function (obj, done) { done(null, obj); }); }
[ "function", "addSessionHandling", "(", "secrets", ",", "app", ")", "{", "var", "connection", "=", "dbUtils", ".", "getConnectionNow", "(", ")", ";", "var", "sessionStore", "=", "new", "MongoStore", "(", "{", "db", ":", "connection", ".", "db", "}", ")", ...
Adds the handling of session cookies.
[ "Adds", "the", "handling", "of", "session", "cookies", "." ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/maintenance.js#L61-L91
31,548
zillow/mustache-wax
lib/mustache-wax.js
mix
function mix(receiver, supplier, overwrite) { var key; if (!receiver || !supplier) { return receiver || {}; } for (key in supplier) { if (supplier.hasOwnProperty(key)) { if (overwrite || !receiver.hasOwnProperty(key)) { receiver[key] = supplier[key]; } } } return receiver; }
javascript
function mix(receiver, supplier, overwrite) { var key; if (!receiver || !supplier) { return receiver || {}; } for (key in supplier) { if (supplier.hasOwnProperty(key)) { if (overwrite || !receiver.hasOwnProperty(key)) { receiver[key] = supplier[key]; } } } return receiver; }
[ "function", "mix", "(", "receiver", ",", "supplier", ",", "overwrite", ")", "{", "var", "key", ";", "if", "(", "!", "receiver", "||", "!", "supplier", ")", "{", "return", "receiver", "||", "{", "}", ";", "}", "for", "(", "key", "in", "supplier", ")...
mix & merge lifted from yui-base, simplified
[ "mix", "&", "merge", "lifted", "from", "yui", "-", "base", "simplified" ]
7e10cadba9c14c3b138ed568eebad16ea5d3b62c
https://github.com/zillow/mustache-wax/blob/7e10cadba9c14c3b138ed568eebad16ea5d3b62c/lib/mustache-wax.js#L284-L300
31,549
RavelLaw/e3
addon/utils/shadow/scales/ordinal.js
function(val) { let guid = guidFor(val); if(guid in map) { return map[guid]; } else if(sort) { let sibiling = calculateMissingPosition(val, domain, sort); return map[guidFor(sibiling)]; } else { return r0; } }
javascript
function(val) { let guid = guidFor(val); if(guid in map) { return map[guid]; } else if(sort) { let sibiling = calculateMissingPosition(val, domain, sort); return map[guidFor(sibiling)]; } else { return r0; } }
[ "function", "(", "val", ")", "{", "let", "guid", "=", "guidFor", "(", "val", ")", ";", "if", "(", "guid", "in", "map", ")", "{", "return", "map", "[", "guid", "]", ";", "}", "else", "if", "(", "sort", ")", "{", "let", "sibiling", "=", "calculat...
Create the closure that will return the matched value.
[ "Create", "the", "closure", "that", "will", "return", "the", "matched", "value", "." ]
7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d
https://github.com/RavelLaw/e3/blob/7149b2a9ebddd5c512132a41f7ae7c3a2235ac0d/addon/utils/shadow/scales/ordinal.js#L61-L71
31,550
rangle/koast
lib/admin-api/backup/backup.js
restoreBackup
function restoreBackup(backupRecord, mongoUri) { var receipts = backupRecord.receipts; var handler = getHandler(backupRecord.type); var restorePromises = receipts.map(function (receipt) { var tmpfile = util.getTempFileName() + '.bson'; return R.pPipe( handler.restore.bind(handler), R.curry(R.flip(mds.dump.fs.file))(tmpfile), R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection) )(receipt.data); }); return q.all(restorePromises).thenResolve('done'); }
javascript
function restoreBackup(backupRecord, mongoUri) { var receipts = backupRecord.receipts; var handler = getHandler(backupRecord.type); var restorePromises = receipts.map(function (receipt) { var tmpfile = util.getTempFileName() + '.bson'; return R.pPipe( handler.restore.bind(handler), R.curry(R.flip(mds.dump.fs.file))(tmpfile), R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection) )(receipt.data); }); return q.all(restorePromises).thenResolve('done'); }
[ "function", "restoreBackup", "(", "backupRecord", ",", "mongoUri", ")", "{", "var", "receipts", "=", "backupRecord", ".", "receipts", ";", "var", "handler", "=", "getHandler", "(", "backupRecord", ".", "type", ")", ";", "var", "restorePromises", "=", "receipts...
Consumes a backupRecord produced by createBackup and a mongoUri and restores the information contained in the record to the database described the mongoUri.
[ "Consumes", "a", "backupRecord", "produced", "by", "createBackup", "and", "a", "mongoUri", "and", "restores", "the", "information", "contained", "in", "the", "record", "to", "the", "database", "described", "the", "mongoUri", "." ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/admin-api/backup/backup.js#L104-L118
31,551
radify/angular-model
src/angular-model.js
autoBox
function autoBox(object, model, data) { if (!object) { return isArray(data) ? model.collection(data, true) : model.instance(data); } if (isArray(data) && isArray(object)) { return model.collection(data, true); } if (data && JSON.stringify(data).length > 3) { deepExtend(object, data); object.$original.sync(data); } return object; }
javascript
function autoBox(object, model, data) { if (!object) { return isArray(data) ? model.collection(data, true) : model.instance(data); } if (isArray(data) && isArray(object)) { return model.collection(data, true); } if (data && JSON.stringify(data).length > 3) { deepExtend(object, data); object.$original.sync(data); } return object; }
[ "function", "autoBox", "(", "object", ",", "model", ",", "data", ")", "{", "if", "(", "!", "object", ")", "{", "return", "isArray", "(", "data", ")", "?", "model", ".", "collection", "(", "data", ",", "true", ")", ":", "model", ".", "instance", "("...
'Box' an object value in a model instance if it is present. Otherwise, return an empty model object.
[ "Box", "an", "object", "value", "in", "a", "model", "instance", "if", "it", "is", "present", ".", "Otherwise", "return", "an", "empty", "model", "object", "." ]
e7afc0e4ca1504195adb63578d0290fc8f7af683
https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L118-L130
31,552
radify/angular-model
src/angular-model.js
function(object) { if (object instanceof ModelClass) { return object.url(); } if (object instanceof ModelInstance || isFunc(object.$model)) { var model = object.$model(); return expr(object, model.$config().identity + '.href').get() || model.url(); } throw new Error('Could not get URL for ' + typeof object); }
javascript
function(object) { if (object instanceof ModelClass) { return object.url(); } if (object instanceof ModelInstance || isFunc(object.$model)) { var model = object.$model(); return expr(object, model.$config().identity + '.href').get() || model.url(); } throw new Error('Could not get URL for ' + typeof object); }
[ "function", "(", "object", ")", "{", "if", "(", "object", "instanceof", "ModelClass", ")", "{", "return", "object", ".", "url", "(", ")", ";", "}", "if", "(", "object", "instanceof", "ModelInstance", "||", "isFunc", "(", "object", ".", "$model", ")", "...
Extract URL from object, or use default URL
[ "Extract", "URL", "from", "object", "or", "use", "default", "URL" ]
e7afc0e4ca1504195adb63578d0290fc8f7af683
https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L139-L148
31,553
radify/angular-model
src/angular-model.js
config
function config(name, options) { if (isObject(name)) { extend(global, name); return; } var previous = (registry[name] && registry[name].$config) ? registry[name].$config() : null, base = extend({}, previous ? extend({}, previous) : extend({}, DEFAULTS, DEFAULT_METHODS)); options = deepExtend(copy(base), options); if (!options.url) { options.url = global.base.replace(/\/$/, '') + '/' + hyphenate(name); } registry[name] = new ModelClass(options); }
javascript
function config(name, options) { if (isObject(name)) { extend(global, name); return; } var previous = (registry[name] && registry[name].$config) ? registry[name].$config() : null, base = extend({}, previous ? extend({}, previous) : extend({}, DEFAULTS, DEFAULT_METHODS)); options = deepExtend(copy(base), options); if (!options.url) { options.url = global.base.replace(/\/$/, '') + '/' + hyphenate(name); } registry[name] = new ModelClass(options); }
[ "function", "config", "(", "name", ",", "options", ")", "{", "if", "(", "isObject", "(", "name", ")", ")", "{", "extend", "(", "global", ",", "name", ")", ";", "return", ";", "}", "var", "previous", "=", "(", "registry", "[", "name", "]", "&&", "...
Configures a new model, updates an existing model's settings, or updates global settings
[ "Configures", "a", "new", "model", "updates", "an", "existing", "model", "s", "settings", "or", "updates", "global", "settings" ]
e7afc0e4ca1504195adb63578d0290fc8f7af683
https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L588-L602
31,554
radify/angular-model
src/angular-model.js
ModelClassFactory
function ModelClassFactory(name, options) { if (!isUndef(options)) { return config(name, options); } return registry[name] || undefined; }
javascript
function ModelClassFactory(name, options) { if (!isUndef(options)) { return config(name, options); } return registry[name] || undefined; }
[ "function", "ModelClassFactory", "(", "name", ",", "options", ")", "{", "if", "(", "!", "isUndef", "(", "options", ")", ")", "{", "return", "config", "(", "name", ",", "options", ")", ";", "}", "return", "registry", "[", "name", "]", "||", "undefined",...
Adds, gets, or updates a named model configuration
[ "Adds", "gets", "or", "updates", "a", "named", "model", "configuration" ]
e7afc0e4ca1504195adb63578d0290fc8f7af683
https://github.com/radify/angular-model/blob/e7afc0e4ca1504195adb63578d0290fc8f7af683/src/angular-model.js#L664-L669
31,555
soajs/soajs.core.drivers
infra/aws/cluster/lb.js
function (options, mCb) { const aws = options.infra.api; getElbMethod(options.params.elbType || 'classic', 'list', (elbResponse) => { const elb = getConnector({ api: elbResponse.api, region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); const ec2 = getConnector({ api: 'ec2', region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); elb[elbResponse.method]({}, function (err, response) { if (err) { return mCb(err); } async.map(response.LoadBalancerDescriptions, function (lb, callback) { async.parallel({ subnets: function (callback) { if (lb && lb.Subnets && Array.isArray(lb.Subnets) && lb.Subnets.length > 0) { let sParams = {SubnetIds: lb.Subnets}; ec2.describeSubnets(sParams, callback); } else { return callback(null, null); } }, instances: function (callback) { let iParams = {LoadBalancerName: lb.LoadBalancerName}; elb.describeInstanceHealth(iParams, callback); } }, function (err, results) { return callback(err, helper[elbResponse.helper]({ lb, region: options.params.region, subnets: results.subnets ? results.subnets.Subnets : [], instances: results.instances ? results.instances.InstanceStates : [] })); }); }, mCb); }); }); }
javascript
function (options, mCb) { const aws = options.infra.api; getElbMethod(options.params.elbType || 'classic', 'list', (elbResponse) => { const elb = getConnector({ api: elbResponse.api, region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); const ec2 = getConnector({ api: 'ec2', region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); elb[elbResponse.method]({}, function (err, response) { if (err) { return mCb(err); } async.map(response.LoadBalancerDescriptions, function (lb, callback) { async.parallel({ subnets: function (callback) { if (lb && lb.Subnets && Array.isArray(lb.Subnets) && lb.Subnets.length > 0) { let sParams = {SubnetIds: lb.Subnets}; ec2.describeSubnets(sParams, callback); } else { return callback(null, null); } }, instances: function (callback) { let iParams = {LoadBalancerName: lb.LoadBalancerName}; elb.describeInstanceHealth(iParams, callback); } }, function (err, results) { return callback(err, helper[elbResponse.helper]({ lb, region: options.params.region, subnets: results.subnets ? results.subnets.Subnets : [], instances: results.instances ? results.instances.InstanceStates : [] })); }); }, mCb); }); }); }
[ "function", "(", "options", ",", "mCb", ")", "{", "const", "aws", "=", "options", ".", "infra", ".", "api", ";", "getElbMethod", "(", "options", ".", "params", ".", "elbType", "||", "'classic'", ",", "'list'", ",", "(", "elbResponse", ")", "=>", "{", ...
This method return a list of Load Balancers @param options @param mCb
[ "This", "method", "return", "a", "list", "of", "Load", "Balancers" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/cluster/lb.js#L50-L95
31,556
soajs/soajs.core.drivers
infra/aws/cluster/lb.js
function (options, mCb) { getElbMethod(options.params.elbType || 'classic', 'delete', (elbResponse) => { const aws = options.infra.api; const elb = getConnector({ api: elbResponse.api, region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); let params = { LoadBalancerName: options.params.name }; options.soajs.log.debug(params); elb[elbResponse.method](params, mCb); }); }
javascript
function (options, mCb) { getElbMethod(options.params.elbType || 'classic', 'delete', (elbResponse) => { const aws = options.infra.api; const elb = getConnector({ api: elbResponse.api, region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); let params = { LoadBalancerName: options.params.name }; options.soajs.log.debug(params); elb[elbResponse.method](params, mCb); }); }
[ "function", "(", "options", ",", "mCb", ")", "{", "getElbMethod", "(", "options", ".", "params", ".", "elbType", "||", "'classic'", ",", "'delete'", ",", "(", "elbResponse", ")", "=>", "{", "const", "aws", "=", "options", ".", "infra", ".", "api", ";",...
This method deletes a load balancer @param options @param mCb @returns {*}
[ "This", "method", "deletes", "a", "load", "balancer" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/infra/aws/cluster/lb.js#L850-L865
31,557
suguru/node-stat
plugins/stat.js
initcpurow
function initcpurow() { return { user: 0, nice: 0, system: 0, iowait: 0, idle: 0, irq: 0, softirq: 0, steal: 0, guest: 0, guest_nice: 0 }; }
javascript
function initcpurow() { return { user: 0, nice: 0, system: 0, iowait: 0, idle: 0, irq: 0, softirq: 0, steal: 0, guest: 0, guest_nice: 0 }; }
[ "function", "initcpurow", "(", ")", "{", "return", "{", "user", ":", "0", ",", "nice", ":", "0", ",", "system", ":", "0", ",", "iowait", ":", "0", ",", "idle", ":", "0", ",", "irq", ":", "0", ",", "softirq", ":", "0", ",", "steal", ":", "0", ...
init cpu row
[ "init", "cpu", "row" ]
0e8eb98307e7cb1bb735a46b82b08b3530660b4f
https://github.com/suguru/node-stat/blob/0e8eb98307e7cb1bb735a46b82b08b3530660b4f/plugins/stat.js#L32-L45
31,558
profitbricks/profitbricks-sdk-nodejs
examples/findserverbyname.js
findname
function findname(error, response, body) { if (error){ return error } if (body){ try{ var info = JSON.parse(body) } catch(err){ console.log(body) return } if (info.items){ var ilen=info.items.length while(ilen--){ var it=info.items[ilen] var thename=it['properties']['name'] if (thename.match(srchfor)){ console.log(it) // <---- print json for server(s) that match srchfor } } } } }
javascript
function findname(error, response, body) { if (error){ return error } if (body){ try{ var info = JSON.parse(body) } catch(err){ console.log(body) return } if (info.items){ var ilen=info.items.length while(ilen--){ var it=info.items[ilen] var thename=it['properties']['name'] if (thename.match(srchfor)){ console.log(it) // <---- print json for server(s) that match srchfor } } } } }
[ "function", "findname", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "error", ")", "{", "return", "error", "}", "if", "(", "body", ")", "{", "try", "{", "var", "info", "=", "JSON", ".", "parse", "(", "body", ")", "}", "catch",...
findname will be our callback
[ "findname", "will", "be", "our", "callback" ]
861ff9daf7a30cfb84b2be0a02fed67369fea964
https://github.com/profitbricks/profitbricks-sdk-nodejs/blob/861ff9daf7a30cfb84b2be0a02fed67369fea964/examples/findserverbyname.js#L19-L42
31,559
bigpipe/temper
index.js
Temper
function Temper(options) { if (!this) return new Temper(options); options = options || {}; // // We only want to cache the templates in production as it's so we can easily // change templates when we're developing. // options.cache = 'cache' in options ? options.cache : process.env.NODE_ENV !== 'production'; this.installed = Object.create(null); // Installed module for extension cache. this.required = Object.create(null); // Template engine require cache. this.compiled = Object.create(null); // Compiled template cache. this.timers = new TickTock(this); // Keep track of timeouts. this.file = Object.create(null); // File lookup cache. this.cache = options.cache; // Cache compiled templates. }
javascript
function Temper(options) { if (!this) return new Temper(options); options = options || {}; // // We only want to cache the templates in production as it's so we can easily // change templates when we're developing. // options.cache = 'cache' in options ? options.cache : process.env.NODE_ENV !== 'production'; this.installed = Object.create(null); // Installed module for extension cache. this.required = Object.create(null); // Template engine require cache. this.compiled = Object.create(null); // Compiled template cache. this.timers = new TickTock(this); // Keep track of timeouts. this.file = Object.create(null); // File lookup cache. this.cache = options.cache; // Cache compiled templates. }
[ "function", "Temper", "(", "options", ")", "{", "if", "(", "!", "this", ")", "return", "new", "Temper", "(", "options", ")", ";", "options", "=", "options", "||", "{", "}", ";", "//", "// We only want to cache the templates in production as it's so we can easily",...
Temper compiles templates to client-side compatible templates as well as it's server side equivalents. @constructor @param {Object} options Temper configuration. @api public
[ "Temper", "compiles", "templates", "to", "client", "-", "side", "compatible", "templates", "as", "well", "as", "it", "s", "server", "side", "equivalents", "." ]
a658d4a0e96d2cf5f001768ed36dd90d2adb8183
https://github.com/bigpipe/temper/blob/a658d4a0e96d2cf5f001768ed36dd90d2adb8183/index.js#L18-L36
31,560
bem-contrib/md-to-bemjson
packages/remark-bemjson/lib/index.js
plugin
function plugin(options) { options = defaultsDeep({}, options, defaults); this.Compiler = compiler; function compiler(node, file) { const root = node && node.type && node.type === 'root'; const bemjson = toBemjson(node, { augment: options.augment }); const bjsonString = options.export ? JSON.stringify(bemjson, null, 4) : ''; if (file.extname) { file.extname = '.js'; } if (file.stem) { file.stem = file.stem + '.bemjson'; } file.data = bemjson; return root ? createExport({ type: options.exportType, name: options.exportName }, bjsonString) : bjsonString; } }
javascript
function plugin(options) { options = defaultsDeep({}, options, defaults); this.Compiler = compiler; function compiler(node, file) { const root = node && node.type && node.type === 'root'; const bemjson = toBemjson(node, { augment: options.augment }); const bjsonString = options.export ? JSON.stringify(bemjson, null, 4) : ''; if (file.extname) { file.extname = '.js'; } if (file.stem) { file.stem = file.stem + '.bemjson'; } file.data = bemjson; return root ? createExport({ type: options.exportType, name: options.exportName }, bjsonString) : bjsonString; } }
[ "function", "plugin", "(", "options", ")", "{", "options", "=", "defaultsDeep", "(", "{", "}", ",", "options", ",", "defaults", ")", ";", "this", ".", "Compiler", "=", "compiler", ";", "function", "compiler", "(", "node", ",", "file", ")", "{", "const"...
remark bemjson compiler plugin @param {Object} options - plugin options @param {ExportType} [options.exportType=commonJS] - export type. @param {string} [options.exportName] - if export to browser requires name. @param {Function} [options.augment] - transform callback.
[ "remark", "bemjson", "compiler", "plugin" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/remark-bemjson/lib/index.js#L17-L40
31,561
rangle/koast
lib/authentication/authentication.js
handleLogin
function handleLogin(user, req, res, next) { var token; var profile; var tokenExpiresInMinutes; var envelope = { data: user, isAuthenticated: true, meta: {} }; // First handle the case where the user was not logged in. if (!user) { if (authConfig.maintenance === 'cookie') { req.logout(); } return res.status(401).send('Wrong password or no such user.'); } // user_id is how it is in the schema /* jshint ignore:start */ // Now handle the case where we did get a user record. if (authConfig.maintenance === 'token') { // For token authentication we want to add a token. profile = { username: user.username, email: user.email, userdata_id: user.userdata_id }; /* jshint ignore:end */ tokenExpiresInMinutes = authConfig.expiresInMinutes || 60; envelope.meta.token = generateToken(profile, tokenExpiresInMinutes, secrets.authTokenSecret); envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes); return res.status(200).send(envelope); } else if (authConfig.maintenance === 'cookie') { // For cookie authentication we want to login the user. req.login(user, function (err) { if (err) { return next(err); } else { return res.status(200).send(envelope); } }); } }
javascript
function handleLogin(user, req, res, next) { var token; var profile; var tokenExpiresInMinutes; var envelope = { data: user, isAuthenticated: true, meta: {} }; // First handle the case where the user was not logged in. if (!user) { if (authConfig.maintenance === 'cookie') { req.logout(); } return res.status(401).send('Wrong password or no such user.'); } // user_id is how it is in the schema /* jshint ignore:start */ // Now handle the case where we did get a user record. if (authConfig.maintenance === 'token') { // For token authentication we want to add a token. profile = { username: user.username, email: user.email, userdata_id: user.userdata_id }; /* jshint ignore:end */ tokenExpiresInMinutes = authConfig.expiresInMinutes || 60; envelope.meta.token = generateToken(profile, tokenExpiresInMinutes, secrets.authTokenSecret); envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes); return res.status(200).send(envelope); } else if (authConfig.maintenance === 'cookie') { // For cookie authentication we want to login the user. req.login(user, function (err) { if (err) { return next(err); } else { return res.status(200).send(envelope); } }); } }
[ "function", "handleLogin", "(", "user", ",", "req", ",", "res", ",", "next", ")", "{", "var", "token", ";", "var", "profile", ";", "var", "tokenExpiresInMinutes", ";", "var", "envelope", "=", "{", "data", ":", "user", ",", "isAuthenticated", ":", "true",...
depends on auth config
[ "depends", "on", "auth", "config" ]
446dfaba7f80c03ae17d86b34dfafd6328be1ba6
https://github.com/rangle/koast/blob/446dfaba7f80c03ae17d86b34dfafd6328be1ba6/lib/authentication/authentication.js#L86-L132
31,562
IonicaBizau/deffy
lib/index.js
Deffy
function Deffy(input, def, options) { // Default is a function if (typeof def === "function") { return def(input); } options = Typpy(options) === "boolean" ? { empty: options } : { empty: false }; // Handle empty if (options.empty) { return input || def; } // Return input if (Typpy(input) === Typpy(def)) { return input; } // Return the default return def; }
javascript
function Deffy(input, def, options) { // Default is a function if (typeof def === "function") { return def(input); } options = Typpy(options) === "boolean" ? { empty: options } : { empty: false }; // Handle empty if (options.empty) { return input || def; } // Return input if (Typpy(input) === Typpy(def)) { return input; } // Return the default return def; }
[ "function", "Deffy", "(", "input", ",", "def", ",", "options", ")", "{", "// Default is a function", "if", "(", "typeof", "def", "===", "\"function\"", ")", "{", "return", "def", "(", "input", ")", ";", "}", "options", "=", "Typpy", "(", "options", ")", ...
Deffy Computes a final value by providing the input and default values. @name Deffy @function @param {Anything} input The input value. @param {Anything|Function} def The default value or a function getting the input value as first argument. @param {Object|Boolean} options The `empty` value or an object containing the following fields: - `empty` (Boolean): Handles the input value as empty field (`input || default`). Default is `false`. @return {Anything} The computed value.
[ "Deffy", "Computes", "a", "final", "value", "by", "providing", "the", "input", "and", "default", "values", "." ]
979c50f40c07d00e6456ef2568344723d7b39042
https://github.com/IonicaBizau/deffy/blob/979c50f40c07d00e6456ef2568344723d7b39042/lib/index.js#L20-L45
31,563
fnogatz/transportation
lib/list.js
generateRandomId
function generateRandomId (length) { var str = '' length = length || 6 while (str.length < length) { str += (((1 + Math.random()) * 0x10000) | 0).toString(16) } return str.substring(str.length - length, str.length) }
javascript
function generateRandomId (length) { var str = '' length = length || 6 while (str.length < length) { str += (((1 + Math.random()) * 0x10000) | 0).toString(16) } return str.substring(str.length - length, str.length) }
[ "function", "generateRandomId", "(", "length", ")", "{", "var", "str", "=", "''", "length", "=", "length", "||", "6", "while", "(", "str", ".", "length", "<", "length", ")", "{", "str", "+=", "(", "(", "(", "1", "+", "Math", ".", "random", "(", "...
Generate an alphanumeric ID with the given length. @param {Integer} length @return {String} ID
[ "Generate", "an", "alphanumeric", "ID", "with", "the", "given", "length", "." ]
4d967d99bc564827ee3c4c122c967dc65d947874
https://github.com/fnogatz/transportation/blob/4d967d99bc564827ee3c4c122c967dc65d947874/lib/list.js#L165-L172
31,564
gbv/jskos-tools
lib/object-types.js
guessObjectType
function guessObjectType(obj, shortname=false) { var type if (typeof obj === "string" && obj) { if (obj in objectTypeUris) { // given by URI type = objectTypeUris[obj] } else { // given by name obj = obj.toLowerCase().replace(/s$/,"") type = Object.keys(objectTypes).find(name => { const lowercase = name.toLowerCase() if (lowercase === obj || lowercase === "concept" + obj) { return true } }) } } else if (typeof obj === "object") { if (obj.type) { let types = Array.isArray(obj.type) ? obj.type : [obj.type] for (let uri of types) { if (uri in objectTypeUris) { type = objectTypeUris[uri] break } } } } return (shortname && type) ? type.toLowerCase().replace(/^concept(.+)/, "$1") : type }
javascript
function guessObjectType(obj, shortname=false) { var type if (typeof obj === "string" && obj) { if (obj in objectTypeUris) { // given by URI type = objectTypeUris[obj] } else { // given by name obj = obj.toLowerCase().replace(/s$/,"") type = Object.keys(objectTypes).find(name => { const lowercase = name.toLowerCase() if (lowercase === obj || lowercase === "concept" + obj) { return true } }) } } else if (typeof obj === "object") { if (obj.type) { let types = Array.isArray(obj.type) ? obj.type : [obj.type] for (let uri of types) { if (uri in objectTypeUris) { type = objectTypeUris[uri] break } } } } return (shortname && type) ? type.toLowerCase().replace(/^concept(.+)/, "$1") : type }
[ "function", "guessObjectType", "(", "obj", ",", "shortname", "=", "false", ")", "{", "var", "type", "if", "(", "typeof", "obj", "===", "\"string\"", "&&", "obj", ")", "{", "if", "(", "obj", "in", "objectTypeUris", ")", "{", "// given by URI", "type", "="...
Guess the JSKOS Concept Type name from an object or name. @memberof module:jskos-tools @param {object|string} jskos|name|uri object or string to guess from @param {boolean} shortname return short name if enabled (false by default)
[ "Guess", "the", "JSKOS", "Concept", "Type", "name", "from", "an", "object", "or", "name", "." ]
da8672203362ea874f4ab9cdd34b990369987075
https://github.com/gbv/jskos-tools/blob/da8672203362ea874f4ab9cdd34b990369987075/lib/object-types.js#L62-L90
31,565
storj/mongodb-adapter
lib/adapter.js
MongoAdapter
function MongoAdapter(mongooseConnection) { if (!(this instanceof MongoAdapter)) { return new MongoAdapter(mongooseConnection); } storj.StorageAdapter.call(this); if (mongooseConnection instanceof Storage) { this._model = mongooseConnection.models.Shard; } else { this._model = Shard(mongooseConnection); } }
javascript
function MongoAdapter(mongooseConnection) { if (!(this instanceof MongoAdapter)) { return new MongoAdapter(mongooseConnection); } storj.StorageAdapter.call(this); if (mongooseConnection instanceof Storage) { this._model = mongooseConnection.models.Shard; } else { this._model = Shard(mongooseConnection); } }
[ "function", "MongoAdapter", "(", "mongooseConnection", ")", "{", "if", "(", "!", "(", "this", "instanceof", "MongoAdapter", ")", ")", "{", "return", "new", "MongoAdapter", "(", "mongooseConnection", ")", ";", "}", "storj", ".", "StorageAdapter", ".", "call", ...
Implements a MongoDB storage adapter for contract and audit management @constructor @extends {storj.StorageAdapter} @param {Storage} mongooseConnection - The connection object from mongoose
[ "Implements", "a", "MongoDB", "storage", "adapter", "for", "contract", "and", "audit", "management" ]
a31dab5c669d9ee7c9c96f2ee094bf28d0f3b1c7
https://github.com/storj/mongodb-adapter/blob/a31dab5c669d9ee7c9c96f2ee094bf28d0f3b1c7/lib/adapter.js#L17-L29
31,566
fissionjs/fission
lib/util/ensureInstance.js
constructModel
function constructModel(Model, options) { return construct({ input: Model, expected: AmpersandModel, createConstructor: model, options: options }); }
javascript
function constructModel(Model, options) { return construct({ input: Model, expected: AmpersandModel, createConstructor: model, options: options }); }
[ "function", "constructModel", "(", "Model", ",", "options", ")", "{", "return", "construct", "(", "{", "input", ":", "Model", ",", "expected", ":", "AmpersandModel", ",", "createConstructor", ":", "model", ",", "options", ":", "options", "}", ")", ";", "}"...
Model = either a Model constructor, a Model instance, or an object to create a Model constructor options = construction options
[ "Model", "=", "either", "a", "Model", "constructor", "a", "Model", "instance", "or", "an", "object", "to", "create", "a", "Model", "constructor", "options", "=", "construction", "options" ]
e34eed78ed2386bb7934a69214e13f17fcd311c3
https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/util/ensureInstance.js#L68-L75
31,567
fissionjs/fission
lib/util/ensureInstance.js
constructCollection
function constructCollection(Collection, options) { return construct({ input: Collection, expected: AmpersandCollection, createConstructor: collection, options: options }); }
javascript
function constructCollection(Collection, options) { return construct({ input: Collection, expected: AmpersandCollection, createConstructor: collection, options: options }); }
[ "function", "constructCollection", "(", "Collection", ",", "options", ")", "{", "return", "construct", "(", "{", "input", ":", "Collection", ",", "expected", ":", "AmpersandCollection", ",", "createConstructor", ":", "collection", ",", "options", ":", "options", ...
Collection = either a Collection constructor, a Collection instance, or an object to create a Collection constructor options = construction options
[ "Collection", "=", "either", "a", "Collection", "constructor", "a", "Collection", "instance", "or", "an", "object", "to", "create", "a", "Collection", "constructor", "options", "=", "construction", "options" ]
e34eed78ed2386bb7934a69214e13f17fcd311c3
https://github.com/fissionjs/fission/blob/e34eed78ed2386bb7934a69214e13f17fcd311c3/lib/util/ensureInstance.js#L80-L87
31,568
soajs/soajs.core.drivers
lib/terraform/index.js
function(options, cb) { let template, render; if(!options.params || !options.params.template || !options.params.template.content) { return utils.checkError('Missing template content', 727, cb); } try { template = handlebars.compile(options.params.template.content); if(options.params.template._id){ if(!options.params.input.tags){ options.params.input.tags = {}; } options.params.input.tags['soajs.template.id'] = options.params.template._id.toString(); } render = template(options.params.input); } catch(e) { return utils.checkError(e, 727, cb); } return cb(null, { render }); }
javascript
function(options, cb) { let template, render; if(!options.params || !options.params.template || !options.params.template.content) { return utils.checkError('Missing template content', 727, cb); } try { template = handlebars.compile(options.params.template.content); if(options.params.template._id){ if(!options.params.input.tags){ options.params.input.tags = {}; } options.params.input.tags['soajs.template.id'] = options.params.template._id.toString(); } render = template(options.params.input); } catch(e) { return utils.checkError(e, 727, cb); } return cb(null, { render }); }
[ "function", "(", "options", ",", "cb", ")", "{", "let", "template", ",", "render", ";", "if", "(", "!", "options", ".", "params", "||", "!", "options", ".", "params", ".", "template", "||", "!", "options", ".", "params", ".", "template", ".", "conten...
Render a terraform dynamic template and return output @param {Object} options Data passed to function as params @param {Function} cb Callback function @return {void}
[ "Render", "a", "terraform", "dynamic", "template", "and", "return", "output" ]
545891509a47e16d9d2f40515e81bb1f4f3d8165
https://github.com/soajs/soajs.core.drivers/blob/545891509a47e16d9d2f40515e81bb1f4f3d8165/lib/terraform/index.js#L34-L55
31,569
Incroud/cassanova
lib/schemaType.js
SchemaType
function SchemaType(type, validation, wrapper, params){ this.type = type; this.validate = validation; this.wrapper = wrapper; this.parameters = params; this.isPrimary = false; chainPrimaryKey(); }
javascript
function SchemaType(type, validation, wrapper, params){ this.type = type; this.validate = validation; this.wrapper = wrapper; this.parameters = params; this.isPrimary = false; chainPrimaryKey(); }
[ "function", "SchemaType", "(", "type", ",", "validation", ",", "wrapper", ",", "params", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "validate", "=", "validation", ";", "this", ".", "wrapper", "=", "wrapper", ";", "this", ".", "parame...
A schema data type for use with Cassandra @param {String} type The data type associated with Cassandra @param {Function} validation A function to validate that the value associated matches the type. @param {Object} wrapper Wraps the schema value if necessary @param {Object} params Additional parameters that the schema type may need. @return {[type]} [description]
[ "A", "schema", "data", "type", "for", "use", "with", "Cassandra" ]
49c5ce2e1bc6b19d25e8223e88df45c113c36b68
https://github.com/Incroud/cassanova/blob/49c5ce2e1bc6b19d25e8223e88df45c113c36b68/lib/schemaType.js#L9-L17
31,570
bem-contrib/md-to-bemjson
packages/mdast-util-to-bemjson/lib/transform.js
function(node, entity, props, content) { const hasContent = (!entity || entity.content !== null) && content !== null; const entityContent = hasContent ? ((entity && entity.content) || content || traverse.children(transform, node)) : null; const block = parseBemNode(entity); const bemNode = build(block, props, entityContent); // Extend blocks context with external plugins hContext if (node.data) { node.data.htmlAttributes && (bemNode.attrs = Object.assign({}, bemNode.attrs, node.data.htmlAttributes)); node.data.hProperties && (bemNode.hProps = node.data.hProperties); } return transform.augment(bemNode); }
javascript
function(node, entity, props, content) { const hasContent = (!entity || entity.content !== null) && content !== null; const entityContent = hasContent ? ((entity && entity.content) || content || traverse.children(transform, node)) : null; const block = parseBemNode(entity); const bemNode = build(block, props, entityContent); // Extend blocks context with external plugins hContext if (node.data) { node.data.htmlAttributes && (bemNode.attrs = Object.assign({}, bemNode.attrs, node.data.htmlAttributes)); node.data.hProperties && (bemNode.hProps = node.data.hProperties); } return transform.augment(bemNode); }
[ "function", "(", "node", ",", "entity", ",", "props", ",", "content", ")", "{", "const", "hasContent", "=", "(", "!", "entity", "||", "entity", ".", "content", "!==", "null", ")", "&&", "content", "!==", "null", ";", "const", "entityContent", "=", "has...
Transform MDAST node to bemNode @param {Object} node - MDAST node @param {Object} entity - bem entity, partial representation of bemNode @param {Object} [props] - bemNode properties @param {Object|Array|String} [content] - bemNode content @returns {Object} bemNode
[ "Transform", "MDAST", "node", "to", "bemNode" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/transform.js#L41-L56
31,571
bem-contrib/md-to-bemjson
packages/mdast-util-to-bemjson/lib/transform.js
augmentFactory
function augmentFactory(augmentFunction) { /** * Apply custom augmentation and insert back to subtree * * @function AugmentFunction * @param {Object} bemNode - representation of bem entity * @returns {Object} bemNode */ function augment(bemNode) { const hasChildren = _hasChildren(bemNode.content); const bemNodeClone = hasChildren ? omit(bemNode, ['content']) : cloneDeep(bemNode); const augmentedBemNode = augmentFunction(bemNodeClone); /* Check that if we has children augmentation doesn't modify content */ assert( !hasChildren || !augmentedBemNode.content, 'You are not allow to modify subtree of bemNode. To do that please use bem-xjst@' ); if (hasChildren) { augmentedBemNode.content = bemNode.content; } return augmentedBemNode; } return augment; }
javascript
function augmentFactory(augmentFunction) { /** * Apply custom augmentation and insert back to subtree * * @function AugmentFunction * @param {Object} bemNode - representation of bem entity * @returns {Object} bemNode */ function augment(bemNode) { const hasChildren = _hasChildren(bemNode.content); const bemNodeClone = hasChildren ? omit(bemNode, ['content']) : cloneDeep(bemNode); const augmentedBemNode = augmentFunction(bemNodeClone); /* Check that if we has children augmentation doesn't modify content */ assert( !hasChildren || !augmentedBemNode.content, 'You are not allow to modify subtree of bemNode. To do that please use bem-xjst@' ); if (hasChildren) { augmentedBemNode.content = bemNode.content; } return augmentedBemNode; } return augment; }
[ "function", "augmentFactory", "(", "augmentFunction", ")", "{", "/**\n * Apply custom augmentation and insert back to subtree\n *\n * @function AugmentFunction\n * @param {Object} bemNode - representation of bem entity\n * @returns {Object} bemNode\n */", ...
Create augment function, for apply custom transformations @param {BjsonConverter~augmentCallback} augmentFunction - callback with custom augmentation @returns {BjsonConverter~augment}
[ "Create", "augment", "function", "for", "apply", "custom", "transformations" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/transform.js#L70-L98
31,572
bem-contrib/md-to-bemjson
packages/mdast-util-to-bemjson/lib/transform.js
_hasChildren
function _hasChildren(content) { if (!content) return false; if (typeof content === 'object') return true; if (Array.isArray(content) && content.every(item => typeof item === 'string')) return false; return false; }
javascript
function _hasChildren(content) { if (!content) return false; if (typeof content === 'object') return true; if (Array.isArray(content) && content.every(item => typeof item === 'string')) return false; return false; }
[ "function", "_hasChildren", "(", "content", ")", "{", "if", "(", "!", "content", ")", "return", "false", ";", "if", "(", "typeof", "content", "===", "'object'", ")", "return", "true", ";", "if", "(", "Array", ".", "isArray", "(", "content", ")", "&&", ...
Check is content of bemNode value, or children @param {Object|Array|String|undefined} content - bemNode content @returns {Boolean} is content of bemNode are children @private
[ "Check", "is", "content", "of", "bemNode", "value", "or", "children" ]
047ab80c681073c7c92aecee754bcf46956507a9
https://github.com/bem-contrib/md-to-bemjson/blob/047ab80c681073c7c92aecee754bcf46956507a9/packages/mdast-util-to-bemjson/lib/transform.js#L110-L115
31,573
canjs/can-react
extensions/can-simple-dom.js
reindexNodes
function reindexNodes () { var child = this.node.firstChild; this._length = 0; while (child) { this[this._length++] = child; child = child.nextSibling; } }
javascript
function reindexNodes () { var child = this.node.firstChild; this._length = 0; while (child) { this[this._length++] = child; child = child.nextSibling; } }
[ "function", "reindexNodes", "(", ")", "{", "var", "child", "=", "this", ".", "node", ".", "firstChild", ";", "this", ".", "_length", "=", "0", ";", "while", "(", "child", ")", "{", "this", "[", "this", ".", "_length", "++", "]", "=", "child", ";", ...
Bind or call this method against a childNodes property
[ "Bind", "or", "call", "this", "method", "against", "a", "childNodes", "property" ]
87aaaff9858cec0629ed83f4f54596cc3c20903a
https://github.com/canjs/can-react/blob/87aaaff9858cec0629ed83f4f54596cc3c20903a/extensions/can-simple-dom.js#L94-L102
31,574
davedoesdev/qlobber
lib/qlobber.js
Qlobber
function Qlobber (options) { options = options || {}; this._separator = options.separator || '.'; this._wildcard_one = options.wildcard_one || '*'; this._wildcard_some = options.wildcard_some || '#'; this._trie = new Map(); if (options.cache_adds instanceof Map) { this._shortcuts = options.cache_adds; } else if (options.cache_adds) { this._shortcuts = new Map(); } }
javascript
function Qlobber (options) { options = options || {}; this._separator = options.separator || '.'; this._wildcard_one = options.wildcard_one || '*'; this._wildcard_some = options.wildcard_some || '#'; this._trie = new Map(); if (options.cache_adds instanceof Map) { this._shortcuts = options.cache_adds; } else if (options.cache_adds) { this._shortcuts = new Map(); } }
[ "function", "Qlobber", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_separator", "=", "options", ".", "separator", "||", "'.'", ";", "this", ".", "_wildcard_one", "=", "options", ".", "wildcard_one", "||", "'*'"...
Creates a new qlobber. @constructor @param {Object} [options] Configures the qlobber. Use the following properties: - `{String} separator` The character to use for separating words in topics. Defaults to '.'. MQTT uses '/' as the separator, for example. - `{String} wildcard_one` The character to use for matching exactly one word in a topic. Defaults to '*'. MQTT uses '+', for example. - `{String} wildcard_some` The character to use for matching zero or more words in a topic. Defaults to '#'. MQTT uses '#' too. - `{Boolean|Map} cache_adds` Whether to cache topics when adding topic matchers. This will make adding multiple matchers for the same topic faster at the cost of extra memory usage. Defaults to `false`. If you supply a `Map` then it will be used to cache the topics (use this to enumerate all the topics in the qlobber).
[ "Creates", "a", "new", "qlobber", "." ]
95d68c17658f24999733e4f8f6d35e01d82fa665
https://github.com/davedoesdev/qlobber/blob/95d68c17658f24999733e4f8f6d35e01d82fa665/lib/qlobber.js#L117-L133
31,575
canjs/can-stache-key
can-stache-key.js
function(value, i, reads, options) { return value && value[getValueSymbol] && value[isValueLikeSymbol] !== false && (options.foundAt || !isAt(i, reads) ); }
javascript
function(value, i, reads, options) { return value && value[getValueSymbol] && value[isValueLikeSymbol] !== false && (options.foundAt || !isAt(i, reads) ); }
[ "function", "(", "value", ",", "i", ",", "reads", ",", "options", ")", "{", "return", "value", "&&", "value", "[", "getValueSymbol", "]", "&&", "value", "[", "isValueLikeSymbol", "]", "!==", "false", "&&", "(", "options", ".", "foundAt", "||", "!", "is...
compute value reader
[ "compute", "value", "reader" ]
909fd944f108f754b63c5e4a3f3021db0e6e6c60
https://github.com/canjs/can-stache-key/blob/909fd944f108f754b63c5e4a3f3021db0e6e6c60/can-stache-key.js#L185-L187
31,576
canjs/can-stache-key
can-stache-key.js
function(parent, key, value, options) { var keys = typeof key === "string" ? observeReader.reads(key) : key; var last; options = options || {}; if(keys.length > 1) { last = keys.pop(); parent = observeReader.read(parent, keys, options).value; keys.push(last); } else { last = keys[0]; } if(!parent) { return; } var keyValue = peek(parent, last.key); // here's where we need to figure out the best way to write // if property being set points at a compute, set the compute if( observeReader.valueReadersMap.isValueLike.test(keyValue, keys.length - 1, keys, options) ) { observeReader.valueReadersMap.isValueLike.write(keyValue, value, options); } else { if(observeReader.valueReadersMap.isValueLike.test(parent, keys.length - 1, keys, options) ) { parent = parent[getValueSymbol](); } if(observeReader.propertyReadersMap.map.test(parent)) { observeReader.propertyReadersMap.map.write(parent, last.key, value, options); } else if(observeReader.propertyReadersMap.object.test(parent)) { observeReader.propertyReadersMap.object.write(parent, last.key, value, options); if(options.observation) { options.observation.update(); } } } }
javascript
function(parent, key, value, options) { var keys = typeof key === "string" ? observeReader.reads(key) : key; var last; options = options || {}; if(keys.length > 1) { last = keys.pop(); parent = observeReader.read(parent, keys, options).value; keys.push(last); } else { last = keys[0]; } if(!parent) { return; } var keyValue = peek(parent, last.key); // here's where we need to figure out the best way to write // if property being set points at a compute, set the compute if( observeReader.valueReadersMap.isValueLike.test(keyValue, keys.length - 1, keys, options) ) { observeReader.valueReadersMap.isValueLike.write(keyValue, value, options); } else { if(observeReader.valueReadersMap.isValueLike.test(parent, keys.length - 1, keys, options) ) { parent = parent[getValueSymbol](); } if(observeReader.propertyReadersMap.map.test(parent)) { observeReader.propertyReadersMap.map.write(parent, last.key, value, options); } else if(observeReader.propertyReadersMap.object.test(parent)) { observeReader.propertyReadersMap.object.write(parent, last.key, value, options); if(options.observation) { options.observation.update(); } } } }
[ "function", "(", "parent", ",", "key", ",", "value", ",", "options", ")", "{", "var", "keys", "=", "typeof", "key", "===", "\"string\"", "?", "observeReader", ".", "reads", "(", "key", ")", ":", "key", ";", "var", "last", ";", "options", "=", "option...
This should be able to set a property similar to how read works.
[ "This", "should", "be", "able", "to", "set", "a", "property", "similar", "to", "how", "read", "works", "." ]
909fd944f108f754b63c5e4a3f3021db0e6e6c60
https://github.com/canjs/can-stache-key/blob/909fd944f108f754b63c5e4a3f3021db0e6e6c60/can-stache-key.js#L306-L341
31,577
kalamuna/metalsmith-assets-convention
index.js
assetFile
function assetFile(filename, callback) { const data = { source: files[filename].source, destination: files[filename].destination || path.join(path.dirname(filename), '.') } delete files[filename] metalsmithAssets(data)(files, metalsmith, callback) }
javascript
function assetFile(filename, callback) { const data = { source: files[filename].source, destination: files[filename].destination || path.join(path.dirname(filename), '.') } delete files[filename] metalsmithAssets(data)(files, metalsmith, callback) }
[ "function", "assetFile", "(", "filename", ",", "callback", ")", "{", "const", "data", "=", "{", "source", ":", "files", "[", "filename", "]", ".", "source", ",", "destination", ":", "files", "[", "filename", "]", ".", "destination", "||", "path", ".", ...
Tell Metalsmith Assets to process the data. @param {string} filename The file to filter on. @param {function} callback A asyncronous callback that's made once the processing is complete.
[ "Tell", "Metalsmith", "Assets", "to", "process", "the", "data", "." ]
8e23ae8e96fb26c446d1989a84be8469c266580e
https://github.com/kalamuna/metalsmith-assets-convention/blob/8e23ae8e96fb26c446d1989a84be8469c266580e/index.js#L36-L43
31,578
bigchaindb/js-utility-belt
src/safe_merge.js
doesObjectListHaveDuplicates
function doesObjectListHaveDuplicates(l) { const mergedList = l.reduce((merged, obj) => ( obj ? merged.concat(Object.keys(obj)) : merged ), []); // Taken from: http://stackoverflow.com/a/7376645/1263876 // By casting the array to a Set, and then checking if the size of the array // shrunk in the process of casting, we can check if there were any duplicates return new Set(mergedList).size !== mergedList.length; }
javascript
function doesObjectListHaveDuplicates(l) { const mergedList = l.reduce((merged, obj) => ( obj ? merged.concat(Object.keys(obj)) : merged ), []); // Taken from: http://stackoverflow.com/a/7376645/1263876 // By casting the array to a Set, and then checking if the size of the array // shrunk in the process of casting, we can check if there were any duplicates return new Set(mergedList).size !== mergedList.length; }
[ "function", "doesObjectListHaveDuplicates", "(", "l", ")", "{", "const", "mergedList", "=", "l", ".", "reduce", "(", "(", "merged", ",", "obj", ")", "=>", "(", "obj", "?", "merged", ".", "concat", "(", "Object", ".", "keys", "(", "obj", ")", ")", ":"...
Checks a list of objects for key duplicates and returns a boolean
[ "Checks", "a", "list", "of", "objects", "for", "key", "duplicates", "and", "returns", "a", "boolean" ]
765cd85bb6d811fa3892c4e89752bfab1f1b825c
https://github.com/bigchaindb/js-utility-belt/blob/765cd85bb6d811fa3892c4e89752bfab1f1b825c/src/safe_merge.js#L21-L30
31,579
bigchaindb/js-utility-belt
src/safe_invoke.js
safeInvokeForConfig
function safeInvokeForConfig({ fn, context, params, onNotInvoked }) { if (typeof fn === 'function') { let fnParams = params; if (typeof params === 'function') { fnParams = params(); } // Warn if params or lazily evaluated params were given but not in an array if (fnParams != null && !Array.isArray(fnParams)) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.warn("Params to pass into safeInvoke's fn is not an array. Ignoring...", fnParams); } fnParams = null; } return { invoked: true, result: fn.apply(context, fnParams) }; } else { if (typeof onNotInvoked === 'function') { onNotInvoked(); } return { invoked: false }; } }
javascript
function safeInvokeForConfig({ fn, context, params, onNotInvoked }) { if (typeof fn === 'function') { let fnParams = params; if (typeof params === 'function') { fnParams = params(); } // Warn if params or lazily evaluated params were given but not in an array if (fnParams != null && !Array.isArray(fnParams)) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.warn("Params to pass into safeInvoke's fn is not an array. Ignoring...", fnParams); } fnParams = null; } return { invoked: true, result: fn.apply(context, fnParams) }; } else { if (typeof onNotInvoked === 'function') { onNotInvoked(); } return { invoked: false }; } }
[ "function", "safeInvokeForConfig", "(", "{", "fn", ",", "context", ",", "params", ",", "onNotInvoked", "}", ")", "{", "if", "(", "typeof", "fn", "===", "'function'", ")", "{", "let", "fnParams", "=", "params", ";", "if", "(", "typeof", "params", "===", ...
Abstraction for safeInvoke's two call signatures
[ "Abstraction", "for", "safeInvoke", "s", "two", "call", "signatures" ]
765cd85bb6d811fa3892c4e89752bfab1f1b825c
https://github.com/bigchaindb/js-utility-belt/blob/765cd85bb6d811fa3892c4e89752bfab1f1b825c/src/safe_invoke.js#L52-L81
31,580
gdbots/pbj-js
src/Message.js
populateDefault
function populateDefault(message, field) { const fieldName = field.getName(); if (message.has(fieldName)) { return true; } const defaultValue = field.getDefault(message); if (defaultValue === null) { return false; } const msg = msgs.get(message); if (field.isASingleValue()) { msg.data.set(fieldName, defaultValue); msg.clearedFields.delete(fieldName); return true; } if (isEmpty(defaultValue)) { return false; } if (field.isASet()) { message.addToSet(fieldName, Array.from(defaultValue)); return true; } msg.data.set(fieldName, defaultValue); msg.clearedFields.delete(fieldName); return true; }
javascript
function populateDefault(message, field) { const fieldName = field.getName(); if (message.has(fieldName)) { return true; } const defaultValue = field.getDefault(message); if (defaultValue === null) { return false; } const msg = msgs.get(message); if (field.isASingleValue()) { msg.data.set(fieldName, defaultValue); msg.clearedFields.delete(fieldName); return true; } if (isEmpty(defaultValue)) { return false; } if (field.isASet()) { message.addToSet(fieldName, Array.from(defaultValue)); return true; } msg.data.set(fieldName, defaultValue); msg.clearedFields.delete(fieldName); return true; }
[ "function", "populateDefault", "(", "message", ",", "field", ")", "{", "const", "fieldName", "=", "field", ".", "getName", "(", ")", ";", "if", "(", "message", ".", "has", "(", "fieldName", ")", ")", "{", "return", "true", ";", "}", "const", "defaultVa...
Populates the default on a single field if it's not already set and the default generated is not a null value or empty array. @param {Message} message @param {Field} field @returns {boolean} Returns true if a non null/empty default was applied or already present.
[ "Populates", "the", "default", "on", "a", "single", "field", "if", "it", "s", "not", "already", "set", "and", "the", "default", "generated", "is", "not", "a", "null", "value", "or", "empty", "array", "." ]
729db944d45d170cd32814f7c18d914072d8e21d
https://github.com/gdbots/pbj-js/blob/729db944d45d170cd32814f7c18d914072d8e21d/src/Message.js#L58-L89
31,581
steelbrain/jasmine-fix
index.js
resetClock
function resetClock() { for (const key in jasmine.Clock.real) { if (jasmine.Clock.real.hasOwnProperty(key)) { window[key] = jasmine.Clock.real[key] } } }
javascript
function resetClock() { for (const key in jasmine.Clock.real) { if (jasmine.Clock.real.hasOwnProperty(key)) { window[key] = jasmine.Clock.real[key] } } }
[ "function", "resetClock", "(", ")", "{", "for", "(", "const", "key", "in", "jasmine", ".", "Clock", ".", "real", ")", "{", "if", "(", "jasmine", ".", "Clock", ".", "real", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "window", "[", "key", "]",...
Jasmine 1.3.x has no sane way of resetting to native clocks, and since we're gonna test promises and such, we're gonna need it
[ "Jasmine", "1", ".", "3", ".", "x", "has", "no", "sane", "way", "of", "resetting", "to", "native", "clocks", "and", "since", "we", "re", "gonna", "test", "promises", "and", "such", "we", "re", "gonna", "need", "it" ]
c7bc55cc9d6de1f4493f3f7a1930c60b80c00557
https://github.com/steelbrain/jasmine-fix/blob/c7bc55cc9d6de1f4493f3f7a1930c60b80c00557/index.js#L17-L23
31,582
nzakas/cssurl
Makefile.js
nodeExec
function nodeExec() { var exitCode = nodeCLI.exec.apply(nodeCLI, arguments).code; if (exitCode > 0) { exit(1); } }
javascript
function nodeExec() { var exitCode = nodeCLI.exec.apply(nodeCLI, arguments).code; if (exitCode > 0) { exit(1); } }
[ "function", "nodeExec", "(", ")", "{", "var", "exitCode", "=", "nodeCLI", ".", "exec", ".", "apply", "(", "nodeCLI", ",", "arguments", ")", ".", "code", ";", "if", "(", "exitCode", ">", "0", ")", "{", "exit", "(", "1", ")", ";", "}", "}" ]
Executes a Node command and exits if the exit code isn't 0. @returns {void} @private
[ "Executes", "a", "Node", "command", "and", "exits", "if", "the", "exit", "code", "isn", "t", "0", "." ]
ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2
https://github.com/nzakas/cssurl/blob/ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2/Makefile.js#L55-L60
31,583
nzakas/cssurl
lib/url-translator.js
function(url, fromFilename, toFilename) { if (!SKIP_URLS.test(url)) { var fromDirname = path.dirname(fromFilename), toDirname = path.dirname(toFilename), fromPath = path.resolve(fromDirname, url), toPath = path.resolve(toDirname); return path.relative(toPath, fromPath).replace(/\\/g, "/"); } else { return url; } }
javascript
function(url, fromFilename, toFilename) { if (!SKIP_URLS.test(url)) { var fromDirname = path.dirname(fromFilename), toDirname = path.dirname(toFilename), fromPath = path.resolve(fromDirname, url), toPath = path.resolve(toDirname); return path.relative(toPath, fromPath).replace(/\\/g, "/"); } else { return url; } }
[ "function", "(", "url", ",", "fromFilename", ",", "toFilename", ")", "{", "if", "(", "!", "SKIP_URLS", ".", "test", "(", "url", ")", ")", "{", "var", "fromDirname", "=", "path", ".", "dirname", "(", "fromFilename", ")", ",", "toDirname", "=", "path", ...
Translates a given relative URL with consideration that the reference is relative to a specific CSS file, and that CSS file location is changing. @param {string} url The URL to translate. @param {string} fromFilename The original filename for the CSS. @param {string} toFilename The new filename for the CSS. @returns {string} The CSS code with the URLs translated.
[ "Translates", "a", "given", "relative", "URL", "with", "consideration", "that", "the", "reference", "is", "relative", "to", "a", "specific", "CSS", "file", "and", "that", "CSS", "file", "location", "is", "changing", "." ]
ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2
https://github.com/nzakas/cssurl/blob/ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2/lib/url-translator.js#L41-L54
31,584
nzakas/cssurl
lib/url-rewriter.js
function(code) { var tokens = new TokenStream(code), hasCRLF = code.indexOf("\r") > -1, lines = code.split(/\r?\n/), line, token, tt, replacement, colAdjust = 0, lastLine = 0; while ((tt = tokens.get()) !== 0) { token = tokens.token(); if (tt === Tokens.URI) { // URI if (lastLine !== token.startLine) { colAdjust = 0; lastLine = token.startLine; } replacement = this.replacer(token.value.replace(URL_PARENS, "")); // 5 is for url() characters line = lines[token.startLine - 1]; lines[token.startLine - 1] = line.substring(0, token.startCol + colAdjust - 1) + "url(" + replacement + ")" + line.substring(token.endCol + colAdjust - 1); colAdjust += ((replacement.length + 5) - token.value.length); } } return lines.join(hasCRLF ? "\r\n" : "\n"); }
javascript
function(code) { var tokens = new TokenStream(code), hasCRLF = code.indexOf("\r") > -1, lines = code.split(/\r?\n/), line, token, tt, replacement, colAdjust = 0, lastLine = 0; while ((tt = tokens.get()) !== 0) { token = tokens.token(); if (tt === Tokens.URI) { // URI if (lastLine !== token.startLine) { colAdjust = 0; lastLine = token.startLine; } replacement = this.replacer(token.value.replace(URL_PARENS, "")); // 5 is for url() characters line = lines[token.startLine - 1]; lines[token.startLine - 1] = line.substring(0, token.startCol + colAdjust - 1) + "url(" + replacement + ")" + line.substring(token.endCol + colAdjust - 1); colAdjust += ((replacement.length + 5) - token.value.length); } } return lines.join(hasCRLF ? "\r\n" : "\n"); }
[ "function", "(", "code", ")", "{", "var", "tokens", "=", "new", "TokenStream", "(", "code", ")", ",", "hasCRLF", "=", "code", ".", "indexOf", "(", "\"\\r\"", ")", ">", "-", "1", ",", "lines", "=", "code", ".", "split", "(", "/", "\\r?\\n", "/", "...
Rewrites the given CSS code using the replacer. @param {string} code The CSS code to rewrite. @returns {string} The CSS code with the URLs replaced.
[ "Rewrites", "the", "given", "CSS", "code", "using", "the", "replacer", "." ]
ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2
https://github.com/nzakas/cssurl/blob/ee60a35eb5db0749d7ae75a7e7b8f3fcb2953dc2/lib/url-rewriter.js#L51-L84
31,585
justan/twei
lib/util.js
open
function open(url, callback){ var cmd, exec = require('child_process').exec; switch(process.platform){ case 'darwin': cmd = 'open'; break; case 'win32': case 'win64': cmd = 'start ""';//加空的双引号可以打开带有 "&" 的地址 break; case 'cygwin': cmd = 'cygstart'; break; default: cmd = 'xdg-open'; break; } cmd = cmd + ' ' + url + ''; return exec(cmd, callback); }
javascript
function open(url, callback){ var cmd, exec = require('child_process').exec; switch(process.platform){ case 'darwin': cmd = 'open'; break; case 'win32': case 'win64': cmd = 'start ""';//加空的双引号可以打开带有 "&" 的地址 break; case 'cygwin': cmd = 'cygstart'; break; default: cmd = 'xdg-open'; break; } cmd = cmd + ' ' + url + ''; return exec(cmd, callback); }
[ "function", "open", "(", "url", ",", "callback", ")", "{", "var", "cmd", ",", "exec", "=", "require", "(", "'child_process'", ")", ".", "exec", ";", "switch", "(", "process", ".", "platform", ")", "{", "case", "'darwin'", ":", "cmd", "=", "'open'", "...
open a url
[ "open", "a", "url" ]
ebc55e78dc315db49cc7d8fe924e68bdea0169f3
https://github.com/justan/twei/blob/ebc55e78dc315db49cc7d8fe924e68bdea0169f3/lib/util.js#L249-L268
31,586
justan/twei
lib/alias.js
aliasExpand
function aliasExpand(cmdmap){ var cmds = {} , twei = require('../') , alias, apiGroup ; for(var key in cmdmap){ alias = cmdmap[key]; if(alias.alias){ if(Array.isArray(alias.alias)){ for(var i = 0, l = alias.alias.length; i < l; i++){ cmds[alias.alias[i]] = cmdmap[key].cmd; } }else{ cmds[alias.alias] = cmdmap[key].cmd; } cmds[key] = cmdmap[key].cmd; delete alias.alias; }else{ cmds[key] = cmdmap[key].cmd || cmdmap[key]; } if(alias.apis && typeof (apiGroup = twei.getApiGroup(alias.apis)) == 'object'){ for(var apiName in apiGroup){ if(!cmds[key + '.' + apiName]){ cmds[key + '.' + apiName] = 'execute ' + alias.apis + '.' + apiName; } } } } //console.log(cmds); return cmds; }
javascript
function aliasExpand(cmdmap){ var cmds = {} , twei = require('../') , alias, apiGroup ; for(var key in cmdmap){ alias = cmdmap[key]; if(alias.alias){ if(Array.isArray(alias.alias)){ for(var i = 0, l = alias.alias.length; i < l; i++){ cmds[alias.alias[i]] = cmdmap[key].cmd; } }else{ cmds[alias.alias] = cmdmap[key].cmd; } cmds[key] = cmdmap[key].cmd; delete alias.alias; }else{ cmds[key] = cmdmap[key].cmd || cmdmap[key]; } if(alias.apis && typeof (apiGroup = twei.getApiGroup(alias.apis)) == 'object'){ for(var apiName in apiGroup){ if(!cmds[key + '.' + apiName]){ cmds[key + '.' + apiName] = 'execute ' + alias.apis + '.' + apiName; } } } } //console.log(cmds); return cmds; }
[ "function", "aliasExpand", "(", "cmdmap", ")", "{", "var", "cmds", "=", "{", "}", ",", "twei", "=", "require", "(", "'../'", ")", ",", "alias", ",", "apiGroup", ";", "for", "(", "var", "key", "in", "cmdmap", ")", "{", "alias", "=", "cmdmap", "[", ...
restore alias to core command @param {Object} cmdmap aliasmap @return {Object} 返回完整的 名称:命令 对象 Example: { update: ''execute status.update'' , user: 'execute user.show' , whois: 'execute user.show' }
[ "restore", "alias", "to", "core", "command" ]
ebc55e78dc315db49cc7d8fe924e68bdea0169f3
https://github.com/justan/twei/blob/ebc55e78dc315db49cc7d8fe924e68bdea0169f3/lib/alias.js#L84-L116
31,587
thlorenz/spok
spok.js
needRecurseArray
function needRecurseArray(arr) { for (var i = 0; i < arr.length; i++) { var el = arr[i] if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true } return false }
javascript
function needRecurseArray(arr) { for (var i = 0; i < arr.length; i++) { var el = arr[i] if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true } return false }
[ "function", "needRecurseArray", "(", "arr", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "var", "el", "=", "arr", "[", "i", "]", "if", "(", "typeof", "el", "!==", "'number'", "&&", ...
only recurse into arrays if they contain actual specs or objects
[ "only", "recurse", "into", "arrays", "if", "they", "contain", "actual", "specs", "or", "objects" ]
f1da9034d4f186bd0a23b0562a8843a343dd81fe
https://github.com/thlorenz/spok/blob/f1da9034d4f186bd0a23b0562a8843a343dd81fe/spok.js#L6-L12
31,588
eladnava/material-letter-icons
lib/generator.js
generateLetterIcon
function generateLetterIcon(letter, cb) { // Derive SVG from base letter SVG var letterSVG = baseSVG; // Get a random Material Design color var color = getRandomLetterColor(); // Substitude placeholders for color and letter letterSVG = letterSVG.replace('{c}', color); letterSVG = letterSVG.replace('{x}', letter); // Get filesystem-friendly file name for letter var fileName = getIconFilename(letter); // Define SVG/PNG output path var outputSVGPath = rootDir + config.dist.path + config.dist.svg.outputPath + fileName + '.svg'; var outputPNGPath = rootDir + config.dist.path + config.dist.png.outputPath + fileName + '.png'; // Export the letter as an SVG file fs.writeFileSync(outputSVGPath, letterSVG); // Convert the SVG file into a PNG file using svg2png svg2png(new Buffer(letterSVG), config.dist.png.dimensions) .then(function (buffer) { // Write to disk fs.writeFileSync(outputPNGPath, buffer); // Success cb(); }).catch(function (err) { // Report error return cb(err); }); }
javascript
function generateLetterIcon(letter, cb) { // Derive SVG from base letter SVG var letterSVG = baseSVG; // Get a random Material Design color var color = getRandomLetterColor(); // Substitude placeholders for color and letter letterSVG = letterSVG.replace('{c}', color); letterSVG = letterSVG.replace('{x}', letter); // Get filesystem-friendly file name for letter var fileName = getIconFilename(letter); // Define SVG/PNG output path var outputSVGPath = rootDir + config.dist.path + config.dist.svg.outputPath + fileName + '.svg'; var outputPNGPath = rootDir + config.dist.path + config.dist.png.outputPath + fileName + '.png'; // Export the letter as an SVG file fs.writeFileSync(outputSVGPath, letterSVG); // Convert the SVG file into a PNG file using svg2png svg2png(new Buffer(letterSVG), config.dist.png.dimensions) .then(function (buffer) { // Write to disk fs.writeFileSync(outputPNGPath, buffer); // Success cb(); }).catch(function (err) { // Report error return cb(err); }); }
[ "function", "generateLetterIcon", "(", "letter", ",", "cb", ")", "{", "// Derive SVG from base letter SVG", "var", "letterSVG", "=", "baseSVG", ";", "// Get a random Material Design color", "var", "color", "=", "getRandomLetterColor", "(", ")", ";", "// Substitude placeho...
Generates icons for a single letter
[ "Generates", "icons", "for", "a", "single", "letter" ]
f425b38e81a570795a78b7baa3638100be2c0edb
https://github.com/eladnava/material-letter-icons/blob/f425b38e81a570795a78b7baa3638100be2c0edb/lib/generator.js#L60-L93
31,589
eladnava/material-letter-icons
lib/generator.js
getRandomLetterColor
function getRandomLetterColor() { // Reset index if we're at the end of the array if (currentColorIndex >= colorKeys.length) { currentColorIndex = 0; } // Get current color and increment index for next time var currentColorKey = colorKeys[currentColorIndex++]; // Return most satured color hex (a700 or 900) var color = colors[currentColorKey]['a700'] || colors[currentColorKey]['900']; // Invalid color saturation value? if (color == undefined) { // No saturation for black or white, // so return the next random color instead return getRandomLetterColor(); } // Return current color hex return color; }
javascript
function getRandomLetterColor() { // Reset index if we're at the end of the array if (currentColorIndex >= colorKeys.length) { currentColorIndex = 0; } // Get current color and increment index for next time var currentColorKey = colorKeys[currentColorIndex++]; // Return most satured color hex (a700 or 900) var color = colors[currentColorKey]['a700'] || colors[currentColorKey]['900']; // Invalid color saturation value? if (color == undefined) { // No saturation for black or white, // so return the next random color instead return getRandomLetterColor(); } // Return current color hex return color; }
[ "function", "getRandomLetterColor", "(", ")", "{", "// Reset index if we're at the end of the array", "if", "(", "currentColorIndex", ">=", "colorKeys", ".", "length", ")", "{", "currentColorIndex", "=", "0", ";", "}", "// Get current color and increment index for next time",...
Returns the next Material Design color for the icon background
[ "Returns", "the", "next", "Material", "Design", "color", "for", "the", "icon", "background" ]
f425b38e81a570795a78b7baa3638100be2c0edb
https://github.com/eladnava/material-letter-icons/blob/f425b38e81a570795a78b7baa3638100be2c0edb/lib/generator.js#L108-L129
31,590
TechGapItalia/angular-vertical-timeline
gulpfile.js
compileSass
function compileSass(path, ext, file, callback) { let compiledCss = sass.renderSync({ file: path, outputStyle: 'compressed', }); callback(null, compiledCss.css); }
javascript
function compileSass(path, ext, file, callback) { let compiledCss = sass.renderSync({ file: path, outputStyle: 'compressed', }); callback(null, compiledCss.css); }
[ "function", "compileSass", "(", "path", ",", "ext", ",", "file", ",", "callback", ")", "{", "let", "compiledCss", "=", "sass", ".", "renderSync", "(", "{", "file", ":", "path", ",", "outputStyle", ":", "'compressed'", ",", "}", ")", ";", "callback", "(...
Compile SASS to CSS. @see https://github.com/ludohenin/gulp-inline-ng2-template @see https://github.com/sass/node-sass
[ "Compile", "SASS", "to", "CSS", "." ]
b1dfaea814b6ff3302efd9d9f85ece6cbcceb6fa
https://github.com/TechGapItalia/angular-vertical-timeline/blob/b1dfaea814b6ff3302efd9d9f85ece6cbcceb6fa/gulpfile.js#L69-L75
31,591
anvaka/rafor
index.js
asyncFor
function asyncFor(array, visitCallback, doneCallback, options) { var start = 0; var elapsed = 0; options = options || {}; var step = options.step || 1; var maxTimeMS = options.maxTimeMS || 8; var pointsPerLoopCycle = options.probeElements || 5000; // we should never block main thread for too long... setTimeout(processSubset, 0); function processSubset() { var finish = Math.min(array.length, start + pointsPerLoopCycle); var i = start; var timeStart = new Date(); for (i = start; i < finish; i += step) { visitCallback(array[i], i, array); } if (i < array.length) { elapsed += (new Date() - timeStart); start = i; pointsPerLoopCycle = Math.round(start * maxTimeMS/elapsed); setTimeout(processSubset, 0); } else { doneCallback(array); } } }
javascript
function asyncFor(array, visitCallback, doneCallback, options) { var start = 0; var elapsed = 0; options = options || {}; var step = options.step || 1; var maxTimeMS = options.maxTimeMS || 8; var pointsPerLoopCycle = options.probeElements || 5000; // we should never block main thread for too long... setTimeout(processSubset, 0); function processSubset() { var finish = Math.min(array.length, start + pointsPerLoopCycle); var i = start; var timeStart = new Date(); for (i = start; i < finish; i += step) { visitCallback(array[i], i, array); } if (i < array.length) { elapsed += (new Date() - timeStart); start = i; pointsPerLoopCycle = Math.round(start * maxTimeMS/elapsed); setTimeout(processSubset, 0); } else { doneCallback(array); } } }
[ "function", "asyncFor", "(", "array", ",", "visitCallback", ",", "doneCallback", ",", "options", ")", "{", "var", "start", "=", "0", ";", "var", "elapsed", "=", "0", ";", "options", "=", "options", "||", "{", "}", ";", "var", "step", "=", "options", ...
Iterates over array in async manner. This function attempts to maximize number of elements visited within single event loop cycle, while at the same time tries to not exceed a time threshold allowed to stay within event loop. @param {Array} array which needs to be iterated. Array-like objects are OK too. @param {VisitCalback} visitCallback called for every element within for loop. @param {DoneCallback} doneCallback called when iterator has reached end of array. @param {Object=} options - additional configuration: @param {number} [options.step=1] - default iteration step @param {number} [options.maxTimeMS=8] - maximum time (in milliseconds) which iterator should spend within single event loop. @param {number} [options.probeElements=5000] - how many elements should iterator visit to measure its iteration speed.
[ "Iterates", "over", "array", "in", "async", "manner", ".", "This", "function", "attempts", "to", "maximize", "number", "of", "elements", "visited", "within", "single", "event", "loop", "cycle", "while", "at", "the", "same", "time", "tries", "to", "not", "exc...
b322a2842a07fadcb993d5d37cbe3880fe4de715
https://github.com/anvaka/rafor/blob/b322a2842a07fadcb993d5d37cbe3880fe4de715/index.js#L19-L46
31,592
ursudio/leaflet-webgl-heatmap
src/leaflet-webgl-heatmap.js
function () { delete this.gl; L.DomUtil.remove(this._container); L.DomEvent.off(this._container); delete this._container; }
javascript
function () { delete this.gl; L.DomUtil.remove(this._container); L.DomEvent.off(this._container); delete this._container; }
[ "function", "(", ")", "{", "delete", "this", ".", "gl", ";", "L", ".", "DomUtil", ".", "remove", "(", "this", ".", "_container", ")", ";", "L", ".", "DomEvent", ".", "off", "(", "this", ".", "_container", ")", ";", "delete", "this", ".", "_containe...
onRemove-ish
[ "onRemove", "-", "ish" ]
52f954982b4289cbba3c6cd2cf4e373fcb4584b7
https://github.com/ursudio/leaflet-webgl-heatmap/blob/52f954982b4289cbba3c6cd2cf4e373fcb4584b7/src/leaflet-webgl-heatmap.js#L68-L73
31,593
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
Container
function Container(parent) { this.parent = parent; this.children = []; this.resolver = parent && parent.resolver || function() {}; this.registry = dictionary(parent ? parent.registry : null); this.cache = dictionary(parent ? parent.cache : null); this.factoryCache = dictionary(parent ? parent.factoryCache : null); this.resolveCache = dictionary(parent ? parent.resolveCache : null); this.typeInjections = dictionary(parent ? parent.typeInjections : null); this.injections = dictionary(null); this.normalizeCache = dictionary(null); this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null); this.factoryInjections = dictionary(null); this._options = dictionary(parent ? parent._options : null); this._typeOptions = dictionary(parent ? parent._typeOptions : null); }
javascript
function Container(parent) { this.parent = parent; this.children = []; this.resolver = parent && parent.resolver || function() {}; this.registry = dictionary(parent ? parent.registry : null); this.cache = dictionary(parent ? parent.cache : null); this.factoryCache = dictionary(parent ? parent.factoryCache : null); this.resolveCache = dictionary(parent ? parent.resolveCache : null); this.typeInjections = dictionary(parent ? parent.typeInjections : null); this.injections = dictionary(null); this.normalizeCache = dictionary(null); this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null); this.factoryInjections = dictionary(null); this._options = dictionary(parent ? parent._options : null); this._typeOptions = dictionary(parent ? parent._typeOptions : null); }
[ "function", "Container", "(", "parent", ")", "{", "this", ".", "parent", "=", "parent", ";", "this", ".", "children", "=", "[", "]", ";", "this", ".", "resolver", "=", "parent", "&&", "parent", ".", "resolver", "||", "function", "(", ")", "{", "}", ...
A lightweight container that helps to assemble and decouple components. Public api for the container is still in flux. The public api, specified on the application namespace should be considered the stable api.
[ "A", "lightweight", "container", "that", "helps", "to", "assemble", "and", "decouple", "components", ".", "Public", "api", "for", "the", "container", "is", "still", "in", "flux", ".", "The", "public", "api", "specified", "on", "the", "application", "namespace"...
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1127-L1146
31,594
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(fullName, factory, options) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (factory === undefined) { throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`'); } var normalizedName = this.normalize(fullName); if (normalizedName in this.cache) { throw new Error('Cannot re-register: `' + fullName +'`, as it has already been looked up.'); } this.registry[normalizedName] = factory; this._options[normalizedName] = (options || {}); }
javascript
function(fullName, factory, options) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (factory === undefined) { throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`'); } var normalizedName = this.normalize(fullName); if (normalizedName in this.cache) { throw new Error('Cannot re-register: `' + fullName +'`, as it has already been looked up.'); } this.registry[normalizedName] = factory; this._options[normalizedName] = (options || {}); }
[ "function", "(", "fullName", ",", "factory", ",", "options", ")", "{", "Ember", ".", "assert", "(", "'fullName must be a proper full name'", ",", "validateFullName", "(", "fullName", ")", ")", ";", "if", "(", "factory", "===", "undefined", ")", "{", "throw", ...
Registers a factory for later injection. Example: ```javascript var container = new Container(); container.register('model:user', Person, {singleton: false }); container.register('fruit:favorite', Orange); container.register('communication:main', Email, {singleton: false}); ``` @method register @param {String} fullName @param {Function} factory @param {Object} options
[ "Registers", "a", "factory", "for", "later", "injection", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1257-L1272
31,595
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(fullName) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); var normalizedName = this.normalize(fullName); delete this.registry[normalizedName]; delete this.cache[normalizedName]; delete this.factoryCache[normalizedName]; delete this.resolveCache[normalizedName]; delete this._options[normalizedName]; }
javascript
function(fullName) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); var normalizedName = this.normalize(fullName); delete this.registry[normalizedName]; delete this.cache[normalizedName]; delete this.factoryCache[normalizedName]; delete this.resolveCache[normalizedName]; delete this._options[normalizedName]; }
[ "function", "(", "fullName", ")", "{", "Ember", ".", "assert", "(", "'fullName must be a proper full name'", ",", "validateFullName", "(", "fullName", ")", ")", ";", "var", "normalizedName", "=", "this", ".", "normalize", "(", "fullName", ")", ";", "delete", "...
Unregister a fullName ```javascript var container = new Container(); container.register('model:user', User); container.lookup('model:user') instanceof User //=> true container.unregister('model:user') container.lookup('model:user') === undefined //=> true ``` @method unregister @param {String} fullName
[ "Unregister", "a", "fullName" ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1290-L1300
31,596
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(fullName, options) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); return lookup(this, this.normalize(fullName), options); }
javascript
function(fullName, options) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); return lookup(this, this.normalize(fullName), options); }
[ "function", "(", "fullName", ",", "options", ")", "{", "Ember", ".", "assert", "(", "'fullName must be a proper full name'", ",", "validateFullName", "(", "fullName", ")", ")", ";", "return", "lookup", "(", "this", ",", "this", ".", "normalize", "(", "fullName...
Given a fullName return a corresponding instance. The default behaviour is for lookup to return a singleton instance. The singleton is scoped to the container, allowing multiple containers to all have their own locally scoped singletons. ```javascript var container = new Container(); container.register('api:twitter', Twitter); var twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true by default the container will return singletons var twitter2 = container.lookup('api:twitter'); twitter2 instanceof Twitter; // => true twitter === twitter2; //=> true ``` If singletons are not wanted an optional flag can be provided at lookup. ```javascript var container = new Container(); container.register('api:twitter', Twitter); var twitter = container.lookup('api:twitter', { singleton: false }); var twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` @method lookup @param {String} fullName @param {Object} options @return {any}
[ "Given", "a", "fullName", "return", "a", "corresponding", "instance", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1429-L1432
31,597
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(type, property, fullName) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (this.parent) { illegalChildOperation('typeInjection'); } var fullNameType = fullName.split(':')[0]; if (fullNameType === type) { throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s). Register the `' + fullName + '` as a different type and perform the typeInjection.'); } addTypeInjection(this.typeInjections, type, property, fullName); }
javascript
function(type, property, fullName) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (this.parent) { illegalChildOperation('typeInjection'); } var fullNameType = fullName.split(':')[0]; if (fullNameType === type) { throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s). Register the `' + fullName + '` as a different type and perform the typeInjection.'); } addTypeInjection(this.typeInjections, type, property, fullName); }
[ "function", "(", "type", ",", "property", ",", "fullName", ")", "{", "Ember", ".", "assert", "(", "'fullName must be a proper full name'", ",", "validateFullName", "(", "fullName", ")", ")", ";", "if", "(", "this", ".", "parent", ")", "{", "illegalChildOperati...
Used only via `injection`. Provides a specialized form of injection, specifically enabling all objects of one type to be injected with a reference to another object. For example, provided each object of type `controller` needed a `router`. one would do the following: ```javascript var container = new Container(); container.register('router:main', Router); container.register('controller:user', UserController); container.register('controller:post', PostController); container.typeInjection('controller', 'router', 'router:main'); var user = container.lookup('controller:user'); var post = container.lookup('controller:post'); user.router instanceof Router; //=> true post.router instanceof Router; //=> true both controllers share the same router user.router === post.router; //=> true ``` @private @method typeInjection @param {String} type @param {String} property @param {String} fullName
[ "Used", "only", "via", "injection", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1536-L1547
31,598
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(fullName, property, injectionName) { if (this.parent) { illegalChildOperation('injection'); } var normalizedName = this.normalize(fullName); var normalizedInjectionName = this.normalize(injectionName); validateFullName(injectionName); if (fullName.indexOf(':') === -1) { return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName); } Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (this.factoryCache[normalizedName]) { throw new Error('Attempted to register a factoryInjection for a type that has already ' + 'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')'); } addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName); }
javascript
function(fullName, property, injectionName) { if (this.parent) { illegalChildOperation('injection'); } var normalizedName = this.normalize(fullName); var normalizedInjectionName = this.normalize(injectionName); validateFullName(injectionName); if (fullName.indexOf(':') === -1) { return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName); } Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (this.factoryCache[normalizedName]) { throw new Error('Attempted to register a factoryInjection for a type that has already ' + 'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')'); } addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName); }
[ "function", "(", "fullName", ",", "property", ",", "injectionName", ")", "{", "if", "(", "this", ".", "parent", ")", "{", "illegalChildOperation", "(", "'injection'", ")", ";", "}", "var", "normalizedName", "=", "this", ".", "normalize", "(", "fullName", "...
Defines factory injection rules. Similar to regular injection rules, but are run against factories, via `Container#lookupFactory`. These rules are used to inject objects onto factories when they are looked up. Two forms of injections are possible: Injecting one fullName on another fullName Injecting one fullName on a type Example: ```javascript var container = new Container(); container.register('store:main', Store); container.register('store:secondary', OtherStore); container.register('model:user', User); container.register('model:post', Post); injecting one fullName on another type container.factoryInjection('model', 'store', 'store:main'); injecting one fullName on another fullName container.factoryInjection('model:post', 'secondaryStore', 'store:secondary'); var UserFactory = container.lookupFactory('model:user'); var PostFactory = container.lookupFactory('model:post'); var store = container.lookup('store:main'); UserFactory.store instanceof Store; //=> true UserFactory.secondaryStore instanceof OtherStore; //=> false PostFactory.store instanceof Store; //=> true PostFactory.secondaryStore instanceof OtherStore; //=> true and both models share the same source instance UserFactory.store === PostFactory.store; //=> true ``` @method factoryInjection @param {String} factoryName @param {String} property @param {String} injectionName
[ "Defines", "factory", "injection", "rules", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1697-L1717
31,599
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function() { for (var i = 0, length = this.children.length; i < length; i++) { this.children[i].destroy(); } this.children = []; eachDestroyable(this, function(item) { item.destroy(); }); this.parent = undefined; this.isDestroyed = true; }
javascript
function() { for (var i = 0, length = this.children.length; i < length; i++) { this.children[i].destroy(); } this.children = []; eachDestroyable(this, function(item) { item.destroy(); }); this.parent = undefined; this.isDestroyed = true; }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "this", ".", "children", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "this", ".", "children", "[", "i", "]", ".", "destroy", "(", ")", ";",...
A depth first traversal, destroying the container, its descendant containers and all their managed objects. @method destroy
[ "A", "depth", "first", "traversal", "destroying", "the", "container", "its", "descendant", "containers", "and", "all", "their", "managed", "objects", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L1725-L1738