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,100
mozilla-jetpack/node-fx-runner
lib/utils.js
fallBack
function fallBack () { var programFilesVar = "ProgramFiles"; if (arch === "(64)") { console.warn("You are using 32-bit version of Firefox on 64-bit versions of the Windows.\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!") programFilesVar = "ProgramFiles(x86)"; } resolve(path.join(process.env[programFilesVar], appName, "firefox.exe")); }
javascript
function fallBack () { var programFilesVar = "ProgramFiles"; if (arch === "(64)") { console.warn("You are using 32-bit version of Firefox on 64-bit versions of the Windows.\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!") programFilesVar = "ProgramFiles(x86)"; } resolve(path.join(process.env[programFilesVar], appName, "firefox.exe")); }
[ "function", "fallBack", "(", ")", "{", "var", "programFilesVar", "=", "\"ProgramFiles\"", ";", "if", "(", "arch", "===", "\"(64)\"", ")", "{", "console", ".", "warn", "(", "\"You are using 32-bit version of Firefox on 64-bit versions of the Windows.\\nSome features may not ...
this is used when reading the registry goes wrong.
[ "this", "is", "used", "when", "reading", "the", "registry", "goes", "wrong", "." ]
71e3848b6adac1054829391c826fd88cfb28f621
https://github.com/mozilla-jetpack/node-fx-runner/blob/71e3848b6adac1054829391c826fd88cfb28f621/lib/utils.js#L74-L81
31,101
primus/substream
index.js
listen
function listen(event, spark) { if ('end' === event) return function end() { if (!spark.streams) return; for (var stream in spark.streams) { stream = spark.streams[stream]; if (stream.end) stream.end(); } }; if ('readyStateChange' === event) return function change(reason) { if (!spark.streams) return; for (var stream in spark.streams) { stream = spark.streams[stream]; stream.readyState = spark.readyState; if (stream.emit) emit.call(stream, event, reason); } }; return function proxy() { if (!spark.streams) return; var args = Array.prototype.slice.call(arguments, 0); for (var stream in spark.streams) { if (stream.emit) emit.call(stream, [event].concat(args)); } }; }
javascript
function listen(event, spark) { if ('end' === event) return function end() { if (!spark.streams) return; for (var stream in spark.streams) { stream = spark.streams[stream]; if (stream.end) stream.end(); } }; if ('readyStateChange' === event) return function change(reason) { if (!spark.streams) return; for (var stream in spark.streams) { stream = spark.streams[stream]; stream.readyState = spark.readyState; if (stream.emit) emit.call(stream, event, reason); } }; return function proxy() { if (!spark.streams) return; var args = Array.prototype.slice.call(arguments, 0); for (var stream in spark.streams) { if (stream.emit) emit.call(stream, [event].concat(args)); } }; }
[ "function", "listen", "(", "event", ",", "spark", ")", "{", "if", "(", "'end'", "===", "event", ")", "return", "function", "end", "(", ")", "{", "if", "(", "!", "spark", ".", "streams", ")", "return", ";", "for", "(", "var", "stream", "in", "spark"...
Return a preconfigured listener. @param {String} event Name of the event. @returns {Function} listener @api private
[ "Return", "a", "preconfigured", "listener", "." ]
626792b746e1dc90b67a81045f442ee1f584c0ec
https://github.com/primus/substream/blob/626792b746e1dc90b67a81045f442ee1f584c0ec/index.js#L25-L54
31,102
globality-corp/nodule-logging
src/logger.js
createLoggerStream
function createLoggerStream(name, level, logglyConfig) { const streams = [process.stdout]; if (logglyConfig.enabled) { const logglyStream = new LogglyStream({ token: logglyConfig.token, subdomain: logglyConfig.subdomain, name, environment: logglyConfig.environment, }); streams.push(logglyStream); } return new UnionStream({ streams }); }
javascript
function createLoggerStream(name, level, logglyConfig) { const streams = [process.stdout]; if (logglyConfig.enabled) { const logglyStream = new LogglyStream({ token: logglyConfig.token, subdomain: logglyConfig.subdomain, name, environment: logglyConfig.environment, }); streams.push(logglyStream); } return new UnionStream({ streams }); }
[ "function", "createLoggerStream", "(", "name", ",", "level", ",", "logglyConfig", ")", "{", "const", "streams", "=", "[", "process", ".", "stdout", "]", ";", "if", "(", "logglyConfig", ".", "enabled", ")", "{", "const", "logglyStream", "=", "new", "LogglyS...
singleton to create a logging instance based on config
[ "singleton", "to", "create", "a", "logging", "instance", "based", "on", "config" ]
5283de6c8bf8a2866f377aa82eca80bc3b30a5c3
https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/logger.js#L16-L28
31,103
wikimedia/restbase-mod-table-cassandra
lib/schemaMigration.js
confChanged
function confChanged(current, proposed) { if (stringify(current.conf) !== stringify(proposed.conf)) { if (current.version >= proposed.version) { const e = new Error('Schema change, but no version increment.'); e.current = current; e.proposed = proposed; throw e; } return true; } else { return false; } }
javascript
function confChanged(current, proposed) { if (stringify(current.conf) !== stringify(proposed.conf)) { if (current.version >= proposed.version) { const e = new Error('Schema change, but no version increment.'); e.current = current; e.proposed = proposed; throw e; } return true; } else { return false; } }
[ "function", "confChanged", "(", "current", ",", "proposed", ")", "{", "if", "(", "stringify", "(", "current", ".", "conf", ")", "!==", "stringify", "(", "proposed", ".", "conf", ")", ")", "{", "if", "(", "current", ".", "version", ">=", "proposed", "."...
Check if a schema part differs, and if it does, if the version was incremented. @param {Object} current { conf: {object}, version: {number} } @param {Object} proposed { conf: {object}, version: {number} } @return {boolean} Whether the attribute has changed. @throws {Error} If the schema fragment changed, but the version was not incremented.
[ "Check", "if", "a", "schema", "part", "differs", "and", "if", "it", "does", "if", "the", "version", "was", "incremented", "." ]
f226a4bd1c75a31243a895d1106bf8ccd643113a
https://github.com/wikimedia/restbase-mod-table-cassandra/blob/f226a4bd1c75a31243a895d1106bf8ccd643113a/lib/schemaMigration.js#L16-L28
31,104
globality-corp/nodule-logging
src/logFormatting.js
validatePropertyType
function validatePropertyType(property, type, recursive) { return type && ( (recursive && typeof property === 'object') || (type === 'string' && typeof property === 'string') || (type === 'number' && typeof property === 'number') || (type === 'uuid' && isUuid(property)) || (type === 'uuidList' && isUuidList(property)) ); }
javascript
function validatePropertyType(property, type, recursive) { return type && ( (recursive && typeof property === 'object') || (type === 'string' && typeof property === 'string') || (type === 'number' && typeof property === 'number') || (type === 'uuid' && isUuid(property)) || (type === 'uuidList' && isUuidList(property)) ); }
[ "function", "validatePropertyType", "(", "property", ",", "type", ",", "recursive", ")", "{", "return", "type", "&&", "(", "(", "recursive", "&&", "typeof", "property", "===", "'object'", ")", "||", "(", "type", "===", "'string'", "&&", "typeof", "property",...
Helper function to parseObject
[ "Helper", "function", "to", "parseObject" ]
5283de6c8bf8a2866f377aa82eca80bc3b30a5c3
https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/logFormatting.js#L44-L52
31,105
globality-corp/nodule-logging
src/logFormatting.js
parseObject
function parseObject(obj, { name, path, subPaths, type, recursive = true, ...args }) { let property = get(obj, path); if (property === null || !validatePropertyType(property, type, recursive)) { return []; } if (type === 'uuidList' && isUuidList(property)) { return [{ [name]: property.split(',') }]; } if (recursive && typeof property === 'object') { const propertyName = isNil(name) ? '' : name; const nextPaths = subPaths || Object.keys(property); return flatten(nextPaths .map(subPath => parseObject(obj, { name: `${propertyName}${subPath}`, path: `${path}.${subPath}`, recursive: false, type, ...args, }))); } if (args.filterPattern) { property = typeof property === 'string' ? get(property.match(args.filterPattern), '[1]') : null; } if (args.hideUUID) { property = typeof property === 'string' ? property.replace( RegExp('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}', 'g'), '{uuid}', ) : null; } return property === null ? [] : [{ [name]: property }]; }
javascript
function parseObject(obj, { name, path, subPaths, type, recursive = true, ...args }) { let property = get(obj, path); if (property === null || !validatePropertyType(property, type, recursive)) { return []; } if (type === 'uuidList' && isUuidList(property)) { return [{ [name]: property.split(',') }]; } if (recursive && typeof property === 'object') { const propertyName = isNil(name) ? '' : name; const nextPaths = subPaths || Object.keys(property); return flatten(nextPaths .map(subPath => parseObject(obj, { name: `${propertyName}${subPath}`, path: `${path}.${subPath}`, recursive: false, type, ...args, }))); } if (args.filterPattern) { property = typeof property === 'string' ? get(property.match(args.filterPattern), '[1]') : null; } if (args.hideUUID) { property = typeof property === 'string' ? property.replace( RegExp('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}', 'g'), '{uuid}', ) : null; } return property === null ? [] : [{ [name]: property }]; }
[ "function", "parseObject", "(", "obj", ",", "{", "name", ",", "path", ",", "subPaths", ",", "type", ",", "recursive", "=", "true", ",", "...", "args", "}", ")", "{", "let", "property", "=", "get", "(", "obj", ",", "path", ")", ";", "if", "(", "pr...
Helper function to extractLoggingProperties Parse rules and return an array of properties to log
[ "Helper", "function", "to", "extractLoggingProperties", "Parse", "rules", "and", "return", "an", "array", "of", "properties", "to", "log" ]
5283de6c8bf8a2866f377aa82eca80bc3b30a5c3
https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/logFormatting.js#L57-L87
31,106
maurelian/eth-registrar-ens
src/index.js
Entry
function Entry(name, hash, status, mode, deed, registrationDate, value, highestBid) { // TODO: improve Entry constructor so that unknown names can be handled via getEntry this.name = name; this.hash = hash; this.status = status; this.mode = mode; this.deed = deed; this.registrationDate = registrationDate; this.value = value; this.highestBid = highestBid; }
javascript
function Entry(name, hash, status, mode, deed, registrationDate, value, highestBid) { // TODO: improve Entry constructor so that unknown names can be handled via getEntry this.name = name; this.hash = hash; this.status = status; this.mode = mode; this.deed = deed; this.registrationDate = registrationDate; this.value = value; this.highestBid = highestBid; }
[ "function", "Entry", "(", "name", ",", "hash", ",", "status", ",", "mode", ",", "deed", ",", "registrationDate", ",", "value", ",", "highestBid", ")", "{", "// TODO: improve Entry constructor so that unknown names can be handled via getEntry", "this", ".", "name", "="...
Constructs a new Entry object corresponding to a name. @ignore @param {string} name The unhashed name @param {string} hash @param {number} status @param {address} deed @param {number} registrationDate @param {number} value @param {number} highestBid
[ "Constructs", "a", "new", "Entry", "object", "corresponding", "to", "a", "name", "." ]
a70baba4de1bcbdb8479f84e1ac694bd670349d5
https://github.com/maurelian/eth-registrar-ens/blob/a70baba4de1bcbdb8479f84e1ac694bd670349d5/src/index.js#L131-L141
31,107
globality-corp/nodule-logging
src/middleware.js
skip
function skip(ignoreRouteUrls) { return function ignoreUrl(req) { const url = req.originalUrl || req.url; return ignoreRouteUrls.includes(url); }; }
javascript
function skip(ignoreRouteUrls) { return function ignoreUrl(req) { const url = req.originalUrl || req.url; return ignoreRouteUrls.includes(url); }; }
[ "function", "skip", "(", "ignoreRouteUrls", ")", "{", "return", "function", "ignoreUrl", "(", "req", ")", "{", "const", "url", "=", "req", ".", "originalUrl", "||", "req", ".", "url", ";", "return", "ignoreRouteUrls", ".", "includes", "(", "url", ")", ";...
exclude any health or other ignorable urls
[ "exclude", "any", "health", "or", "other", "ignorable", "urls" ]
5283de6c8bf8a2866f377aa82eca80bc3b30a5c3
https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/middleware.js#L9-L14
31,108
globality-corp/nodule-logging
src/middleware.js
omit
function omit(req, blacklist) { return omitBy(req, (value, key) => blacklist.includes(key)); }
javascript
function omit(req, blacklist) { return omitBy(req, (value, key) => blacklist.includes(key)); }
[ "function", "omit", "(", "req", ",", "blacklist", ")", "{", "return", "omitBy", "(", "req", ",", "(", "value", ",", "key", ")", "=>", "blacklist", ".", "includes", "(", "key", ")", ")", ";", "}" ]
filter out named properties from req object
[ "filter", "out", "named", "properties", "from", "req", "object" ]
5283de6c8bf8a2866f377aa82eca80bc3b30a5c3
https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/middleware.js#L28-L30
31,109
globality-corp/nodule-logging
src/middleware.js
morganMiddleware
function morganMiddleware(req, res, next) { const { ignoreRouteUrls, includeReqHeaders, omitReqProperties } = getConfig('logger'); const { format } = getConfig('logger.morgan'); // define custom tokens morgan.token('operation-hash', request => get(request, 'body.extensions.persistentQuery.sha256Hash')); morgan.token('operation-name', request => get(request, 'body.operationName')); morgan.token('user-id', request => get(request, 'locals.user.id')); morgan.token('company-id', request => get(request, 'locals.user.companyId')); morgan.token('message', request => request.name || '-'); morgan.token('request-id', request => request.id); morgan.token('request-headers', (request) => { const headers = includeReqHeaders === true ? omit(request.headers, omitReqProperties) : {}; return JSON.stringify(headers); }); const logger = getContainer('logger'); const formatFormat = json(format); const options = { stream: asStream(logger), skip: skip(ignoreRouteUrls), }; return morgan(formatFormat, options)(req, res, next); }
javascript
function morganMiddleware(req, res, next) { const { ignoreRouteUrls, includeReqHeaders, omitReqProperties } = getConfig('logger'); const { format } = getConfig('logger.morgan'); // define custom tokens morgan.token('operation-hash', request => get(request, 'body.extensions.persistentQuery.sha256Hash')); morgan.token('operation-name', request => get(request, 'body.operationName')); morgan.token('user-id', request => get(request, 'locals.user.id')); morgan.token('company-id', request => get(request, 'locals.user.companyId')); morgan.token('message', request => request.name || '-'); morgan.token('request-id', request => request.id); morgan.token('request-headers', (request) => { const headers = includeReqHeaders === true ? omit(request.headers, omitReqProperties) : {}; return JSON.stringify(headers); }); const logger = getContainer('logger'); const formatFormat = json(format); const options = { stream: asStream(logger), skip: skip(ignoreRouteUrls), }; return morgan(formatFormat, options)(req, res, next); }
[ "function", "morganMiddleware", "(", "req", ",", "res", ",", "next", ")", "{", "const", "{", "ignoreRouteUrls", ",", "includeReqHeaders", ",", "omitReqProperties", "}", "=", "getConfig", "(", "'logger'", ")", ";", "const", "{", "format", "}", "=", "getConfig...
Use morgan library to log every HTTP response Also set req._startAt - that is used by the logger
[ "Use", "morgan", "library", "to", "log", "every", "HTTP", "response", "Also", "set", "req", ".", "_startAt", "-", "that", "is", "used", "by", "the", "logger" ]
5283de6c8bf8a2866f377aa82eca80bc3b30a5c3
https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/middleware.js#L40-L63
31,110
wikimedia/restbase-mod-table-cassandra
maintenance/lib/index.js
getConfig
function getConfig(config) { // Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG // env var, or from /etc/restbase/config.yaml var conf; if (config) { conf = config; } else if (process.env.CONFIG) { conf = process.env.CONFIG; } else { conf = '/etc/restbase/config.yaml'; } var confObj = yaml.safeLoad(fs.readFileSync(conf)); return confObj.default_project['x-modules'][0].options.table; }
javascript
function getConfig(config) { // Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG // env var, or from /etc/restbase/config.yaml var conf; if (config) { conf = config; } else if (process.env.CONFIG) { conf = process.env.CONFIG; } else { conf = '/etc/restbase/config.yaml'; } var confObj = yaml.safeLoad(fs.readFileSync(conf)); return confObj.default_project['x-modules'][0].options.table; }
[ "function", "getConfig", "(", "config", ")", "{", "// Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG", "// env var, or from /etc/restbase/config.yaml", "var", "conf", ";", "if", "(", "config", ")", "{", "conf", "=", "config", ";", "}", "...
Return the table section of a RESTBase config. @param {string} config - Path to a RESTBase YAML configuration file. @return {Object} table section of configuration.
[ "Return", "the", "table", "section", "of", "a", "RESTBase", "config", "." ]
f226a4bd1c75a31243a895d1106bf8ccd643113a
https://github.com/wikimedia/restbase-mod-table-cassandra/blob/f226a4bd1c75a31243a895d1106bf8ccd643113a/maintenance/lib/index.js#L12-L27
31,111
jsrmath/sharp11
lib/note.js
function (name) { var octave = null; name = prepareNoteName(name); // Extract octave number if given if (/\d$/.test(name)) { octave = parseInt(name.slice(-1)); name = name.slice(0, -1); } // Throw an error for an invalid note name if (!(/^[A-Ga-g](bb|##|[b#n])?$/).test(name)) { throw new Error('Invalid note name: ' + name); } return { letter: name[0].toUpperCase(), acc: name.slice(1) || 'n', octave: octave }; }
javascript
function (name) { var octave = null; name = prepareNoteName(name); // Extract octave number if given if (/\d$/.test(name)) { octave = parseInt(name.slice(-1)); name = name.slice(0, -1); } // Throw an error for an invalid note name if (!(/^[A-Ga-g](bb|##|[b#n])?$/).test(name)) { throw new Error('Invalid note name: ' + name); } return { letter: name[0].toUpperCase(), acc: name.slice(1) || 'n', octave: octave }; }
[ "function", "(", "name", ")", "{", "var", "octave", "=", "null", ";", "name", "=", "prepareNoteName", "(", "name", ")", ";", "// Extract octave number if given", "if", "(", "/", "\\d$", "/", ".", "test", "(", "name", ")", ")", "{", "octave", "=", "pars...
Parse a note name and return object with letter, accidental
[ "Parse", "a", "note", "name", "and", "return", "object", "with", "letter", "accidental" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L37-L58
31,112
jsrmath/sharp11
lib/note.js
function (note, number) { var letter = note.letter; var index = scale.indexOf(note.letter); var newIndex = mod(index + number - 1, scale.length); assert(index > -1); assert(newIndex > -1 && newIndex < scale.length); return scale[newIndex]; }
javascript
function (note, number) { var letter = note.letter; var index = scale.indexOf(note.letter); var newIndex = mod(index + number - 1, scale.length); assert(index > -1); assert(newIndex > -1 && newIndex < scale.length); return scale[newIndex]; }
[ "function", "(", "note", ",", "number", ")", "{", "var", "letter", "=", "note", ".", "letter", ";", "var", "index", "=", "scale", ".", "indexOf", "(", "note", ".", "letter", ")", ";", "var", "newIndex", "=", "mod", "(", "index", "+", "number", "-",...
Increase the letter of a note by a given interval
[ "Increase", "the", "letter", "of", "a", "note", "by", "a", "given", "interval" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L61-L70
31,113
jsrmath/sharp11
lib/note.js
function (letter1, letter2) { var index1 = scale.indexOf(letter1); var index2 = scale.indexOf(letter2); var distance = mod(index2 - index1, scale.length) + 1; assert(index1 > -1); assert(index2 > -1); assert(distance > 0 && distance <= scale.length); return distance; }
javascript
function (letter1, letter2) { var index1 = scale.indexOf(letter1); var index2 = scale.indexOf(letter2); var distance = mod(index2 - index1, scale.length) + 1; assert(index1 > -1); assert(index2 > -1); assert(distance > 0 && distance <= scale.length); return distance; }
[ "function", "(", "letter1", ",", "letter2", ")", "{", "var", "index1", "=", "scale", ".", "indexOf", "(", "letter1", ")", ";", "var", "index2", "=", "scale", ".", "indexOf", "(", "letter2", ")", ";", "var", "distance", "=", "mod", "(", "index2", "-",...
Find the interval number between two notes given their letters
[ "Find", "the", "interval", "number", "between", "two", "notes", "given", "their", "letters" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L73-L83
31,114
jsrmath/sharp11
lib/note.js
function (int) { var map = interval.isPerfect(int.number) ? perfectOffsets : majorOffsets; var key = _.invert(map)[int.quality]; return parseInt(key, 10); }
javascript
function (int) { var map = interval.isPerfect(int.number) ? perfectOffsets : majorOffsets; var key = _.invert(map)[int.quality]; return parseInt(key, 10); }
[ "function", "(", "int", ")", "{", "var", "map", "=", "interval", ".", "isPerfect", "(", "int", ".", "number", ")", "?", "perfectOffsets", ":", "majorOffsets", ";", "var", "key", "=", "_", ".", "invert", "(", "map", ")", "[", "int", ".", "quality", ...
Find the number of half steps between interval and corresponding diatonic interval
[ "Find", "the", "number", "of", "half", "steps", "between", "interval", "and", "corresponding", "diatonic", "interval" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L97-L102
31,115
jsrmath/sharp11
lib/note.js
function (number, halfSteps) { var diatonicHalfSteps = getDiatonicHalfSteps(number); var halfStepOffset = halfSteps - diatonicHalfSteps; // Handle various abnormalities if (halfStepOffset === 11) halfStepOffset = -1; if (halfStepOffset === -11) halfStepOffset = 1; return halfStepOffset; }
javascript
function (number, halfSteps) { var diatonicHalfSteps = getDiatonicHalfSteps(number); var halfStepOffset = halfSteps - diatonicHalfSteps; // Handle various abnormalities if (halfStepOffset === 11) halfStepOffset = -1; if (halfStepOffset === -11) halfStepOffset = 1; return halfStepOffset; }
[ "function", "(", "number", ",", "halfSteps", ")", "{", "var", "diatonicHalfSteps", "=", "getDiatonicHalfSteps", "(", "number", ")", ";", "var", "halfStepOffset", "=", "halfSteps", "-", "diatonicHalfSteps", ";", "// Handle various abnormalities", "if", "(", "halfStep...
Find the offset between
[ "Find", "the", "offset", "between" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L105-L114
31,116
jsrmath/sharp11
lib/mehegan.js
function (key, n) { var int; var numeral; try { int = key.getInterval(n); } catch (err) { try { int = key.getInterval(n.clean()); } catch (err2) { int = key.getInterval(n.toggleAccidental()); } } // Although dim7, for example, is a valid interval, we don't want a bbVII in our symbol if (!interval.isPerfect(int.number) && int.quality === 'dim') { int = interval.parse((int.number - 1).toString()); } numeral = romanNumeral[int.number]; if (int.quality === 'm' || int.quality === 'dim') numeral = 'b' + numeral; if (int.quality === 'aug') numeral = '#' + numeral; return numeral; }
javascript
function (key, n) { var int; var numeral; try { int = key.getInterval(n); } catch (err) { try { int = key.getInterval(n.clean()); } catch (err2) { int = key.getInterval(n.toggleAccidental()); } } // Although dim7, for example, is a valid interval, we don't want a bbVII in our symbol if (!interval.isPerfect(int.number) && int.quality === 'dim') { int = interval.parse((int.number - 1).toString()); } numeral = romanNumeral[int.number]; if (int.quality === 'm' || int.quality === 'dim') numeral = 'b' + numeral; if (int.quality === 'aug') numeral = '#' + numeral; return numeral; }
[ "function", "(", "key", ",", "n", ")", "{", "var", "int", ";", "var", "numeral", ";", "try", "{", "int", "=", "key", ".", "getInterval", "(", "n", ")", ";", "}", "catch", "(", "err", ")", "{", "try", "{", "int", "=", "key", ".", "getInterval", ...
Given a key and a note, return a roman numeral representing the note
[ "Given", "a", "key", "and", "a", "note", "return", "a", "roman", "numeral", "representing", "the", "note" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/mehegan.js#L36-L61
31,117
jsrmath/sharp11
lib/mehegan.js
function (numeral) { var matches = numeral.match(/([b#]?)([iIvV]+)/); var halfSteps = interval.parse(_.indexOf(romanNumeral, matches[2]).toString()).halfSteps(); if (matches[1] === 'b') halfSteps -= 1; if (matches[1] === '#') halfSteps += 1; return halfSteps; }
javascript
function (numeral) { var matches = numeral.match(/([b#]?)([iIvV]+)/); var halfSteps = interval.parse(_.indexOf(romanNumeral, matches[2]).toString()).halfSteps(); if (matches[1] === 'b') halfSteps -= 1; if (matches[1] === '#') halfSteps += 1; return halfSteps; }
[ "function", "(", "numeral", ")", "{", "var", "matches", "=", "numeral", ".", "match", "(", "/", "([b#]?)([iIvV]+)", "/", ")", ";", "var", "halfSteps", "=", "interval", ".", "parse", "(", "_", ".", "indexOf", "(", "romanNumeral", ",", "matches", "[", "2...
Given a roman numeral, return the number of half steps
[ "Given", "a", "roman", "numeral", "return", "the", "number", "of", "half", "steps" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/mehegan.js#L64-L72
31,118
jsrmath/sharp11
lib/mehegan.js
function (numeral, quality) { // Roman numeral representing chord this.numeral = numeral; // Chord quality: M, m, x, o, ø, s this.quality = quality; if (!_.contains(['M', 'm', 'x', 'o', 'ø', 's'], quality)) { throw new Error('Invalid chord quality'); } // The number of half-steps between the key and the chord // e.g. I => 0, bIV => 6 this.interval = getHalfSteps(numeral); this.toString = function () { return this.numeral + this.quality; }; }
javascript
function (numeral, quality) { // Roman numeral representing chord this.numeral = numeral; // Chord quality: M, m, x, o, ø, s this.quality = quality; if (!_.contains(['M', 'm', 'x', 'o', 'ø', 's'], quality)) { throw new Error('Invalid chord quality'); } // The number of half-steps between the key and the chord // e.g. I => 0, bIV => 6 this.interval = getHalfSteps(numeral); this.toString = function () { return this.numeral + this.quality; }; }
[ "function", "(", "numeral", ",", "quality", ")", "{", "// Roman numeral representing chord", "this", ".", "numeral", "=", "numeral", ";", "// Chord quality: M, m, x, o, ø, s", "this", ".", "quality", "=", "quality", ";", "if", "(", "!", "_", ".", "contains", "("...
A roman numeral symbol representing a chord using the Mehegan system
[ "A", "roman", "numeral", "symbol", "representing", "a", "chord", "using", "the", "Mehegan", "system" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/mehegan.js#L80-L97
31,119
jsrmath/sharp11
lib/mehegan.js
function (key, ch) { key = note.create(key || 'C'); ch = chord.create(ch); return new Mehegan(getNumeral(key, ch.root), getQuality(ch)); }
javascript
function (key, ch) { key = note.create(key || 'C'); ch = chord.create(ch); return new Mehegan(getNumeral(key, ch.root), getQuality(ch)); }
[ "function", "(", "key", ",", "ch", ")", "{", "key", "=", "note", ".", "create", "(", "key", "||", "'C'", ")", ";", "ch", "=", "chord", ".", "create", "(", "ch", ")", ";", "return", "new", "Mehegan", "(", "getNumeral", "(", "key", ",", "ch", "."...
Create a Mehegan symbol given a key and a chord
[ "Create", "a", "Mehegan", "symbol", "given", "a", "key", "and", "a", "chord" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/mehegan.js#L100-L105
31,120
jsrmath/sharp11
lib/mehegan.js
function (mehegan, cache) { if (mehegan instanceof Mehegan) return mehegan; // If no cache is provided, return string as Mehegan symbol if (!cache) return fromString(mehegan); // Otherwise, try to retrieve symbol from cache, creating a new symbol if it's not found if (!cache[mehegan]) cache[mehegan] = fromString(mehegan); return cache[mehegan]; }
javascript
function (mehegan, cache) { if (mehegan instanceof Mehegan) return mehegan; // If no cache is provided, return string as Mehegan symbol if (!cache) return fromString(mehegan); // Otherwise, try to retrieve symbol from cache, creating a new symbol if it's not found if (!cache[mehegan]) cache[mehegan] = fromString(mehegan); return cache[mehegan]; }
[ "function", "(", "mehegan", ",", "cache", ")", "{", "if", "(", "mehegan", "instanceof", "Mehegan", ")", "return", "mehegan", ";", "// If no cache is provided, return string as Mehegan symbol", "if", "(", "!", "cache", ")", "return", "fromString", "(", "mehegan", "...
Given a Mehegan symbol, return the Mehegan symbol Given a Mehegan string, return it as a Mehegan symbol If a cache is given, will store and retrieve symbols based on string
[ "Given", "a", "Mehegan", "symbol", "return", "the", "Mehegan", "symbol", "Given", "a", "Mehegan", "string", "return", "it", "as", "a", "Mehegan", "symbol", "If", "a", "cache", "is", "given", "will", "store", "and", "retrieve", "symbols", "based", "on", "st...
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/mehegan.js#L136-L145
31,121
jsrmath/sharp11
lib/interval.js
function (interval) { var quality; var number; if (interval instanceof Interval) return interval; quality = interval.replace(/\d/g, ''); // Remove digits number = parseInt(interval.replace(/\D/g, ''), 10); // Remove non-digits if (!quality) { // No quality given, assume major or perfect quality = isPerfect(number) ? 'P' : 'M'; } return new Interval(number, quality); }
javascript
function (interval) { var quality; var number; if (interval instanceof Interval) return interval; quality = interval.replace(/\d/g, ''); // Remove digits number = parseInt(interval.replace(/\D/g, ''), 10); // Remove non-digits if (!quality) { // No quality given, assume major or perfect quality = isPerfect(number) ? 'P' : 'M'; } return new Interval(number, quality); }
[ "function", "(", "interval", ")", "{", "var", "quality", ";", "var", "number", ";", "if", "(", "interval", "instanceof", "Interval", ")", "return", "interval", ";", "quality", "=", "interval", ".", "replace", "(", "/", "\\d", "/", "g", ",", "''", ")", ...
Parse a string and return an interval object
[ "Parse", "a", "string", "and", "return", "an", "interval", "object" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/interval.js#L43-L57
31,122
jsrmath/sharp11
lib/scale.js
function (scale, note) { return _.findIndex(scale.scale, function (scaleNote) { return scaleNote.enharmonic(note); }); }
javascript
function (scale, note) { return _.findIndex(scale.scale, function (scaleNote) { return scaleNote.enharmonic(note); }); }
[ "function", "(", "scale", ",", "note", ")", "{", "return", "_", ".", "findIndex", "(", "scale", ".", "scale", ",", "function", "(", "scaleNote", ")", "{", "return", "scaleNote", ".", "enharmonic", "(", "note", ")", ";", "}", ")", ";", "}" ]
Return index of note in scale
[ "Return", "index", "of", "note", "in", "scale" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/scale.js#L94-L98
31,123
jsrmath/sharp11
lib/chord.js
function (chord) { var noteRegex = '[A-Ga-g][#b]{0,2}'; var root = chord.match(new RegExp('^' + noteRegex))[0]; var bass = null; var symbol; root = note.create(root); // Strip note, strip spaces, strip bass symbol = chord.replace(/[\s]/g, '') .replace(new RegExp('^' + noteRegex), '') .replace(new RegExp('/' + noteRegex + '$'), ''); bass = chord.match(new RegExp('/' + noteRegex + '$')); if (bass) bass = note.create(bass[0].slice(1)); return { root: root, symbol: symbol, bass: bass }; }
javascript
function (chord) { var noteRegex = '[A-Ga-g][#b]{0,2}'; var root = chord.match(new RegExp('^' + noteRegex))[0]; var bass = null; var symbol; root = note.create(root); // Strip note, strip spaces, strip bass symbol = chord.replace(/[\s]/g, '') .replace(new RegExp('^' + noteRegex), '') .replace(new RegExp('/' + noteRegex + '$'), ''); bass = chord.match(new RegExp('/' + noteRegex + '$')); if (bass) bass = note.create(bass[0].slice(1)); return { root: root, symbol: symbol, bass: bass }; }
[ "function", "(", "chord", ")", "{", "var", "noteRegex", "=", "'[A-Ga-g][#b]{0,2}'", ";", "var", "root", "=", "chord", ".", "match", "(", "new", "RegExp", "(", "'^'", "+", "noteRegex", ")", ")", "[", "0", "]", ";", "var", "bass", "=", "null", ";", "...
Parse a chord symbol and return root, chord, bass
[ "Parse", "a", "chord", "symbol", "and", "return", "root", "chord", "bass" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L10-L27
31,124
jsrmath/sharp11
lib/chord.js
function (interval) { return _.find(notes, function (n) { return root.transpose(interval).enharmonic(n); }); }
javascript
function (interval) { return _.find(notes, function (n) { return root.transpose(interval).enharmonic(n); }); }
[ "function", "(", "interval", ")", "{", "return", "_", ".", "find", "(", "notes", ",", "function", "(", "n", ")", "{", "return", "root", ".", "transpose", "(", "interval", ")", ".", "enharmonic", "(", "n", ")", ";", "}", ")", ";", "}" ]
Return true if interval is present in this chord
[ "Return", "true", "if", "interval", "is", "present", "in", "this", "chord" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L183-L187
31,125
jsrmath/sharp11
lib/chord.js
function (root, bass, intervals) { var chord = _.chain(intervals) .map(function (quality, number) { var int; if (quality) { // #9 is stored as b10, so special case this if (number === 10 && quality === 'm') { int = interval.create(9, 'aug'); } else { int = interval.create(number, quality); } return root.transpose(int); } }) .compact() .value(); var bassIndex; // Handle slash chords if (bass && !root.enharmonic(bass)) { bassIndex = _.findIndex(chord, bass.enharmonic.bind(bass)); if (bassIndex > -1) { // Rotate chord so bass is first chord = rotateArr(chord, bassIndex); } else { // Otherwise, add bass to beginning chord.unshift(bass); } } return chord; }
javascript
function (root, bass, intervals) { var chord = _.chain(intervals) .map(function (quality, number) { var int; if (quality) { // #9 is stored as b10, so special case this if (number === 10 && quality === 'm') { int = interval.create(9, 'aug'); } else { int = interval.create(number, quality); } return root.transpose(int); } }) .compact() .value(); var bassIndex; // Handle slash chords if (bass && !root.enharmonic(bass)) { bassIndex = _.findIndex(chord, bass.enharmonic.bind(bass)); if (bassIndex > -1) { // Rotate chord so bass is first chord = rotateArr(chord, bassIndex); } else { // Otherwise, add bass to beginning chord.unshift(bass); } } return chord; }
[ "function", "(", "root", ",", "bass", ",", "intervals", ")", "{", "var", "chord", "=", "_", ".", "chain", "(", "intervals", ")", ".", "map", "(", "function", "(", "quality", ",", "number", ")", "{", "var", "int", ";", "if", "(", "quality", ")", "...
Return an array of notes in a chord
[ "Return", "an", "array", "of", "notes", "in", "a", "chord" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L364-L397
31,126
jsrmath/sharp11
lib/chord.js
function (root, symbol, bass) { var name = root.name + symbol; var octave = bass ? bass.octave : root.octave; if (bass) name += '/' + bass.name; return new Chord(name, octave); }
javascript
function (root, symbol, bass) { var name = root.name + symbol; var octave = bass ? bass.octave : root.octave; if (bass) name += '/' + bass.name; return new Chord(name, octave); }
[ "function", "(", "root", ",", "symbol", ",", "bass", ")", "{", "var", "name", "=", "root", ".", "name", "+", "symbol", ";", "var", "octave", "=", "bass", "?", "bass", ".", "octave", ":", "root", ".", "octave", ";", "if", "(", "bass", ")", "name",...
Make a chord object given root, symbol, bass
[ "Make", "a", "chord", "object", "given", "root", "symbol", "bass" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L400-L406
31,127
jsrmath/sharp11
lib/chord.js
function (scales, chord) { // Exclude scales with a particular interval var exclude = function (int) { scales = _.filter(scales, function (scale) { return !scale.hasInterval(int); }); }; // Add a scale at a particular index var include = function (index, scaleId) { scales.splice(index, 0, scale.create(chord.root, scaleId)); }; if (_.includes(['m', 'm6', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) { exclude('M3'); } if (_.includes(['7', '9', '11', '13', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) { exclude('M7'); } if (_.includes(['M7', 'M9', 'M11', 'M13'], chord.formattedSymbol)) { exclude('m7'); } if (chord.formattedSymbol[0] === '6' || chord.formattedSymbol.slice(0, 2) === 'M6') { exclude('m7'); } if (_.includes(['7', '7#9', '7+9', '7#11', '7+11'], chord.formattedSymbol)) { include(2, 'blues'); } return scales; }
javascript
function (scales, chord) { // Exclude scales with a particular interval var exclude = function (int) { scales = _.filter(scales, function (scale) { return !scale.hasInterval(int); }); }; // Add a scale at a particular index var include = function (index, scaleId) { scales.splice(index, 0, scale.create(chord.root, scaleId)); }; if (_.includes(['m', 'm6', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) { exclude('M3'); } if (_.includes(['7', '9', '11', '13', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) { exclude('M7'); } if (_.includes(['M7', 'M9', 'M11', 'M13'], chord.formattedSymbol)) { exclude('m7'); } if (chord.formattedSymbol[0] === '6' || chord.formattedSymbol.slice(0, 2) === 'M6') { exclude('m7'); } if (_.includes(['7', '7#9', '7+9', '7#11', '7+11'], chord.formattedSymbol)) { include(2, 'blues'); } return scales; }
[ "function", "(", "scales", ",", "chord", ")", "{", "// Exclude scales with a particular interval", "var", "exclude", "=", "function", "(", "int", ")", "{", "scales", "=", "_", ".", "filter", "(", "scales", ",", "function", "(", "scale", ")", "{", "return", ...
Given an ordered list of scales and a chord symbol, optimize order
[ "Given", "an", "ordered", "list", "of", "scales", "and", "a", "chord", "symbol", "optimize", "order" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L409-L440
31,128
jsrmath/sharp11
lib/chord.js
function (index, scaleId) { scales.splice(index, 0, scale.create(chord.root, scaleId)); }
javascript
function (index, scaleId) { scales.splice(index, 0, scale.create(chord.root, scaleId)); }
[ "function", "(", "index", ",", "scaleId", ")", "{", "scales", ".", "splice", "(", "index", ",", "0", ",", "scale", ".", "create", "(", "chord", ".", "root", ",", "scaleId", ")", ")", ";", "}" ]
Add a scale at a particular index
[ "Add", "a", "scale", "at", "a", "particular", "index" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L418-L420
31,129
jsrmath/sharp11
lib/chord.js
function (obj, octave) { var lastNote = obj.chord[0]; obj.chord = _.map(obj.chord, function (n) { // Every time a note is "lower" than the last note, we're in a new octave if (n.lowerThan(lastNote)) octave += 1; // As a side-effect, update the octaves for root and bass if (n.enharmonic(obj.root)) { obj.root = obj.root.inOctave(octave); } if (obj.bass && n.enharmonic(obj.bass)) { obj.bass = obj.bass.inOctave(octave); } lastNote = n; return n.inOctave(octave); }); }
javascript
function (obj, octave) { var lastNote = obj.chord[0]; obj.chord = _.map(obj.chord, function (n) { // Every time a note is "lower" than the last note, we're in a new octave if (n.lowerThan(lastNote)) octave += 1; // As a side-effect, update the octaves for root and bass if (n.enharmonic(obj.root)) { obj.root = obj.root.inOctave(octave); } if (obj.bass && n.enharmonic(obj.bass)) { obj.bass = obj.bass.inOctave(octave); } lastNote = n; return n.inOctave(octave); }); }
[ "function", "(", "obj", ",", "octave", ")", "{", "var", "lastNote", "=", "obj", ".", "chord", "[", "0", "]", ";", "obj", ".", "chord", "=", "_", ".", "map", "(", "obj", ".", "chord", ",", "function", "(", "n", ")", "{", "// Every time a note is \"l...
Given a chord object and an octave number, assign appropriate octave numbers to notes
[ "Given", "a", "chord", "object", "and", "an", "octave", "number", "assign", "appropriate", "octave", "numbers", "to", "notes" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/chord.js#L443-L461
31,130
jsrmath/sharp11
lib/midi.js
function (num, totalBytes) { var numBytes = Math.floor(Math.log(num) / Math.log(0xff)) + 1; var buffer = new Buffer(totalBytes); buffer.fill(0); buffer.writeUIntBE(num, totalBytes - numBytes, numBytes); return buffer; }
javascript
function (num, totalBytes) { var numBytes = Math.floor(Math.log(num) / Math.log(0xff)) + 1; var buffer = new Buffer(totalBytes); buffer.fill(0); buffer.writeUIntBE(num, totalBytes - numBytes, numBytes); return buffer; }
[ "function", "(", "num", ",", "totalBytes", ")", "{", "var", "numBytes", "=", "Math", ".", "floor", "(", "Math", ".", "log", "(", "num", ")", "/", "Math", ".", "log", "(", "0xff", ")", ")", "+", "1", ";", "var", "buffer", "=", "new", "Buffer", "...
Return a number in a buffer padded to have a certain number of bytes
[ "Return", "a", "number", "in", "a", "buffer", "padded", "to", "have", "a", "certain", "number", "of", "bytes" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L14-L22
31,131
jsrmath/sharp11
lib/midi.js
function (format, numTracks) { var chunklen = padNumber(6, 4); // MIDI header is always 6 bytes long var ntracks = padNumber(numTracks, 2); var tickdiv = padNumber(ticksPerBeat, 2); format = padNumber(format, 2); // Usually format 1 MIDI file (multuple overlayed tracks) return Buffer.concat([midiHeader, chunklen, format, ntracks, tickdiv]); }
javascript
function (format, numTracks) { var chunklen = padNumber(6, 4); // MIDI header is always 6 bytes long var ntracks = padNumber(numTracks, 2); var tickdiv = padNumber(ticksPerBeat, 2); format = padNumber(format, 2); // Usually format 1 MIDI file (multuple overlayed tracks) return Buffer.concat([midiHeader, chunklen, format, ntracks, tickdiv]); }
[ "function", "(", "format", ",", "numTracks", ")", "{", "var", "chunklen", "=", "padNumber", "(", "6", ",", "4", ")", ";", "// MIDI header is always 6 bytes long", "var", "ntracks", "=", "padNumber", "(", "numTracks", ",", "2", ")", ";", "var", "tickdiv", "...
Given a number of tracks, return a MIDI header
[ "Given", "a", "number", "of", "tracks", "return", "a", "MIDI", "header" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L45-L52
31,132
jsrmath/sharp11
lib/midi.js
function (settings) { var tempo = 60e6 / settings.tempo; // Microseconds per beat var setTempo = Buffer.concat([new Buffer([0, 0xFF, 0x51, 0x03]), padNumber(tempo, 3)]); var length = setTempo.length + trackFooter.length; return Buffer.concat([trackHeader, padNumber(length, 4), setTempo, trackFooter]); }
javascript
function (settings) { var tempo = 60e6 / settings.tempo; // Microseconds per beat var setTempo = Buffer.concat([new Buffer([0, 0xFF, 0x51, 0x03]), padNumber(tempo, 3)]); var length = setTempo.length + trackFooter.length; return Buffer.concat([trackHeader, padNumber(length, 4), setTempo, trackFooter]); }
[ "function", "(", "settings", ")", "{", "var", "tempo", "=", "60e6", "/", "settings", ".", "tempo", ";", "// Microseconds per beat", "var", "setTempo", "=", "Buffer", ".", "concat", "(", "[", "new", "Buffer", "(", "[", "0", ",", "0xFF", ",", "0x51", ","...
Return a buffer with a MIDI track that sets the tempo
[ "Return", "a", "buffer", "with", "a", "MIDI", "track", "that", "sets", "the", "tempo" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L55-L61
31,133
jsrmath/sharp11
lib/midi.js
function (deltaTime, on, channel, note, velocity) { var status = on ? 0x90 : 0x80; status += channel; deltaTime = makeVLQ(deltaTime); return Buffer.concat([deltaTime, new Buffer([status, note, velocity])]); }
javascript
function (deltaTime, on, channel, note, velocity) { var status = on ? 0x90 : 0x80; status += channel; deltaTime = makeVLQ(deltaTime); return Buffer.concat([deltaTime, new Buffer([status, note, velocity])]); }
[ "function", "(", "deltaTime", ",", "on", ",", "channel", ",", "note", ",", "velocity", ")", "{", "var", "status", "=", "on", "?", "0x90", ":", "0x80", ";", "status", "+=", "channel", ";", "deltaTime", "=", "makeVLQ", "(", "deltaTime", ")", ";", "retu...
Make a MIDI note event
[ "Make", "a", "MIDI", "note", "event" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L70-L77
31,134
jsrmath/sharp11
lib/midi.js
function (deltaTime, on, firstChannel, chord, velocity) { var arr = []; // Make note event for first note after appropriate time arr.push(makeNoteEvent(deltaTime, on, firstChannel, noteValue(_.first(chord)), velocity)); // Make note event for rest of the notes _.each(_.rest(chord), function (note, i) { arr.push(makeNoteEvent(0, on, i + firstChannel, noteValue(note), velocity)); }); return Buffer.concat(arr); }
javascript
function (deltaTime, on, firstChannel, chord, velocity) { var arr = []; // Make note event for first note after appropriate time arr.push(makeNoteEvent(deltaTime, on, firstChannel, noteValue(_.first(chord)), velocity)); // Make note event for rest of the notes _.each(_.rest(chord), function (note, i) { arr.push(makeNoteEvent(0, on, i + firstChannel, noteValue(note), velocity)); }); return Buffer.concat(arr); }
[ "function", "(", "deltaTime", ",", "on", ",", "firstChannel", ",", "chord", ",", "velocity", ")", "{", "var", "arr", "=", "[", "]", ";", "// Make note event for first note after appropriate time", "arr", ".", "push", "(", "makeNoteEvent", "(", "deltaTime", ",", ...
Make a multiple MIDI note events for a given chord
[ "Make", "a", "multiple", "MIDI", "note", "events", "for", "a", "given", "chord" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L80-L92
31,135
jsrmath/sharp11
lib/midi.js
function (duration, settings) { // If there's no swing ratio, assume straight eighths var ratio = settings && settings.swingRatio ? settings.swingRatio : 1; return Math.round(ticksPerBeat * duration.value(ratio)); }
javascript
function (duration, settings) { // If there's no swing ratio, assume straight eighths var ratio = settings && settings.swingRatio ? settings.swingRatio : 1; return Math.round(ticksPerBeat * duration.value(ratio)); }
[ "function", "(", "duration", ",", "settings", ")", "{", "// If there's no swing ratio, assume straight eighths", "var", "ratio", "=", "settings", "&&", "settings", ".", "swingRatio", "?", "settings", ".", "swingRatio", ":", "1", ";", "return", "Math", ".", "round"...
Given a note duration, return the time delta
[ "Given", "a", "note", "duration", "return", "the", "time", "delta" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L95-L99
31,136
jsrmath/sharp11
lib/midi.js
function (notes, settings) { var restBuffer = 0; var events = _.reduce(notes, function (arr, obj) { var time = noteLength(obj.duration, settings); if (obj.note) { arr.push(makeNoteEvent(restBuffer, true, 0, noteValue(obj.note), settings.noteVelocity)); // On arr.push(makeNoteEvent(time, false, 0, noteValue(obj.note), settings.noteVelocity)); // Off restBuffer = 0; } else { restBuffer += time; } return arr; }, []); return Buffer.concat(events); }
javascript
function (notes, settings) { var restBuffer = 0; var events = _.reduce(notes, function (arr, obj) { var time = noteLength(obj.duration, settings); if (obj.note) { arr.push(makeNoteEvent(restBuffer, true, 0, noteValue(obj.note), settings.noteVelocity)); // On arr.push(makeNoteEvent(time, false, 0, noteValue(obj.note), settings.noteVelocity)); // Off restBuffer = 0; } else { restBuffer += time; } return arr; }, []); return Buffer.concat(events); }
[ "function", "(", "notes", ",", "settings", ")", "{", "var", "restBuffer", "=", "0", ";", "var", "events", "=", "_", ".", "reduce", "(", "notes", ",", "function", "(", "arr", ",", "obj", ")", "{", "var", "time", "=", "noteLength", "(", "obj", ".", ...
Given note list, return a buffer containing note events
[ "Given", "note", "list", "return", "a", "buffer", "containing", "note", "events" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L107-L126
31,137
jsrmath/sharp11
lib/midi.js
function (chords, settings) { var events = _.reduce(chords, function (arr, obj) { var time = noteLength(obj.duration, settings); var chord = obj.chord.inOctave(settings.chordOctave).chord; arr.push(makeChordEvent(0, true, 1, chord, settings.chordVelocity)); // On arr.push(makeChordEvent(time, false, 1, chord, settings.chordVelocity)); // Off return arr; }, []); return Buffer.concat(events); }
javascript
function (chords, settings) { var events = _.reduce(chords, function (arr, obj) { var time = noteLength(obj.duration, settings); var chord = obj.chord.inOctave(settings.chordOctave).chord; arr.push(makeChordEvent(0, true, 1, chord, settings.chordVelocity)); // On arr.push(makeChordEvent(time, false, 1, chord, settings.chordVelocity)); // Off return arr; }, []); return Buffer.concat(events); }
[ "function", "(", "chords", ",", "settings", ")", "{", "var", "events", "=", "_", ".", "reduce", "(", "chords", ",", "function", "(", "arr", ",", "obj", ")", "{", "var", "time", "=", "noteLength", "(", "obj", ".", "duration", ",", "settings", ")", "...
Given chord data, return a buffer containing note events
[ "Given", "chord", "data", "return", "a", "buffer", "containing", "note", "events" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L129-L141
31,138
jsrmath/sharp11
lib/midi.js
function (notes, settings) { var noteEvents = makeNoteEvents(notes, settings); var setPatch = makePatchEvent(0, settings.melodyPatch); var length = setPatch.length + noteEvents.length + trackFooter.length; return Buffer.concat([trackHeader, padNumber(length, 4), setPatch, noteEvents, trackFooter]); }
javascript
function (notes, settings) { var noteEvents = makeNoteEvents(notes, settings); var setPatch = makePatchEvent(0, settings.melodyPatch); var length = setPatch.length + noteEvents.length + trackFooter.length; return Buffer.concat([trackHeader, padNumber(length, 4), setPatch, noteEvents, trackFooter]); }
[ "function", "(", "notes", ",", "settings", ")", "{", "var", "noteEvents", "=", "makeNoteEvents", "(", "notes", ",", "settings", ")", ";", "var", "setPatch", "=", "makePatchEvent", "(", "0", ",", "settings", ".", "melodyPatch", ")", ";", "var", "length", ...
Return a buffer with a melody track
[ "Return", "a", "buffer", "with", "a", "melody", "track" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L144-L150
31,139
jsrmath/sharp11
lib/midi.js
function (chords, settings) { var chordEvents = makeChordEvents(chords, settings); // Set all channels var setPatches = _.reduce(_.range(0xf), function (buffer, channel) { return Buffer.concat([buffer, makePatchEvent(channel, settings.chordPatch)]); }, new Buffer(0)); var length = setPatches.length + chordEvents.length + trackFooter.length; return Buffer.concat([trackHeader, padNumber(length, 4), setPatches, chordEvents, trackFooter]); }
javascript
function (chords, settings) { var chordEvents = makeChordEvents(chords, settings); // Set all channels var setPatches = _.reduce(_.range(0xf), function (buffer, channel) { return Buffer.concat([buffer, makePatchEvent(channel, settings.chordPatch)]); }, new Buffer(0)); var length = setPatches.length + chordEvents.length + trackFooter.length; return Buffer.concat([trackHeader, padNumber(length, 4), setPatches, chordEvents, trackFooter]); }
[ "function", "(", "chords", ",", "settings", ")", "{", "var", "chordEvents", "=", "makeChordEvents", "(", "chords", ",", "settings", ")", ";", "// Set all channels", "var", "setPatches", "=", "_", ".", "reduce", "(", "_", ".", "range", "(", "0xf", ")", ",...
Return a buffer with a chord track
[ "Return", "a", "buffer", "with", "a", "chord", "track" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L153-L164
31,140
vaneenige/unswitch
src/index.js
getAxesPosition
function getAxesPosition(axes, buttons) { if (axes.length === 10) { return Math.round(axes[9] / (2 / 7) + 3.5); } const [right, left, down, up] = [...buttons].reverse(); const buttonValues = [up, right, down, left] .map((pressed, i) => (pressed.value ? i * 2 : false)) .filter(val => val !== false); if (buttonValues.length === 0) return 8; if (buttonValues.length === 2 && buttonValues[0] === 0 && buttonValues[1] === 6) return 7; return buttonValues.reduce((prev, curr) => prev + curr, 0) / buttonValues.length; }
javascript
function getAxesPosition(axes, buttons) { if (axes.length === 10) { return Math.round(axes[9] / (2 / 7) + 3.5); } const [right, left, down, up] = [...buttons].reverse(); const buttonValues = [up, right, down, left] .map((pressed, i) => (pressed.value ? i * 2 : false)) .filter(val => val !== false); if (buttonValues.length === 0) return 8; if (buttonValues.length === 2 && buttonValues[0] === 0 && buttonValues[1] === 6) return 7; return buttonValues.reduce((prev, curr) => prev + curr, 0) / buttonValues.length; }
[ "function", "getAxesPosition", "(", "axes", ",", "buttons", ")", "{", "if", "(", "axes", ".", "length", "===", "10", ")", "{", "return", "Math", ".", "round", "(", "axes", "[", "9", "]", "/", "(", "2", "/", "7", ")", "+", "3.5", ")", ";", "}", ...
Get the axes position based based on browser. @param {array} axes @param {array} buttons
[ "Get", "the", "axes", "position", "based", "based", "on", "browser", "." ]
88e073bce1e35e4faa536b912827cd2b2db238c5
https://github.com/vaneenige/unswitch/blob/88e073bce1e35e4faa536b912827cd2b2db238c5/src/index.js#L8-L19
31,141
vaneenige/unswitch
src/index.js
Unswitch
function Unswitch(settings) { const buttonState = {}; let axesPosition = 8; for (let i = buttonMappings.length - 1; i >= 0; i -= 1) { buttonState[buttonMappings[i]] = { pressed: false }; } this.update = () => { const gamepads = navigator.getGamepads(); for (let i = Object.keys(gamepads).length - 1; i >= 0; i -= 1) { if (gamepads[i] && gamepads[i].id && gamepads[i].id.indexOf(settings.side) !== -1) { this.observe(gamepads[i]); break; } } }; this.observe = (pad) => { const { buttons, axes } = pad; for (let j = buttonMappings.length - 1; j >= 0; j -= 1) { const button = buttonMappings[j]; if (buttonState[button].pressed !== buttons[j].pressed) { buttonState[button].pressed = buttons[j].pressed; if (settings[button]) { settings[button](buttonState[button].pressed); } if (settings.buttons) { settings.buttons(button, buttonState[button].pressed, settings.side); } } } if (settings.axes) { const position = getAxesPosition(axes, buttons); if (position !== axesPosition) { settings.axes(position); axesPosition = position; } } }; }
javascript
function Unswitch(settings) { const buttonState = {}; let axesPosition = 8; for (let i = buttonMappings.length - 1; i >= 0; i -= 1) { buttonState[buttonMappings[i]] = { pressed: false }; } this.update = () => { const gamepads = navigator.getGamepads(); for (let i = Object.keys(gamepads).length - 1; i >= 0; i -= 1) { if (gamepads[i] && gamepads[i].id && gamepads[i].id.indexOf(settings.side) !== -1) { this.observe(gamepads[i]); break; } } }; this.observe = (pad) => { const { buttons, axes } = pad; for (let j = buttonMappings.length - 1; j >= 0; j -= 1) { const button = buttonMappings[j]; if (buttonState[button].pressed !== buttons[j].pressed) { buttonState[button].pressed = buttons[j].pressed; if (settings[button]) { settings[button](buttonState[button].pressed); } if (settings.buttons) { settings.buttons(button, buttonState[button].pressed, settings.side); } } } if (settings.axes) { const position = getAxesPosition(axes, buttons); if (position !== axesPosition) { settings.axes(position); axesPosition = position; } } }; }
[ "function", "Unswitch", "(", "settings", ")", "{", "const", "buttonState", "=", "{", "}", ";", "let", "axesPosition", "=", "8", ";", "for", "(", "let", "i", "=", "buttonMappings", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "-=", "1", ...
Create an instance of Unswitch. @param {object} settings
[ "Create", "an", "instance", "of", "Unswitch", "." ]
88e073bce1e35e4faa536b912827cd2b2db238c5
https://github.com/vaneenige/unswitch/blob/88e073bce1e35e4faa536b912827cd2b2db238c5/src/index.js#L25-L66
31,142
perropicante/connect-redirecthost
lib/redirectHost.js
createHandler
function createHandler(to, except, pathFunc, protocol) { return function(req, res, next) { var host = req.hostname || ''; var url = req.url; if (host in except) { next(); } else { var target = new URIjs(pathFunc(host, url)) .host(to) .protocol(protocol || '') .href(); res.redirect(301, target); } }; }
javascript
function createHandler(to, except, pathFunc, protocol) { return function(req, res, next) { var host = req.hostname || ''; var url = req.url; if (host in except) { next(); } else { var target = new URIjs(pathFunc(host, url)) .host(to) .protocol(protocol || '') .href(); res.redirect(301, target); } }; }
[ "function", "createHandler", "(", "to", ",", "except", ",", "pathFunc", ",", "protocol", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "host", "=", "req", ".", "hostname", "||", "''", ";", "var", "url", "=", ...
Creates the middleware to handle the redirect @param {String} to @param {Array} except @return {Function} middleware function(req, res, next) @api private
[ "Creates", "the", "middleware", "to", "handle", "the", "redirect" ]
212b9ffda68534f4644d3eed95c55958ccc29c00
https://github.com/perropicante/connect-redirecthost/blob/212b9ffda68534f4644d3eed95c55958ccc29c00/lib/redirectHost.js#L136-L152
31,143
warehouseai/cdnup
index.js
CDNUp
function CDNUp(bucket, options) { options = options || {}; this.sharding = !!options.sharding; this.urls = arrayify(options.url || options.urls); this.mime = options.mime || {}; this.check = options.check; this.bucket = bucket; this.client = pkgcloud.storage.createClient(options.pkgcloud || {}); this.acl = options.acl; this.subdomain = options.subdomain; }
javascript
function CDNUp(bucket, options) { options = options || {}; this.sharding = !!options.sharding; this.urls = arrayify(options.url || options.urls); this.mime = options.mime || {}; this.check = options.check; this.bucket = bucket; this.client = pkgcloud.storage.createClient(options.pkgcloud || {}); this.acl = options.acl; this.subdomain = options.subdomain; }
[ "function", "CDNUp", "(", "bucket", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "sharding", "=", "!", "!", "options", ".", "sharding", ";", "this", ".", "urls", "=", "arrayify", "(", "options", ".", "url", ...
CDNup is our CDN management API. Options: - sharding: Use DNS sharding. - env: Optional forced environment. - url/urls: Array or string of a URL that we use to build our assets URLs - mime: Custom lookup object. @constructor @param {String} bucket bucket location of where you want the files to be stored. @param {Object} options Configuration for the CDN uploading. @api public
[ "CDNup", "is", "our", "CDN", "management", "API", "." ]
208e90b8236fdd52d8f90685522ef56047a30fc4
https://github.com/warehouseai/cdnup/blob/208e90b8236fdd52d8f90685522ef56047a30fc4/index.js#L24-L35
31,144
warehouseai/cdnup
index.js
arrayify
function arrayify(urls) { var tmp = Array.isArray(urls) ? urls : [urls]; return tmp.filter(Boolean); }
javascript
function arrayify(urls) { var tmp = Array.isArray(urls) ? urls : [urls]; return tmp.filter(Boolean); }
[ "function", "arrayify", "(", "urls", ")", "{", "var", "tmp", "=", "Array", ".", "isArray", "(", "urls", ")", "?", "urls", ":", "[", "urls", "]", ";", "return", "tmp", ".", "filter", "(", "Boolean", ")", ";", "}" ]
Force a single string to an array if necessary
[ "Force", "a", "single", "string", "to", "an", "array", "if", "necessary" ]
208e90b8236fdd52d8f90685522ef56047a30fc4
https://github.com/warehouseai/cdnup/blob/208e90b8236fdd52d8f90685522ef56047a30fc4/index.js#L143-L146
31,145
cloudkick/whiskey
lib/gen_makefile.js
generateMakefile
function generateMakefile(testFiles, targetPath, callback) { var template = new templates.Template('Makefile.magic'); var fullPath = path.join(targetPath, 'Makefile'); var context = { test_files: testFiles.join(' \\\n ') }; if (path.existsSync(fullPath)) { callback(new Error(sprintf('File "%s" already exists', fullPath))); return; } async.waterfall([ template.load.bind(template), function render(template, callback) { template.render(context, callback); }, function save(output, callback) { fs.writeFile(fullPath, output.join(''), callback); } ], callback); }
javascript
function generateMakefile(testFiles, targetPath, callback) { var template = new templates.Template('Makefile.magic'); var fullPath = path.join(targetPath, 'Makefile'); var context = { test_files: testFiles.join(' \\\n ') }; if (path.existsSync(fullPath)) { callback(new Error(sprintf('File "%s" already exists', fullPath))); return; } async.waterfall([ template.load.bind(template), function render(template, callback) { template.render(context, callback); }, function save(output, callback) { fs.writeFile(fullPath, output.join(''), callback); } ], callback); }
[ "function", "generateMakefile", "(", "testFiles", ",", "targetPath", ",", "callback", ")", "{", "var", "template", "=", "new", "templates", ".", "Template", "(", "'Makefile.magic'", ")", ";", "var", "fullPath", "=", "path", ".", "join", "(", "targetPath", ",...
Generate and write a Makefile with Whiskey related targets. @param {Array} testFiles Test files. @param {String} targetPath path where a generated Makefile is saved. @param {Function} callback Callback called with (err).
[ "Generate", "and", "write", "a", "Makefile", "with", "Whiskey", "related", "targets", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/gen_makefile.js#L16-L39
31,146
1999/sklad
lib/sklad.js
checkSavedData
function checkSavedData(dbName, objStore, data) { const keyValueContainer = Object.prototype.isPrototypeOf.call(skladKeyValueContainer, data); const value = keyValueContainer ? data.value : data; const objStoreMeta = objStoresMeta.get(dbName).get(objStore.name); let key = keyValueContainer ? data.key : undefined; const keyPath = objStore.keyPath || objStoreMeta.keyPath; const autoIncrement = objStore.autoIncrement || objStoreMeta.autoIncrement; if (keyPath === null) { if (!autoIncrement && key === undefined) { key = uuid(); } } else { if (typeof data !== 'object') { return false; } // TODO: support dot-separated and array keyPaths if (!autoIncrement && data[keyPath] === undefined) { data[keyPath] = uuid(); } } return key ? [value, key] : [value]; }
javascript
function checkSavedData(dbName, objStore, data) { const keyValueContainer = Object.prototype.isPrototypeOf.call(skladKeyValueContainer, data); const value = keyValueContainer ? data.value : data; const objStoreMeta = objStoresMeta.get(dbName).get(objStore.name); let key = keyValueContainer ? data.key : undefined; const keyPath = objStore.keyPath || objStoreMeta.keyPath; const autoIncrement = objStore.autoIncrement || objStoreMeta.autoIncrement; if (keyPath === null) { if (!autoIncrement && key === undefined) { key = uuid(); } } else { if (typeof data !== 'object') { return false; } // TODO: support dot-separated and array keyPaths if (!autoIncrement && data[keyPath] === undefined) { data[keyPath] = uuid(); } } return key ? [value, key] : [value]; }
[ "function", "checkSavedData", "(", "dbName", ",", "objStore", ",", "data", ")", "{", "const", "keyValueContainer", "=", "Object", ".", "prototype", ".", "isPrototypeOf", ".", "call", "(", "skladKeyValueContainer", ",", "data", ")", ";", "const", "value", "=", ...
Checks data before saving it in the object store @return {Boolean} false if saved data type is incorrect, otherwise {Array} object store function arguments
[ "Checks", "data", "before", "saving", "it", "in", "the", "object", "store" ]
6aa3479b4e9704e7ca0ed2f0fcf050440ca823b1
https://github.com/1999/sklad/blob/6aa3479b4e9704e7ca0ed2f0fcf050440ca823b1/lib/sklad.js#L68-L93
31,147
1999/sklad
lib/sklad.js
checkContainingStores
function checkContainingStores(objStoreNames) { return objStoreNames.every(function (storeName) { return (indexOf.call(this.database.objectStoreNames, storeName) !== -1); }, this); }
javascript
function checkContainingStores(objStoreNames) { return objStoreNames.every(function (storeName) { return (indexOf.call(this.database.objectStoreNames, storeName) !== -1); }, this); }
[ "function", "checkContainingStores", "(", "objStoreNames", ")", "{", "return", "objStoreNames", ".", "every", "(", "function", "(", "storeName", ")", "{", "return", "(", "indexOf", ".", "call", "(", "this", ".", "database", ".", "objectStoreNames", ",", "store...
Check whether database contains all needed stores @param {Array<String>} objStoreNames @return {Boolean}
[ "Check", "whether", "database", "contains", "all", "needed", "stores" ]
6aa3479b4e9704e7ca0ed2f0fcf050440ca823b1
https://github.com/1999/sklad/blob/6aa3479b4e9704e7ca0ed2f0fcf050440ca823b1/lib/sklad.js#L101-L105
31,148
1999/sklad
lib/sklad.js
getObjStoresMeta
function getObjStoresMeta(db, objStoreNames) { const dbMeta = objStoresMeta.get(db.name); const promises = []; objStoreNames.forEach(objStoreName => { if (dbMeta.has(objStoreName)) { return; } const promise = new Promise(resolve => { const transaction = db.transaction([objStoreName], TRANSACTION_READWRITE); transaction.oncomplete = resolve; transaction.onabort = resolve; const objStore = transaction.objectStore(objStoreName); if (objStore.autoIncrement !== undefined) { dbMeta.set(objStoreName, { autoIncrement: objStore.autoIncrement, keyPath: objStore.keyPath }); return; } let autoIncrement; if (objStore.keyPath !== null) { // if key path is defined it's possible to insert only objects // but if key generator (autoIncrement) is not defined the inserted objects // must contain field(s) described in keyPath value otherwise IDBObjectStore.add op fails // so if we run ODBObjectStore.add with an empty object and it fails, this means that // autoIncrement property was false. Otherwise - true // if key path is array autoIncrement property can't be true if (Array.isArray(objStore.keyPath)) { autoIncrement = false; } else { try { objStore.add({}); autoIncrement = true; } catch (ex) { autoIncrement = false; } } } else { // if key path is not defined it's possible to insert any kind of data // but if key generator (autoIncrement) is not defined you should set it explicitly // so if we run ODBObjectStore.add with one argument and it fails, this means that // autoIncrement property was false. Otherwise - true try { objStore.add('some value'); autoIncrement = true; } catch (ex) { autoIncrement = false; } } // save meta properties dbMeta.set(objStoreName, { autoIncrement: autoIncrement, keyPath: objStore.keyPath }); // and abort transaction so that new record is forgotten transaction.abort(); }); promises.push(promise); }); return Promise.all(promises); }
javascript
function getObjStoresMeta(db, objStoreNames) { const dbMeta = objStoresMeta.get(db.name); const promises = []; objStoreNames.forEach(objStoreName => { if (dbMeta.has(objStoreName)) { return; } const promise = new Promise(resolve => { const transaction = db.transaction([objStoreName], TRANSACTION_READWRITE); transaction.oncomplete = resolve; transaction.onabort = resolve; const objStore = transaction.objectStore(objStoreName); if (objStore.autoIncrement !== undefined) { dbMeta.set(objStoreName, { autoIncrement: objStore.autoIncrement, keyPath: objStore.keyPath }); return; } let autoIncrement; if (objStore.keyPath !== null) { // if key path is defined it's possible to insert only objects // but if key generator (autoIncrement) is not defined the inserted objects // must contain field(s) described in keyPath value otherwise IDBObjectStore.add op fails // so if we run ODBObjectStore.add with an empty object and it fails, this means that // autoIncrement property was false. Otherwise - true // if key path is array autoIncrement property can't be true if (Array.isArray(objStore.keyPath)) { autoIncrement = false; } else { try { objStore.add({}); autoIncrement = true; } catch (ex) { autoIncrement = false; } } } else { // if key path is not defined it's possible to insert any kind of data // but if key generator (autoIncrement) is not defined you should set it explicitly // so if we run ODBObjectStore.add with one argument and it fails, this means that // autoIncrement property was false. Otherwise - true try { objStore.add('some value'); autoIncrement = true; } catch (ex) { autoIncrement = false; } } // save meta properties dbMeta.set(objStoreName, { autoIncrement: autoIncrement, keyPath: objStore.keyPath }); // and abort transaction so that new record is forgotten transaction.abort(); }); promises.push(promise); }); return Promise.all(promises); }
[ "function", "getObjStoresMeta", "(", "db", ",", "objStoreNames", ")", "{", "const", "dbMeta", "=", "objStoresMeta", ".", "get", "(", "db", ".", "name", ")", ";", "const", "promises", "=", "[", "]", ";", "objStoreNames", ".", "forEach", "(", "objStoreName",...
autoIncrement is broken in IE family. Run this transaction to get its value on every object store @param {IDBDatabase} db @param {Array<String>} objStoreNames @return {Promise} @see http://stackoverflow.com/questions/35682165/indexeddb-in-ie11-edge-why-is-objstore-autoincrement-undefined @see https://connect.microsoft.com/IE/Feedback/Details/772726
[ "autoIncrement", "is", "broken", "in", "IE", "family", ".", "Run", "this", "transaction", "to", "get", "its", "value", "on", "every", "object", "store" ]
6aa3479b4e9704e7ca0ed2f0fcf050440ca823b1
https://github.com/1999/sklad/blob/6aa3479b4e9704e7ca0ed2f0fcf050440ca823b1/lib/sklad.js#L118-L189
31,149
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
createProgram
function createProgram( gl, shaders, opt_attribs, opt_locations, opt_errorCallback) { var errFn = opt_errorCallback || error; var program = gl.createProgram(); shaders.forEach(function(shader) { gl.attachShader(program, shader); }); if (opt_attribs) { opt_attribs.forEach(function(attrib, ndx) { gl.bindAttribLocation( program, opt_locations ? opt_locations[ndx] : ndx, attrib); }); } gl.linkProgram(program); // Check the link status var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link var lastError = gl.getProgramInfoLog(program); errFn("Error in program linking:" + lastError); gl.deleteProgram(program); return null; } return program; }
javascript
function createProgram( gl, shaders, opt_attribs, opt_locations, opt_errorCallback) { var errFn = opt_errorCallback || error; var program = gl.createProgram(); shaders.forEach(function(shader) { gl.attachShader(program, shader); }); if (opt_attribs) { opt_attribs.forEach(function(attrib, ndx) { gl.bindAttribLocation( program, opt_locations ? opt_locations[ndx] : ndx, attrib); }); } gl.linkProgram(program); // Check the link status var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link var lastError = gl.getProgramInfoLog(program); errFn("Error in program linking:" + lastError); gl.deleteProgram(program); return null; } return program; }
[ "function", "createProgram", "(", "gl", ",", "shaders", ",", "opt_attribs", ",", "opt_locations", ",", "opt_errorCallback", ")", "{", "var", "errFn", "=", "opt_errorCallback", "||", "error", ";", "var", "program", "=", "gl", ".", "createProgram", "(", ")", "...
Creates a program, attaches shaders, binds attrib locations, links the program and calls useProgram. @param {WebGLShader[]} shaders The shaders to attach @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations. @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message. @memberOf module:webgl-utils
[ "Creates", "a", "program", "attaches", "shaders", "binds", "attrib", "locations", "links", "the", "program", "and", "calls", "useProgram", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L124-L152
31,150
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
getBindPointForSamplerType
function getBindPointForSamplerType(gl, type) { if (type === gl.SAMPLER_2D) return gl.TEXTURE_2D; // eslint-disable-line if (type === gl.SAMPLER_CUBE) return gl.TEXTURE_CUBE_MAP; // eslint-disable-line return undefined; }
javascript
function getBindPointForSamplerType(gl, type) { if (type === gl.SAMPLER_2D) return gl.TEXTURE_2D; // eslint-disable-line if (type === gl.SAMPLER_CUBE) return gl.TEXTURE_CUBE_MAP; // eslint-disable-line return undefined; }
[ "function", "getBindPointForSamplerType", "(", "gl", ",", "type", ")", "{", "if", "(", "type", "===", "gl", ".", "SAMPLER_2D", ")", "return", "gl", ".", "TEXTURE_2D", ";", "// eslint-disable-line", "if", "(", "type", "===", "gl", ".", "SAMPLER_CUBE", ")", ...
Returns the corresponding bind point for a given sampler type
[ "Returns", "the", "corresponding", "bind", "point", "for", "a", "given", "sampler", "type" ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L246-L250
31,151
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
getExtensionWithKnownPrefixes
function getExtensionWithKnownPrefixes(gl, name) { for (var ii = 0; ii < browserPrefixes.length; ++ii) { var prefixedName = browserPrefixes[ii] + name; var ext = gl.getExtension(prefixedName); if (ext) { return ext; } } return undefined; }
javascript
function getExtensionWithKnownPrefixes(gl, name) { for (var ii = 0; ii < browserPrefixes.length; ++ii) { var prefixedName = browserPrefixes[ii] + name; var ext = gl.getExtension(prefixedName); if (ext) { return ext; } } return undefined; }
[ "function", "getExtensionWithKnownPrefixes", "(", "gl", ",", "name", ")", "{", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "browserPrefixes", ".", "length", ";", "++", "ii", ")", "{", "var", "prefixedName", "=", "browserPrefixes", "[", "ii", "]", ...
Given an extension name like WEBGL_compressed_texture_s3tc returns the supported version extension, like WEBKIT_WEBGL_compressed_teture_s3tc @param {string} name Name of extension to look for @return {WebGLExtension} The extension or undefined if not found. @memberOf module:webgl-utils
[ "Given", "an", "extension", "name", "like", "WEBGL_compressed_texture_s3tc", "returns", "the", "supported", "version", "extension", "like", "WEBKIT_WEBGL_compressed_teture_s3tc" ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L745-L754
31,152
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
resizeCanvasToDisplaySize
function resizeCanvasToDisplaySize(canvas, multiplier) { multiplier = multiplier || 1; var width = canvas.clientWidth * multiplier | 0; var height = canvas.clientHeight * multiplier | 0; if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; return true; } return false; }
javascript
function resizeCanvasToDisplaySize(canvas, multiplier) { multiplier = multiplier || 1; var width = canvas.clientWidth * multiplier | 0; var height = canvas.clientHeight * multiplier | 0; if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; return true; } return false; }
[ "function", "resizeCanvasToDisplaySize", "(", "canvas", ",", "multiplier", ")", "{", "multiplier", "=", "multiplier", "||", "1", ";", "var", "width", "=", "canvas", ".", "clientWidth", "*", "multiplier", "|", "0", ";", "var", "height", "=", "canvas", ".", ...
Resize a canvas to match the size its displayed. @param {HTMLCanvasElement} canvas The canvas to resize. @param {number} [multiplier] amount to multiply by. Pass in window.devicePixelRatio for native pixels. @return {boolean} true if the canvas was resized. @memberOf module:webgl-utils
[ "Resize", "a", "canvas", "to", "match", "the", "size", "its", "displayed", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L764-L774
31,153
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
getNumElementsFromNonIndexedArrays
function getNumElementsFromNonIndexedArrays(arrays) { var key = Object.keys(arrays)[0]; var array = arrays[key]; if (isArrayBuffer(array)) { return array.numElements; } else { return array.data.length / array.numComponents; } }
javascript
function getNumElementsFromNonIndexedArrays(arrays) { var key = Object.keys(arrays)[0]; var array = arrays[key]; if (isArrayBuffer(array)) { return array.numElements; } else { return array.data.length / array.numComponents; } }
[ "function", "getNumElementsFromNonIndexedArrays", "(", "arrays", ")", "{", "var", "key", "=", "Object", ".", "keys", "(", "arrays", ")", "[", "0", "]", ";", "var", "array", "=", "arrays", "[", "key", "]", ";", "if", "(", "isArrayBuffer", "(", "array", ...
tries to get the number of elements from a set of arrays.
[ "tries", "to", "get", "the", "number", "of", "elements", "from", "a", "set", "of", "arrays", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L979-L987
31,154
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
createBuffersFromArrays
function createBuffersFromArrays(gl, arrays) { var buffers = { }; Object.keys(arrays).forEach(function(key) { var type = key === "indices" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; var array = makeTypedArray(arrays[key], name); buffers[key] = createBufferFromTypedArray(gl, array, type); }); // hrm if (arrays.indices) { buffers.numElements = arrays.indices.length; } else if (arrays.position) { buffers.numElements = arrays.position.length / 3; } return buffers; }
javascript
function createBuffersFromArrays(gl, arrays) { var buffers = { }; Object.keys(arrays).forEach(function(key) { var type = key === "indices" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; var array = makeTypedArray(arrays[key], name); buffers[key] = createBufferFromTypedArray(gl, array, type); }); // hrm if (arrays.indices) { buffers.numElements = arrays.indices.length; } else if (arrays.position) { buffers.numElements = arrays.position.length / 3; } return buffers; }
[ "function", "createBuffersFromArrays", "(", "gl", ",", "arrays", ")", "{", "var", "buffers", "=", "{", "}", ";", "Object", ".", "keys", "(", "arrays", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "type", "=", "key", "===", "\"in...
Creates buffers from typed arrays Given something like this var arrays = { positions: [1, 2, 3], normals: [0, 0, 1], } returns something like buffers = { positions: WebGLBuffer, normals: WebGLBuffer, } If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER. @param {WebGLRenderingContext} gl A WebGLRenderingContext. @param {Object<string, array|typedarray>} arrays @return {Object<string, WebGLBuffer>} returns an object with one WebGLBuffer per array @memberOf module:webgl-utils
[ "Creates", "buffers", "from", "typed", "arrays" ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L1159-L1175
31,155
leonardpauli/docs
design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js
drawBufferInfo
function drawBufferInfo(gl, bufferInfo, primitiveType, count, offset) { var indices = bufferInfo.indices; primitiveType = primitiveType === undefined ? gl.TRIANGLES : primitiveType; var numElements = count === undefined ? bufferInfo.numElements : count; offset = offset === undefined ? offset : 0; if (indices) { gl.drawElements(primitiveType, numElements, gl.UNSIGNED_SHORT, offset); } else { gl.drawArrays(primitiveType, offset, numElements); } }
javascript
function drawBufferInfo(gl, bufferInfo, primitiveType, count, offset) { var indices = bufferInfo.indices; primitiveType = primitiveType === undefined ? gl.TRIANGLES : primitiveType; var numElements = count === undefined ? bufferInfo.numElements : count; offset = offset === undefined ? offset : 0; if (indices) { gl.drawElements(primitiveType, numElements, gl.UNSIGNED_SHORT, offset); } else { gl.drawArrays(primitiveType, offset, numElements); } }
[ "function", "drawBufferInfo", "(", "gl", ",", "bufferInfo", ",", "primitiveType", ",", "count", ",", "offset", ")", "{", "var", "indices", "=", "bufferInfo", ".", "indices", ";", "primitiveType", "=", "primitiveType", "===", "undefined", "?", "gl", ".", "TRI...
Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate normally you'd call `gl.drawElements` or `gl.drawArrays` yourself but calling this means if you switch from indexed data to non-indexed data you don't have to remember to update your draw call. @param {WebGLRenderingContext} gl A WebGLRenderingContext @param {module:webgl-utils.BufferInfo} bufferInfo as returned from createBufferInfoFromArrays @param {enum} [primitiveType] eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...) @param {number} [count] An optional count. Defaults to bufferInfo.numElements @param {number} [offset] An optional offset. Defaults to 0. @memberOf module:webgl-utils
[ "Calls", "gl", ".", "drawElements", "or", "gl", ".", "drawArrays", "whichever", "is", "appropriate" ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/design/gpu-programming/webgl/experiment/game-of-life/external/webgl-utils.js#L1191-L1201
31,156
jose-pleonasm/py-logging
core/logging.js
getLogger
function getLogger(name) { name = name || ''; if (!name) { return Manager.root; } else { return Manager.getLogger(name); } }
javascript
function getLogger(name) { name = name || ''; if (!name) { return Manager.root; } else { return Manager.getLogger(name); } }
[ "function", "getLogger", "(", "name", ")", "{", "name", "=", "name", "||", "''", ";", "if", "(", "!", "name", ")", "{", "return", "Manager", ".", "root", ";", "}", "else", "{", "return", "Manager", ".", "getLogger", "(", "name", ")", ";", "}", "}...
Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. @function @memberof module:py-logging @param {string} [name] @return {Logger}
[ "Return", "a", "logger", "with", "the", "specified", "name", "creating", "it", "if", "necessary", ".", "If", "no", "name", "is", "specified", "return", "the", "root", "logger", "." ]
598f41284311ea6a837d4ba56236301abe689b09
https://github.com/jose-pleonasm/py-logging/blob/598f41284311ea6a837d4ba56236301abe689b09/core/logging.js#L672-L680
31,157
basisjs/basisjs-tools-build
lib/common/files.js
function(filename){ // resolve by symlink if possible for (var from in this.symlinks) if (filename.indexOf(from) === 0 && (filename === from || filename[from.length] === '/')) return this.symlinks[from] + filename.substr(from.length); return path.resolve(this.fsBaseURI, filename.replace(/^[\\\/]/, '')); }
javascript
function(filename){ // resolve by symlink if possible for (var from in this.symlinks) if (filename.indexOf(from) === 0 && (filename === from || filename[from.length] === '/')) return this.symlinks[from] + filename.substr(from.length); return path.resolve(this.fsBaseURI, filename.replace(/^[\\\/]/, '')); }
[ "function", "(", "filename", ")", "{", "// resolve by symlink if possible", "for", "(", "var", "from", "in", "this", ".", "symlinks", ")", "if", "(", "filename", ".", "indexOf", "(", "from", ")", "===", "0", "&&", "(", "filename", "===", "from", "||", "f...
Returns absolute filesystem filename. @param {string} filename @return {string}
[ "Returns", "absolute", "filesystem", "filename", "." ]
177018ab31b225cddb6a184693fe4746512e7af1
https://github.com/basisjs/basisjs-tools-build/blob/177018ab31b225cddb6a184693fe4746512e7af1/lib/common/files.js#L320-L327
31,158
basisjs/basisjs-tools-build
lib/common/files.js
function(fileRef){ var filename; var file; if (fileRef instanceof File) { file = fileRef; filename = file.filename; } else { filename = abspath(this.baseURI, fileRef); file = this.map[filename]; if (!file) { this.flow.warn({ file: filename, message: 'File `' + fileRef + '` not found in map' }); return; } } // remove links for (var i = file.linkTo.length, linkTo; linkTo = file.linkTo[i]; i--) file.unlink(linkTo); for (var i = file.linkBack.length, linkBack; linkBack = file.linkBack[i]; i--) linkBack.unlink(file); // remove from queue var index = this.queue.indexOf(file); if (index != -1) this.queue.splice(index, 1); // remove from map if (filename) delete this.map[filename]; }
javascript
function(fileRef){ var filename; var file; if (fileRef instanceof File) { file = fileRef; filename = file.filename; } else { filename = abspath(this.baseURI, fileRef); file = this.map[filename]; if (!file) { this.flow.warn({ file: filename, message: 'File `' + fileRef + '` not found in map' }); return; } } // remove links for (var i = file.linkTo.length, linkTo; linkTo = file.linkTo[i]; i--) file.unlink(linkTo); for (var i = file.linkBack.length, linkBack; linkBack = file.linkBack[i]; i--) linkBack.unlink(file); // remove from queue var index = this.queue.indexOf(file); if (index != -1) this.queue.splice(index, 1); // remove from map if (filename) delete this.map[filename]; }
[ "function", "(", "fileRef", ")", "{", "var", "filename", ";", "var", "file", ";", "if", "(", "fileRef", "instanceof", "File", ")", "{", "file", "=", "fileRef", ";", "filename", "=", "file", ".", "filename", ";", "}", "else", "{", "filename", "=", "ab...
Remove a file from manager and break all links between files. @param {File|string} fileRef File name or File instance to be removed.
[ "Remove", "a", "file", "from", "manager", "and", "break", "all", "links", "between", "files", "." ]
177018ab31b225cddb6a184693fe4746512e7af1
https://github.com/basisjs/basisjs-tools-build/blob/177018ab31b225cddb6a184693fe4746512e7af1/lib/common/files.js#L511-L551
31,159
rrharvey/grunt-file-blocks
tasks/fileblocks.js
function(data, options) { var configs = []; if (_.isArray(data)) { data.forEach(function(block) { configs.push(new BlockConfig(block.name, block, options)); }); } else if (_.isPlainObject(data)) { _.forOwn(data, function(value, name) { configs.push(new BlockConfig(name, value, options)); }); } else { grunt.warn('Block configuration must be an array or object.'); } return configs; }
javascript
function(data, options) { var configs = []; if (_.isArray(data)) { data.forEach(function(block) { configs.push(new BlockConfig(block.name, block, options)); }); } else if (_.isPlainObject(data)) { _.forOwn(data, function(value, name) { configs.push(new BlockConfig(name, value, options)); }); } else { grunt.warn('Block configuration must be an array or object.'); } return configs; }
[ "function", "(", "data", ",", "options", ")", "{", "var", "configs", "=", "[", "]", ";", "if", "(", "_", ".", "isArray", "(", "data", ")", ")", "{", "data", ".", "forEach", "(", "function", "(", "block", ")", "{", "configs", ".", "push", "(", "...
Normalize and return block configurations from the Gruntfile. @param {Object[]|Object.<string, object>} blocks - The block configurations from the Gruntfile. @returns {BlockConfig[]}
[ "Normalize", "and", "return", "block", "configurations", "from", "the", "Gruntfile", "." ]
c1e3bfcb33df76ca820de580da3864085bfaed44
https://github.com/rrharvey/grunt-file-blocks/blob/c1e3bfcb33df76ca820de580da3864085bfaed44/tasks/fileblocks.js#L25-L41
31,160
jose-pleonasm/py-logging
core/handlers.js
ConsoleHandler
function ConsoleHandler(level, grouping, collapsed) { grouping = typeof grouping !== 'undefined' ? grouping : true; collapsed = typeof collapsed !== 'undefined' ? collapsed : false; Handler.call(this, level); this._grouping = grouping; this._groupMethod = collapsed ? 'groupCollapsed' : 'group'; this._openGroup = ''; }
javascript
function ConsoleHandler(level, grouping, collapsed) { grouping = typeof grouping !== 'undefined' ? grouping : true; collapsed = typeof collapsed !== 'undefined' ? collapsed : false; Handler.call(this, level); this._grouping = grouping; this._groupMethod = collapsed ? 'groupCollapsed' : 'group'; this._openGroup = ''; }
[ "function", "ConsoleHandler", "(", "level", ",", "grouping", ",", "collapsed", ")", "{", "grouping", "=", "typeof", "grouping", "!==", "'undefined'", "?", "grouping", ":", "true", ";", "collapsed", "=", "typeof", "collapsed", "!==", "'undefined'", "?", "collap...
Console handler. @constructor ConsoleHandler @extends Handler @param {number} [level] @param {boolean} [grouping=true] @param {boolean} [collapsed=false]
[ "Console", "handler", "." ]
598f41284311ea6a837d4ba56236301abe689b09
https://github.com/jose-pleonasm/py-logging/blob/598f41284311ea6a837d4ba56236301abe689b09/core/handlers.js#L81-L90
31,161
lbdremy/scrapinode
lib/error/scrapinode-error.js
ScrapinodeError
function ScrapinodeError(message){ Error.call(this); Error.captureStackTrace(this,arguments.callee); this.name = 'ScrapinodeError'; this.message = message; }
javascript
function ScrapinodeError(message){ Error.call(this); Error.captureStackTrace(this,arguments.callee); this.name = 'ScrapinodeError'; this.message = message; }
[ "function", "ScrapinodeError", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'ScrapinodeError'", ";", "this", "...
Create a new `ScrapinodeError` @constructor @inherit {Error} @api private
[ "Create", "a", "new", "ScrapinodeError" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/error/scrapinode-error.js#L21-L26
31,162
jose-pleonasm/py-logging
nodekit/index.js
FileHandler
function FileHandler(filename, mode, encoding, delay) { mode = mode || 'a'; encoding = typeof encoding !== 'undefined' ? encoding : 'utf8'; delay = typeof delay !== 'undefined' ? delay : false; /** * @private * @type {string} */ this._filename = filename; /** * @private * @type {string} */ this._mode = mode; /** * @private * @type {string} */ this._encoding = encoding; if (delay) { StreamHandler.call(this); this._stream = null; } else { StreamHandler.call(this, this._open()); } }
javascript
function FileHandler(filename, mode, encoding, delay) { mode = mode || 'a'; encoding = typeof encoding !== 'undefined' ? encoding : 'utf8'; delay = typeof delay !== 'undefined' ? delay : false; /** * @private * @type {string} */ this._filename = filename; /** * @private * @type {string} */ this._mode = mode; /** * @private * @type {string} */ this._encoding = encoding; if (delay) { StreamHandler.call(this); this._stream = null; } else { StreamHandler.call(this, this._open()); } }
[ "function", "FileHandler", "(", "filename", ",", "mode", ",", "encoding", ",", "delay", ")", "{", "mode", "=", "mode", "||", "'a'", ";", "encoding", "=", "typeof", "encoding", "!==", "'undefined'", "?", "encoding", ":", "'utf8'", ";", "delay", "=", "type...
File handler. @constructor FileHandler @extends StreamHandler @param {string} filename @param {string} [mode=a] {@link https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback} @param {string} [encoding=utf8] {@link https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings} @param {boolean} [delay=false]
[ "File", "handler", "." ]
598f41284311ea6a837d4ba56236301abe689b09
https://github.com/jose-pleonasm/py-logging/blob/598f41284311ea6a837d4ba56236301abe689b09/nodekit/index.js#L127-L157
31,163
jose-pleonasm/py-logging
nodekit/index.js
RotatingFileHandler
function RotatingFileHandler(filename, mode, maxBytes, backupCount, encoding, delay) { mode = mode || 'a'; maxBytes = typeof maxBytes !== 'undefined' ? maxBytes : 0; backupCount = typeof backupCount !== 'undefined' ? backupCount : 0; encoding = typeof encoding !== 'undefined' ? encoding : 'utf8'; delay = typeof delay !== 'undefined' ? delay : false; if (maxBytes > 0) { mode = 'a'; } FileHandler.call(this, filename, mode, encoding, delay); /** * @private * @type {number} */ this._maxBytes = maxBytes; /** * @private * @type {number} */ this._backupCount = backupCount; /** * @private * @type {Promise} */ this._chain = Promise.resolve(); }
javascript
function RotatingFileHandler(filename, mode, maxBytes, backupCount, encoding, delay) { mode = mode || 'a'; maxBytes = typeof maxBytes !== 'undefined' ? maxBytes : 0; backupCount = typeof backupCount !== 'undefined' ? backupCount : 0; encoding = typeof encoding !== 'undefined' ? encoding : 'utf8'; delay = typeof delay !== 'undefined' ? delay : false; if (maxBytes > 0) { mode = 'a'; } FileHandler.call(this, filename, mode, encoding, delay); /** * @private * @type {number} */ this._maxBytes = maxBytes; /** * @private * @type {number} */ this._backupCount = backupCount; /** * @private * @type {Promise} */ this._chain = Promise.resolve(); }
[ "function", "RotatingFileHandler", "(", "filename", ",", "mode", ",", "maxBytes", ",", "backupCount", ",", "encoding", ",", "delay", ")", "{", "mode", "=", "mode", "||", "'a'", ";", "maxBytes", "=", "typeof", "maxBytes", "!==", "'undefined'", "?", "maxBytes"...
Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size. @constructor RotatingFileHandler @extends FileHandler @param {string} filename @param {string} [mode=a] {@link https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback} @param {number} [maxBytes=0] @param {number} [backupCount=0] @param {string} [encoding=utf8] {@link https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings} @param {boolean} [delay=false]
[ "Handler", "for", "logging", "to", "a", "set", "of", "files", "which", "switches", "from", "one", "file", "to", "the", "next", "when", "the", "current", "file", "reaches", "a", "certain", "size", "." ]
598f41284311ea6a837d4ba56236301abe689b09
https://github.com/jose-pleonasm/py-logging/blob/598f41284311ea6a837d4ba56236301abe689b09/nodekit/index.js#L205-L236
31,164
somesocks/vet
dist/utils/accepts.js
accepts
function accepts(func, validator, message) { message = messageBuilder(message || 'vet/utils/accepts error!'); return function wrapper(){ var args = arguments; if (validator.apply(this, args)) { return func.apply(this, args); } else { throw new Error(message.apply(this, args)); } }; }
javascript
function accepts(func, validator, message) { message = messageBuilder(message || 'vet/utils/accepts error!'); return function wrapper(){ var args = arguments; if (validator.apply(this, args)) { return func.apply(this, args); } else { throw new Error(message.apply(this, args)); } }; }
[ "function", "accepts", "(", "func", ",", "validator", ",", "message", ")", "{", "message", "=", "messageBuilder", "(", "message", "||", "'vet/utils/accepts error!'", ")", ";", "return", "function", "wrapper", "(", ")", "{", "var", "args", "=", "arguments", "...
Wraps a function in a validator which checks its arguments, and throws an error if the arguments are bad. @param func - the function to wrap @param validator - the validator function. This gets passed the arguments as an array @param message - an optional message string to pass into the error thrown @returns a wrapped function that throws an error if the arguments do not pass validation @memberof vet.utils
[ "Wraps", "a", "function", "in", "a", "validator", "which", "checks", "its", "arguments", "and", "throws", "an", "error", "if", "the", "arguments", "are", "bad", "." ]
4557abeb6a8b470cb4a5823a2cc802c825ef29ef
https://github.com/somesocks/vet/blob/4557abeb6a8b470cb4a5823a2cc802c825ef29ef/dist/utils/accepts.js#L18-L29
31,165
phovea/generator-phovea
generators/init-product/templates/plain/build.js
toRepoUrl
function toRepoUrl(url) { if (url.startsWith('git@')) { if (argv.useSSH) { return url; } // have an ssh url need an http url const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/); return `https://${m[3]}/${m[4]}.git`; } if (url.startsWith('http')) { if (!argv.useSSH) { return url; } // have a http url need an ssh url const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/); return `git@${m[2]}:${m[4]}.git`; } if (!url.includes('/')) { url = `Caleydo/${url}`; } if (argv.useSSH) { return `git@github.com:${url}.git`; } return `https://github.com/${url}.git`; }
javascript
function toRepoUrl(url) { if (url.startsWith('git@')) { if (argv.useSSH) { return url; } // have an ssh url need an http url const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/); return `https://${m[3]}/${m[4]}.git`; } if (url.startsWith('http')) { if (!argv.useSSH) { return url; } // have a http url need an ssh url const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/); return `git@${m[2]}:${m[4]}.git`; } if (!url.includes('/')) { url = `Caleydo/${url}`; } if (argv.useSSH) { return `git@github.com:${url}.git`; } return `https://github.com/${url}.git`; }
[ "function", "toRepoUrl", "(", "url", ")", "{", "if", "(", "url", ".", "startsWith", "(", "'git@'", ")", ")", "{", "if", "(", "argv", ".", "useSSH", ")", "{", "return", "url", ";", "}", "// have an ssh url need an http url", "const", "m", "=", "url", "....
generates a repo url to clone depending on the argv.useSSH option @param {string} url the repo url either in git@ for https:// form @returns the clean repo url
[ "generates", "a", "repo", "url", "to", "clone", "depending", "on", "the", "argv", ".", "useSSH", "option" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/init-product/templates/plain/build.js#L57-L81
31,166
phovea/generator-phovea
generators/init-product/templates/plain/build.js
guessUserName
function guessUserName(repo) { // extract the host const host = repo.match(/:\/\/([^/]+)/)[1]; const hostClean = host.replace(/\./g, '_').toUpperCase(); // e.g. GITHUB_COM_CREDENTIALS const envVar = process.env[`${hostClean}_CREDENTIALS`]; if (envVar) { return envVar; } return process.env.PHOVEA_GITHUB_CREDENTIALS; }
javascript
function guessUserName(repo) { // extract the host const host = repo.match(/:\/\/([^/]+)/)[1]; const hostClean = host.replace(/\./g, '_').toUpperCase(); // e.g. GITHUB_COM_CREDENTIALS const envVar = process.env[`${hostClean}_CREDENTIALS`]; if (envVar) { return envVar; } return process.env.PHOVEA_GITHUB_CREDENTIALS; }
[ "function", "guessUserName", "(", "repo", ")", "{", "// extract the host", "const", "host", "=", "repo", ".", "match", "(", "/", ":\\/\\/([^/]+)", "/", ")", "[", "1", "]", ";", "const", "hostClean", "=", "host", ".", "replace", "(", "/", "\\.", "/", "g...
guesses the credentials environment variable based on the given repository hostname @param {string} repo
[ "guesses", "the", "credentials", "environment", "variable", "based", "on", "the", "given", "repository", "hostname" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/init-product/templates/plain/build.js#L87-L97
31,167
phovea/generator-phovea
generators/init-product/templates/plain/build.js
spawn
function spawn(cmd, args, opts) { const spawn = require('child_process').spawn; const _ = require('lodash'); return new Promise((resolve, reject) => { const p = spawn(cmd, typeof args === 'string' ? args.split(' ') : args, _.merge({stdio: argv.quiet ? ['ignore', 'pipe', 'pipe'] : ['ignore', 1, 2]}, opts)); const out = []; if (p.stdout) { p.stdout.on('data', (chunk) => out.push(chunk)); } if (p.stderr) { p.stderr.on('data', (chunk) => out.push(chunk)); } p.on('close', (code, signal) => { if (code === 0) { console.info(cmd, 'ok status code', code, signal); resolve(code); } else { console.error(cmd, 'status code', code, signal); if (args.quiet) { // log output what has been captured console.log(out.join('\n')); } reject(`${cmd} failed with status code ${code} ${signal}`); } }); }); }
javascript
function spawn(cmd, args, opts) { const spawn = require('child_process').spawn; const _ = require('lodash'); return new Promise((resolve, reject) => { const p = spawn(cmd, typeof args === 'string' ? args.split(' ') : args, _.merge({stdio: argv.quiet ? ['ignore', 'pipe', 'pipe'] : ['ignore', 1, 2]}, opts)); const out = []; if (p.stdout) { p.stdout.on('data', (chunk) => out.push(chunk)); } if (p.stderr) { p.stderr.on('data', (chunk) => out.push(chunk)); } p.on('close', (code, signal) => { if (code === 0) { console.info(cmd, 'ok status code', code, signal); resolve(code); } else { console.error(cmd, 'status code', code, signal); if (args.quiet) { // log output what has been captured console.log(out.join('\n')); } reject(`${cmd} failed with status code ${code} ${signal}`); } }); }); }
[ "function", "spawn", "(", "cmd", ",", "args", ",", "opts", ")", "{", "const", "spawn", "=", "require", "(", "'child_process'", ")", ".", "spawn", ";", "const", "_", "=", "require", "(", "'lodash'", ")", ";", "return", "new", "Promise", "(", "(", "res...
spawns a child process @param cmd command as array @param args arguments @param opts options @returns a promise with the result code or a reject with the error string
[ "spawns", "a", "child", "process" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/init-product/templates/plain/build.js#L190-L216
31,168
phovea/generator-phovea
generators/init-product/templates/plain/build.js
npm
function npm(cwd, cmd) { console.log(cwd, chalk.blue('running npm', cmd)); const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; return spawn(npm, (cmd || 'install').split(' '), {cwd, env}); }
javascript
function npm(cwd, cmd) { console.log(cwd, chalk.blue('running npm', cmd)); const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; return spawn(npm, (cmd || 'install').split(' '), {cwd, env}); }
[ "function", "npm", "(", "cwd", ",", "cmd", ")", "{", "console", ".", "log", "(", "cwd", ",", "chalk", ".", "blue", "(", "'running npm'", ",", "cmd", ")", ")", ";", "const", "npm", "=", "process", ".", "platform", "===", "'win32'", "?", "'npm.cmd'", ...
run npm with the given args @param cwd working directory @param cmd the command to execute as a string @return {*}
[ "run", "npm", "with", "the", "given", "args" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/init-product/templates/plain/build.js#L224-L228
31,169
phovea/generator-phovea
generators/init-product/templates/plain/build.js
docker
function docker(cwd, cmd) { console.log(cwd, chalk.blue('running docker', cmd)); return spawn('docker', (cmd || 'build .').split(' '), {cwd, env}); }
javascript
function docker(cwd, cmd) { console.log(cwd, chalk.blue('running docker', cmd)); return spawn('docker', (cmd || 'build .').split(' '), {cwd, env}); }
[ "function", "docker", "(", "cwd", ",", "cmd", ")", "{", "console", ".", "log", "(", "cwd", ",", "chalk", ".", "blue", "(", "'running docker'", ",", "cmd", ")", ")", ";", "return", "spawn", "(", "'docker'", ",", "(", "cmd", "||", "'build .'", ")", "...
runs docker command @param cwd @param cmd @return {*}
[ "runs", "docker", "command" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/init-product/templates/plain/build.js#L236-L239
31,170
phovea/generator-phovea
generators/init-product/templates/plain/build.js
yo
function yo(generator, options, cwd) { const yeoman = require('yeoman-environment'); // call yo internally const yeomanEnv = yeoman.createEnv([], {cwd, env}, quiet ? createQuietTerminalAdapter() : undefined); yeomanEnv.register(require.resolve('generator-phovea/generators/' + generator), 'phovea:' + generator); return new Promise((resolve, reject) => { try { console.log(cwd, chalk.blue('running yo phovea:' + generator)); yeomanEnv.run('phovea:' + generator, options, resolve); } catch (e) { console.error('error', e, e.stack); reject(e); } }); }
javascript
function yo(generator, options, cwd) { const yeoman = require('yeoman-environment'); // call yo internally const yeomanEnv = yeoman.createEnv([], {cwd, env}, quiet ? createQuietTerminalAdapter() : undefined); yeomanEnv.register(require.resolve('generator-phovea/generators/' + generator), 'phovea:' + generator); return new Promise((resolve, reject) => { try { console.log(cwd, chalk.blue('running yo phovea:' + generator)); yeomanEnv.run('phovea:' + generator, options, resolve); } catch (e) { console.error('error', e, e.stack); reject(e); } }); }
[ "function", "yo", "(", "generator", ",", "options", ",", "cwd", ")", "{", "const", "yeoman", "=", "require", "(", "'yeoman-environment'", ")", ";", "// call yo internally", "const", "yeomanEnv", "=", "yeoman", ".", "createEnv", "(", "[", "]", ",", "{", "cw...
runs yo internally @param generator @param options @param cwd
[ "runs", "yo", "internally" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/init-product/templates/plain/build.js#L295-L309
31,171
Strider-CD/strider-simple-runner
lib/jobqueue.js
function (job, config, callback) { var task = { job: job, config: config, callback: callback || function () { } }; task.id = task.job._id; // Tasks with identical keys will be prevented from being scheduled concurrently. task.key = task.job.project + branchFromJob(task.job); this.tasks.push(task); // Defer task execution to the next event loop tick to ensure that the push() function's // callback is *always* invoked asynchronously. // http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony process.nextTick(this.drain.bind(this)); }
javascript
function (job, config, callback) { var task = { job: job, config: config, callback: callback || function () { } }; task.id = task.job._id; // Tasks with identical keys will be prevented from being scheduled concurrently. task.key = task.job.project + branchFromJob(task.job); this.tasks.push(task); // Defer task execution to the next event loop tick to ensure that the push() function's // callback is *always* invoked asynchronously. // http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony process.nextTick(this.drain.bind(this)); }
[ "function", "(", "job", ",", "config", ",", "callback", ")", "{", "var", "task", "=", "{", "job", ":", "job", ",", "config", ":", "config", ",", "callback", ":", "callback", "||", "function", "(", ")", "{", "}", "}", ";", "task", ".", "id", "=", ...
Add a job to the end of the queue. If the queue is not currently saturated, immediately schedule a task to handle the new job. If a callback is provided, call it when this job's task completes.
[ "Add", "a", "job", "to", "the", "end", "of", "the", "queue", ".", "If", "the", "queue", "is", "not", "currently", "saturated", "immediately", "schedule", "a", "task", "to", "handle", "the", "new", "job", ".", "If", "a", "callback", "is", "provided", "c...
6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218
https://github.com/Strider-CD/strider-simple-runner/blob/6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218/lib/jobqueue.js#L23-L42
31,172
Strider-CD/strider-simple-runner
lib/jobqueue.js
function () { var self = this; // See how much capacity we have left to fill. var launchCount = this.concurrency - Object.keys(this.active).length; // Identify up to launchCount eligible tasks, giving priority to those earlier in the queue. var offset = 0; var launchTasks = []; while (launchTasks.length < launchCount && this.tasks.length > offset) { var task = this.tasks[offset]; if (task.key in this.active) { // This task cannot run right now, so skip it. offset += 1; } else { // This task is eligible to run. Remove it from the queue and prepare it to launch. this.tasks.splice(offset, 1); launchTasks.push(task); } } // Create a task completion callback. Remove the task from the active set, invoke the tasks' // push() callback, then drain() again to see if another task is ready to run. function makeTaskHandler(task) { return function (err) { delete self.active[task.key]; task.callback(err); // Defer the next drain() call again in case the task's callback was synchronous. process.nextTick(self.drain.bind(self)); }; } // Launch the queue handler for each chosen task. for (var i = 0; i < launchTasks.length; i++) { var each = launchTasks[i]; this.active[each.key] = each; this.handler(each.job, each.config, makeTaskHandler(each)); } // Fire and unset the drain callback if one has been registered. if (this.drainCallback) { var lastCallback = this.drainCallback; this.drainCallback = null; lastCallback(); } }
javascript
function () { var self = this; // See how much capacity we have left to fill. var launchCount = this.concurrency - Object.keys(this.active).length; // Identify up to launchCount eligible tasks, giving priority to those earlier in the queue. var offset = 0; var launchTasks = []; while (launchTasks.length < launchCount && this.tasks.length > offset) { var task = this.tasks[offset]; if (task.key in this.active) { // This task cannot run right now, so skip it. offset += 1; } else { // This task is eligible to run. Remove it from the queue and prepare it to launch. this.tasks.splice(offset, 1); launchTasks.push(task); } } // Create a task completion callback. Remove the task from the active set, invoke the tasks' // push() callback, then drain() again to see if another task is ready to run. function makeTaskHandler(task) { return function (err) { delete self.active[task.key]; task.callback(err); // Defer the next drain() call again in case the task's callback was synchronous. process.nextTick(self.drain.bind(self)); }; } // Launch the queue handler for each chosen task. for (var i = 0; i < launchTasks.length; i++) { var each = launchTasks[i]; this.active[each.key] = each; this.handler(each.job, each.config, makeTaskHandler(each)); } // Fire and unset the drain callback if one has been registered. if (this.drainCallback) { var lastCallback = this.drainCallback; this.drainCallback = null; lastCallback(); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// See how much capacity we have left to fill.", "var", "launchCount", "=", "this", ".", "concurrency", "-", "Object", ".", "keys", "(", "this", ".", "active", ")", ".", "length", ";", "// Identify u...
Launch the asynchronous handler function for each eligible waiting task until the queue is saturated.
[ "Launch", "the", "asynchronous", "handler", "function", "for", "each", "eligible", "waiting", "task", "until", "the", "queue", "is", "saturated", "." ]
6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218
https://github.com/Strider-CD/strider-simple-runner/blob/6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218/lib/jobqueue.js#L46-L96
31,173
Strider-CD/strider-simple-runner
lib/jobqueue.js
function (id) { for (var key in this.active) { if (this.active.hasOwnProperty(key) && this.active[key].id === id) { return true; } } return false; }
javascript
function (id) { for (var key in this.active) { if (this.active.hasOwnProperty(key) && this.active[key].id === id) { return true; } } return false; }
[ "function", "(", "id", ")", "{", "for", "(", "var", "key", "in", "this", ".", "active", ")", "{", "if", "(", "this", ".", "active", ".", "hasOwnProperty", "(", "key", ")", "&&", "this", ".", "active", "[", "key", "]", ".", "id", "===", "id", ")...
Return true if "id" corresponds to the job ID of an active job.
[ "Return", "true", "if", "id", "corresponds", "to", "the", "job", "ID", "of", "an", "active", "job", "." ]
6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218
https://github.com/Strider-CD/strider-simple-runner/blob/6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218/lib/jobqueue.js#L104-L111
31,174
Janpot/gulp-htmlbuild
example/gulpfile.js
function (opts) { var paths = es.through(); var files = es.through(); paths.pipe(es.writeArray(function (err, srcs) { gulp.src(srcs, opts).pipe(files); })); return es.duplex(paths, files); }
javascript
function (opts) { var paths = es.through(); var files = es.through(); paths.pipe(es.writeArray(function (err, srcs) { gulp.src(srcs, opts).pipe(files); })); return es.duplex(paths, files); }
[ "function", "(", "opts", ")", "{", "var", "paths", "=", "es", ".", "through", "(", ")", ";", "var", "files", "=", "es", ".", "through", "(", ")", ";", "paths", ".", "pipe", "(", "es", ".", "writeArray", "(", "function", "(", "err", ",", "srcs", ...
pipe a glob stream into this and receive a gulp file stream
[ "pipe", "a", "glob", "stream", "into", "this", "and", "receive", "a", "gulp", "file", "stream" ]
00a3428a3c4537873e40f9180b2c6f56c4a851ee
https://github.com/Janpot/gulp-htmlbuild/blob/00a3428a3c4537873e40f9180b2c6f56c4a851ee/example/gulpfile.js#L10-L19
31,175
Janpot/gulp-htmlbuild
example/gulpfile.js
function (block) { es.readArray([ '<!--', ' processed by htmlbuild', '-->' ].map(function (str) { return block.indent + str; })).pipe(block); }
javascript
function (block) { es.readArray([ '<!--', ' processed by htmlbuild', '-->' ].map(function (str) { return block.indent + str; })).pipe(block); }
[ "function", "(", "block", ")", "{", "es", ".", "readArray", "(", "[", "'<!--'", ",", "' processed by htmlbuild'", ",", "'-->'", "]", ".", "map", "(", "function", "(", "str", ")", "{", "return", "block", ".", "indent", "+", "str", ";", "}", ")", ")",...
add a header with this target
[ "add", "a", "header", "with", "this", "target" ]
00a3428a3c4537873e40f9180b2c6f56c4a851ee
https://github.com/Janpot/gulp-htmlbuild/blob/00a3428a3c4537873e40f9180b2c6f56c4a851ee/example/gulpfile.js#L63-L71
31,176
rrharvey/grunt-file-blocks
lib/fileprocessor.js
function (template) { var pattern = _.template(template)(fileReplace); pattern = pattern.replace(/\//g, '\\/'); pattern = pattern.replace(/\s+/g, '\\s*'); pattern = '\\s*' + pattern + '\\s*'; return new RegExp(pattern); }
javascript
function (template) { var pattern = _.template(template)(fileReplace); pattern = pattern.replace(/\//g, '\\/'); pattern = pattern.replace(/\s+/g, '\\s*'); pattern = '\\s*' + pattern + '\\s*'; return new RegExp(pattern); }
[ "function", "(", "template", ")", "{", "var", "pattern", "=", "_", ".", "template", "(", "template", ")", "(", "fileReplace", ")", ";", "pattern", "=", "pattern", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'\\\\/'", ")", ";", "pattern", "=", ...
Convert the template into a RegExp that can capture the file name. @param {string} template @returns {RegExp} A regular expression that can capture the file name.
[ "Convert", "the", "template", "into", "a", "RegExp", "that", "can", "capture", "the", "file", "name", "." ]
c1e3bfcb33df76ca820de580da3864085bfaed44
https://github.com/rrharvey/grunt-file-blocks/blob/c1e3bfcb33df76ca820de580da3864085bfaed44/lib/fileprocessor.js#L29-L35
31,177
rrharvey/grunt-file-blocks
lib/fileprocessor.js
function (line, block) { if (!block.template) { return; } var regex = getRegExp(block.template); var match = regex.exec(line); return match ? match[1] : match; }
javascript
function (line, block) { if (!block.template) { return; } var regex = getRegExp(block.template); var match = regex.exec(line); return match ? match[1] : match; }
[ "function", "(", "line", ",", "block", ")", "{", "if", "(", "!", "block", ".", "template", ")", "{", "return", ";", "}", "var", "regex", "=", "getRegExp", "(", "block", ".", "template", ")", ";", "var", "match", "=", "regex", ".", "exec", "(", "l...
Parse the file name from the line if it exists. @param {string} line - A line from the file. @param {Block} block - The replacement block object. @returns {string} The file name if it exists.
[ "Parse", "the", "file", "name", "from", "the", "line", "if", "it", "exists", "." ]
c1e3bfcb33df76ca820de580da3864085bfaed44
https://github.com/rrharvey/grunt-file-blocks/blob/c1e3bfcb33df76ca820de580da3864085bfaed44/lib/fileprocessor.js#L43-L51
31,178
lbdremy/scrapinode
lib/defaults/index.js
scrapDescription
function scrapDescription(window){ var $ = window.$; var descriptions = []; // Open Graph protocol by Facebook <meta property="og:description" content="(*)"/> $('meta[property="og:description"]').each(function(){ var content = $(this).attr('content'); if(content) descriptions.push(content); }); // Schema.org : <* itemprop="description">(*)</*> $('[itemprop="description"]').each(function(){ var text = $(this).text(); if(text) descriptions.push(text); }); // Meta tag description: <meta property="description" content="(*)" /> $('meta[name="description"]').each(function(){ var description = utils.inline($(this).attr('content')).trim(); if(description) descriptions.push(description); }); // Random text in div and p tags. Oriented product informations if(descriptions.length === 0){ $('div,p').each(function(){ if( ($(this).attr('class') && $(this).attr('class').toLowerCase() === 'productdesc') || ($(this).attr('id') && $(this).attr('id').toLowerCase() === 'productdesc')){ var description = utils.inline($(this).text()).trim(); if(description) descriptions.push(description); } }); } return descriptions; }
javascript
function scrapDescription(window){ var $ = window.$; var descriptions = []; // Open Graph protocol by Facebook <meta property="og:description" content="(*)"/> $('meta[property="og:description"]').each(function(){ var content = $(this).attr('content'); if(content) descriptions.push(content); }); // Schema.org : <* itemprop="description">(*)</*> $('[itemprop="description"]').each(function(){ var text = $(this).text(); if(text) descriptions.push(text); }); // Meta tag description: <meta property="description" content="(*)" /> $('meta[name="description"]').each(function(){ var description = utils.inline($(this).attr('content')).trim(); if(description) descriptions.push(description); }); // Random text in div and p tags. Oriented product informations if(descriptions.length === 0){ $('div,p').each(function(){ if( ($(this).attr('class') && $(this).attr('class').toLowerCase() === 'productdesc') || ($(this).attr('id') && $(this).attr('id').toLowerCase() === 'productdesc')){ var description = utils.inline($(this).text()).trim(); if(description) descriptions.push(description); } }); } return descriptions; }
[ "function", "scrapDescription", "(", "window", ")", "{", "var", "$", "=", "window", ".", "$", ";", "var", "descriptions", "=", "[", "]", ";", "// Open Graph protocol by Facebook <meta property=\"og:description\" content=\"(*)\"/>", "$", "(", "'meta[property=\"og:descripti...
Retrieve descriptions of the page @param {Object} window - object representating the window @return {Array} @api public
[ "Retrieve", "descriptions", "of", "the", "page" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/defaults/index.js#L43-L75
31,179
lbdremy/scrapinode
lib/defaults/index.js
isValidExtension
function isValidExtension(src){ var extension = src.split('.').pop(); var isValid = ENUM_INVALID_EXTENSIONS[extension] === false ? false : true; return isValid; }
javascript
function isValidExtension(src){ var extension = src.split('.').pop(); var isValid = ENUM_INVALID_EXTENSIONS[extension] === false ? false : true; return isValid; }
[ "function", "isValidExtension", "(", "src", ")", "{", "var", "extension", "=", "src", ".", "split", "(", "'.'", ")", ".", "pop", "(", ")", ";", "var", "isValid", "=", "ENUM_INVALID_EXTENSIONS", "[", "extension", "]", "===", "false", "?", "false", ":", ...
Check if the extension is considered valid @param {String} src - url of the image @return {Boolean} true if valid, false otherwise @api private
[ "Check", "if", "the", "extension", "is", "considered", "valid" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/defaults/index.js#L92-L96
31,180
lbdremy/scrapinode
lib/defaults/index.js
scrapImage
function scrapImage(window){ var $ = window.$; var url = window.url; var thumbs = []; var thumbsRejected = []; var title = scrapTitle(window); var addToThumbs = function(image,beginning){ var src = $(image).attr('src'); if(src && isValidExtension(src) ){ src = utils.toURL(src,url); if(beginning){ thumbs.unshift(src); }else{ thumbs.push(src); } }else if(src){ thumbsRejected.push(src); } }; // Open Graph protocol by Facebook: <meta property="og:image" content="(*)"/> $('meta[property="og:image"]').each(function(){ var content = $(this).attr('content'); if(content) thumbs.push(utils.toURL(content)); }); // Schema.org: <img itemprop="image" src="(*)"/> $('img[itemprop="image"]').each(function(){ addToThumbs(this); }); // Oriented product informations if(thumbs.length < 1){ $('img[id*="product"]').each(function(){ addToThumbs(this); }); $('img[class*="product"]').each(function(){ addToThumbs(this); }); } // Grab all images if(thumbs.length < 10){ $('img').each(function(){ if($(this).attr('itemprop') === 'image') return; var alt = $(this).attr('alt'); // Leave this test alone // the selector 'img[alt="title"]' will not work if the title is like LG 42PT35342" PLASMA TV. Escaping issues. // Image where the title of the page is equal to the content of the alt attribute of the image tag. if(alt === title){ addToThumbs(this,true); }else{ addToThumbs(this); } }); } if(thumbs.length === 0){ thumbs = thumbsRejected; } return thumbs; }
javascript
function scrapImage(window){ var $ = window.$; var url = window.url; var thumbs = []; var thumbsRejected = []; var title = scrapTitle(window); var addToThumbs = function(image,beginning){ var src = $(image).attr('src'); if(src && isValidExtension(src) ){ src = utils.toURL(src,url); if(beginning){ thumbs.unshift(src); }else{ thumbs.push(src); } }else if(src){ thumbsRejected.push(src); } }; // Open Graph protocol by Facebook: <meta property="og:image" content="(*)"/> $('meta[property="og:image"]').each(function(){ var content = $(this).attr('content'); if(content) thumbs.push(utils.toURL(content)); }); // Schema.org: <img itemprop="image" src="(*)"/> $('img[itemprop="image"]').each(function(){ addToThumbs(this); }); // Oriented product informations if(thumbs.length < 1){ $('img[id*="product"]').each(function(){ addToThumbs(this); }); $('img[class*="product"]').each(function(){ addToThumbs(this); }); } // Grab all images if(thumbs.length < 10){ $('img').each(function(){ if($(this).attr('itemprop') === 'image') return; var alt = $(this).attr('alt'); // Leave this test alone // the selector 'img[alt="title"]' will not work if the title is like LG 42PT35342" PLASMA TV. Escaping issues. // Image where the title of the page is equal to the content of the alt attribute of the image tag. if(alt === title){ addToThumbs(this,true); }else{ addToThumbs(this); } }); } if(thumbs.length === 0){ thumbs = thumbsRejected; } return thumbs; }
[ "function", "scrapImage", "(", "window", ")", "{", "var", "$", "=", "window", ".", "$", ";", "var", "url", "=", "window", ".", "url", ";", "var", "thumbs", "=", "[", "]", ";", "var", "thumbsRejected", "=", "[", "]", ";", "var", "title", "=", "scr...
Retrieve image urls on the page @param {Object} window - @return {Array} @api public
[ "Retrieve", "image", "urls", "on", "the", "page" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/defaults/index.js#L106-L169
31,181
lbdremy/scrapinode
lib/defaults/index.js
scrapTitle
function scrapTitle(window){ var $ = window.$; var url = window.location.href; // Tags or attributes whom can contain a nice title for the page var titleTag = $('title').text().trim(); var metaTitleTag = $('meta[name="title"]').attr('content'); var openGraphTitle = $('meta[property="og:title"]').attr('content'); var h1Tag = $('h1').eq(0).text().trim(); var itempropNameTag = $('[itemprop="name"]').text().trim(); var titles = [titleTag, metaTitleTag, openGraphTitle, h1Tag, itempropNameTag]; // Regex of the web site name var nameWebsite = utils.getWebsiteName(url); var regex = new RegExp(nameWebsite,'i'); // Sort to find the best title var titlesNotEmpty = titles.filter(function(value){ return !!value; }); var titlesBest = titlesNotEmpty.filter(function(value){ return !regex.test(value); }); var bestTitle = (titlesBest && titlesBest[0]) || (titlesNotEmpty && titlesNotEmpty[0]) || ''; return utils.inline(bestTitle); }
javascript
function scrapTitle(window){ var $ = window.$; var url = window.location.href; // Tags or attributes whom can contain a nice title for the page var titleTag = $('title').text().trim(); var metaTitleTag = $('meta[name="title"]').attr('content'); var openGraphTitle = $('meta[property="og:title"]').attr('content'); var h1Tag = $('h1').eq(0).text().trim(); var itempropNameTag = $('[itemprop="name"]').text().trim(); var titles = [titleTag, metaTitleTag, openGraphTitle, h1Tag, itempropNameTag]; // Regex of the web site name var nameWebsite = utils.getWebsiteName(url); var regex = new RegExp(nameWebsite,'i'); // Sort to find the best title var titlesNotEmpty = titles.filter(function(value){ return !!value; }); var titlesBest = titlesNotEmpty.filter(function(value){ return !regex.test(value); }); var bestTitle = (titlesBest && titlesBest[0]) || (titlesNotEmpty && titlesNotEmpty[0]) || ''; return utils.inline(bestTitle); }
[ "function", "scrapTitle", "(", "window", ")", "{", "var", "$", "=", "window", ".", "$", ";", "var", "url", "=", "window", ".", "location", ".", "href", ";", "// Tags or attributes whom can contain a nice title for the page", "var", "titleTag", "=", "$", "(", "...
Retrieve the more appropriate title of the page @param {Object} window - @return {String} title of the page @api public
[ "Retrieve", "the", "more", "appropriate", "title", "of", "the", "page" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/defaults/index.js#L179-L203
31,182
lbdremy/scrapinode
lib/defaults/index.js
scrapVideo
function scrapVideo(window){ var $ = window.$; var url = window.location.href; var thumbs = []; // Open Graph protocol by Facebook: <meta property="og:video" content="(*)"/> $('meta').each(function(){ var property = $(this).attr('property'); var content = $(this).attr('content'); if(property === 'og:video' && content){ thumbs.push(utils.toURL(content)); } }); $('video, embed').each(function(){ var src = $(this).attr('src'); if(src) thumbs.push(utils.toURL(src,url)); }); return thumbs; }
javascript
function scrapVideo(window){ var $ = window.$; var url = window.location.href; var thumbs = []; // Open Graph protocol by Facebook: <meta property="og:video" content="(*)"/> $('meta').each(function(){ var property = $(this).attr('property'); var content = $(this).attr('content'); if(property === 'og:video' && content){ thumbs.push(utils.toURL(content)); } }); $('video, embed').each(function(){ var src = $(this).attr('src'); if(src) thumbs.push(utils.toURL(src,url)); }); return thumbs; }
[ "function", "scrapVideo", "(", "window", ")", "{", "var", "$", "=", "window", ".", "$", ";", "var", "url", "=", "window", ".", "location", ".", "href", ";", "var", "thumbs", "=", "[", "]", ";", "// Open Graph protocol by Facebook: <meta property=\"og:video\" c...
Retrieve the video urls on the page @param {Object} window - @return {Array} @api public
[ "Retrieve", "the", "video", "urls", "on", "the", "page" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/defaults/index.js#L213-L233
31,183
phovea/generator-phovea
utils/pip.js
parseRequirements
function parseRequirements(file) { if (!file) { return {}; } file = file.trim(); if (file === '') { return {}; } const versions = {}; file.split('\n').forEach((line) => { line = line.trim(); if (line.startsWith('-e')) { // editable special dependency const branchSeparator = line.indexOf('@'); const name = line.slice(0, branchSeparator).trim(); versions[name] = line.slice(branchSeparator).trim(); return; } if (line.startsWith('#') || line.startsWith('-')) { return; // skip } const versionSeparator = line.search(/[\^~=>!]/); if (versionSeparator >= 0) { const name = line.slice(0, versionSeparator).trim(); versions[name] = line.slice(versionSeparator).trim(); } else { versions[line] = ''; } }); return versions; }
javascript
function parseRequirements(file) { if (!file) { return {}; } file = file.trim(); if (file === '') { return {}; } const versions = {}; file.split('\n').forEach((line) => { line = line.trim(); if (line.startsWith('-e')) { // editable special dependency const branchSeparator = line.indexOf('@'); const name = line.slice(0, branchSeparator).trim(); versions[name] = line.slice(branchSeparator).trim(); return; } if (line.startsWith('#') || line.startsWith('-')) { return; // skip } const versionSeparator = line.search(/[\^~=>!]/); if (versionSeparator >= 0) { const name = line.slice(0, versionSeparator).trim(); versions[name] = line.slice(versionSeparator).trim(); } else { versions[line] = ''; } }); return versions; }
[ "function", "parseRequirements", "(", "file", ")", "{", "if", "(", "!", "file", ")", "{", "return", "{", "}", ";", "}", "file", "=", "file", ".", "trim", "(", ")", ";", "if", "(", "file", "===", "''", ")", "{", "return", "{", "}", ";", "}", "...
Created by Samuel Gratzl on 05.04.2017.
[ "Created", "by", "Samuel", "Gratzl", "on", "05", ".", "04", ".", "2017", "." ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/utils/pip.js#L5-L37
31,184
cloudkick/whiskey
lib/util.js
function(func, context, args, callback) { try { func.apply(context, args); } catch (err) {} if (callback) { callback(); } }
javascript
function(func, context, args, callback) { try { func.apply(context, args); } catch (err) {} if (callback) { callback(); } }
[ "function", "(", "func", ",", "context", ",", "args", ",", "callback", ")", "{", "try", "{", "func", ".", "apply", "(", "context", ",", "args", ")", ";", "}", "catch", "(", "err", ")", "{", "}", "if", "(", "callback", ")", "{", "callback", "(", ...
Call a function and ignore any error thrown. @param {Function} func Function to call. @param {Object} context Context in which the function is called. @param {Array} Function argument @param {Function} callback Optional callback which is called at the end.
[ "Call", "a", "function", "and", "ignore", "any", "error", "thrown", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/util.js#L59-L68
31,185
cloudkick/whiskey
lib/util.js
fireOnce
function fireOnce(fn) { var fired = false; return function wrapped() { if (!fired) { fired = true; fn.apply(null, arguments); } }; }
javascript
function fireOnce(fn) { var fired = false; return function wrapped() { if (!fired) { fired = true; fn.apply(null, arguments); } }; }
[ "function", "fireOnce", "(", "fn", ")", "{", "var", "fired", "=", "false", ";", "return", "function", "wrapped", "(", ")", "{", "if", "(", "!", "fired", ")", "{", "fired", "=", "true", ";", "fn", ".", "apply", "(", "null", ",", "arguments", ")", ...
Wrap a function so that the original function will only be called once, regardless of how many times the wrapper is called. @param {Function} fn The to wrap. @return {Function} A function which will call fn the first time it is called.
[ "Wrap", "a", "function", "so", "that", "the", "original", "function", "will", "only", "be", "called", "once", "regardless", "of", "how", "many", "times", "the", "wrapper", "is", "called", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/util.js#L299-L307
31,186
leonardpauli/docs
app/api/external/google/drive/example/script.js
handleClientLoad
function handleClientLoad() { (async ()=> { await config.load() await config.api.google.load() gapi.load('client:auth2', initClient) })().catch(console.error) }
javascript
function handleClientLoad() { (async ()=> { await config.load() await config.api.google.load() gapi.load('client:auth2', initClient) })().catch(console.error) }
[ "function", "handleClientLoad", "(", ")", "{", "(", "async", "(", ")", "=>", "{", "await", "config", ".", "load", "(", ")", "await", "config", ".", "api", ".", "google", ".", "load", "(", ")", "gapi", ".", "load", "(", "'client:auth2'", ",", "initCli...
On load, called to load the auth2 library and API client library.
[ "On", "load", "called", "to", "load", "the", "auth2", "library", "and", "API", "client", "library", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/app/api/external/google/drive/example/script.js#L34-L40
31,187
leonardpauli/docs
app/api/external/google/drive/example/script.js
initClient
function initClient() { gapi.client.init({ apiKey: config.api.google.web.key, clientId: config.api.google.web.client_id, discoveryDocs: DISCOVERY_DOCS, scope: SCOPES }).then(function () { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton.onclick = handleSignoutClick; }, function(error) { appendPre(JSON.stringify(error, null, 2)); }); }
javascript
function initClient() { gapi.client.init({ apiKey: config.api.google.web.key, clientId: config.api.google.web.client_id, discoveryDocs: DISCOVERY_DOCS, scope: SCOPES }).then(function () { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton.onclick = handleSignoutClick; }, function(error) { appendPre(JSON.stringify(error, null, 2)); }); }
[ "function", "initClient", "(", ")", "{", "gapi", ".", "client", ".", "init", "(", "{", "apiKey", ":", "config", ".", "api", ".", "google", ".", "web", ".", "key", ",", "clientId", ":", "config", ".", "api", ".", "google", ".", "web", ".", "client_i...
Initializes the API client library and sets up sign-in state listeners.
[ "Initializes", "the", "API", "client", "library", "and", "sets", "up", "sign", "-", "in", "state", "listeners", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/app/api/external/google/drive/example/script.js#L46-L63
31,188
leonardpauli/docs
app/api/external/google/drive/example/script.js
updateSigninStatus
function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; listFiles(); } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; } }
javascript
function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; listFiles(); } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; } }
[ "function", "updateSigninStatus", "(", "isSignedIn", ")", "{", "if", "(", "isSignedIn", ")", "{", "authorizeButton", ".", "style", ".", "display", "=", "'none'", ";", "signoutButton", ".", "style", ".", "display", "=", "'block'", ";", "listFiles", "(", ")", ...
Called when the signed in status changes, to update the UI appropriately. After a sign-in, the API is called.
[ "Called", "when", "the", "signed", "in", "status", "changes", "to", "update", "the", "UI", "appropriately", ".", "After", "a", "sign", "-", "in", "the", "API", "is", "called", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/app/api/external/google/drive/example/script.js#L69-L78
31,189
leonardpauli/docs
app/api/external/google/drive/example/script.js
appendPre
function appendPre(message) { var pre = document.getElementById('content'); var textContent = document.createTextNode(message + '\n'); pre.appendChild(textContent); }
javascript
function appendPre(message) { var pre = document.getElementById('content'); var textContent = document.createTextNode(message + '\n'); pre.appendChild(textContent); }
[ "function", "appendPre", "(", "message", ")", "{", "var", "pre", "=", "document", ".", "getElementById", "(", "'content'", ")", ";", "var", "textContent", "=", "document", ".", "createTextNode", "(", "message", "+", "'\\n'", ")", ";", "pre", ".", "appendCh...
Append a pre element to the body containing the given message as its text node. Used to display the results of the API call. @param {string} message Text to be placed in pre element.
[ "Append", "a", "pre", "element", "to", "the", "body", "containing", "the", "given", "message", "as", "its", "text", "node", ".", "Used", "to", "display", "the", "results", "of", "the", "API", "call", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/app/api/external/google/drive/example/script.js#L100-L104
31,190
leonardpauli/docs
app/api/external/google/drive/example/script.js
listFiles
function listFiles() { gapi.client.drive.files.list({ 'pageSize': 10, 'fields': "nextPageToken, files(id, name)" }).then(function(response) { appendPre('Files:'); var files = response.result.files; if (files && files.length > 0) { for (var i = 0; i < files.length; i++) { var file = files[i]; appendPre(file.name + ' (' + file.id + ')'); } } else { appendPre('No files found.'); } }); }
javascript
function listFiles() { gapi.client.drive.files.list({ 'pageSize': 10, 'fields': "nextPageToken, files(id, name)" }).then(function(response) { appendPre('Files:'); var files = response.result.files; if (files && files.length > 0) { for (var i = 0; i < files.length; i++) { var file = files[i]; appendPre(file.name + ' (' + file.id + ')'); } } else { appendPre('No files found.'); } }); }
[ "function", "listFiles", "(", ")", "{", "gapi", ".", "client", ".", "drive", ".", "files", ".", "list", "(", "{", "'pageSize'", ":", "10", ",", "'fields'", ":", "\"nextPageToken, files(id, name)\"", "}", ")", ".", "then", "(", "function", "(", "response", ...
Print files.
[ "Print", "files", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/app/api/external/google/drive/example/script.js#L109-L125
31,191
jose-pleonasm/py-logging
core/Formatter.js
Formatter
function Formatter(format, timeFormat) { format = format || '%(message)'; timeFormat = timeFormat || '%Y-%m-%d %H:%M:%S'; /** * @private * @type {string} */ this._format = format; /** * @private * @type {string} */ this._timeFormat = timeFormat; }
javascript
function Formatter(format, timeFormat) { format = format || '%(message)'; timeFormat = timeFormat || '%Y-%m-%d %H:%M:%S'; /** * @private * @type {string} */ this._format = format; /** * @private * @type {string} */ this._timeFormat = timeFormat; }
[ "function", "Formatter", "(", "format", ",", "timeFormat", ")", "{", "format", "=", "format", "||", "'%(message)'", ";", "timeFormat", "=", "timeFormat", "||", "'%Y-%m-%d %H:%M:%S'", ";", "/**\n\t * @private\n\t * @type {string}\n\t */", "this", ".", "_format", "=", ...
Default formatter. @constructor Formatter @param {string} [format] @param {string} [timeFormat]
[ "Default", "formatter", "." ]
598f41284311ea6a837d4ba56236301abe689b09
https://github.com/jose-pleonasm/py-logging/blob/598f41284311ea6a837d4ba56236301abe689b09/core/Formatter.js#L10-L25
31,192
cronvel/kung-fig
lib/kfgStringify.js
stringifyString
function stringifyString( v , runtime , isTemplateSentence ) { var maybeDollar = '' ; if ( isTemplateSentence ) { if ( v.key ) { v = v.key ; maybeDollar = '$' ; } else { runtime.str += runtime.depth ? ' <Sentence>' : '<Sentence>' ; return ; } } if ( runtime.preferQuotes ) { return stringifyStringMaybeQuotes( v , runtime , maybeDollar ) ; } return stringifyStringMaybeStringLine( v , runtime , maybeDollar ) ; }
javascript
function stringifyString( v , runtime , isTemplateSentence ) { var maybeDollar = '' ; if ( isTemplateSentence ) { if ( v.key ) { v = v.key ; maybeDollar = '$' ; } else { runtime.str += runtime.depth ? ' <Sentence>' : '<Sentence>' ; return ; } } if ( runtime.preferQuotes ) { return stringifyStringMaybeQuotes( v , runtime , maybeDollar ) ; } return stringifyStringMaybeStringLine( v , runtime , maybeDollar ) ; }
[ "function", "stringifyString", "(", "v", ",", "runtime", ",", "isTemplateSentence", ")", "{", "var", "maybeDollar", "=", "''", ";", "if", "(", "isTemplateSentence", ")", "{", "if", "(", "v", ".", "key", ")", "{", "v", "=", "v", ".", "key", ";", "mayb...
no control chars except newline and tab
[ "no", "control", "chars", "except", "newline", "and", "tab" ]
a862c37237a283b4c0a4a5ff0bde6617d77104eb
https://github.com/cronvel/kung-fig/blob/a862c37237a283b4c0a4a5ff0bde6617d77104eb/lib/kfgStringify.js#L154-L174
31,193
Strider-CD/strider-simple-runner
lib/index.js
t
function t(time, done) { if (arguments.length === 1) { done = time; time = 2000; } var error = new Error(`Callback took too long (max: ${time})`); var waiting = true; var timeout = setTimeout(function () { if (!waiting) return; waiting = false; done(error); }, time); function handler() { if (!waiting) return; clearTimeout(timeout); waiting = false; done.apply(this, arguments); } return handler; }
javascript
function t(time, done) { if (arguments.length === 1) { done = time; time = 2000; } var error = new Error(`Callback took too long (max: ${time})`); var waiting = true; var timeout = setTimeout(function () { if (!waiting) return; waiting = false; done(error); }, time); function handler() { if (!waiting) return; clearTimeout(timeout); waiting = false; done.apply(this, arguments); } return handler; }
[ "function", "t", "(", "time", ",", "done", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "done", "=", "time", ";", "time", "=", "2000", ";", "}", "var", "error", "=", "new", "Error", "(", "`", "${", "time", "}", "`", ...
timeout for callbacks. Helps to kill misbehaving plugins, etc
[ "timeout", "for", "callbacks", ".", "Helps", "to", "kill", "misbehaving", "plugins", "etc" ]
6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218
https://github.com/Strider-CD/strider-simple-runner/blob/6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218/lib/index.js#L18-L40
31,194
lbdremy/scrapinode
lib/browser.js
getRequest
function getRequest(options,callback){ var destroyed = false; var req = request.get(options.url) .set(options.headers) .timeout(options.timeout) .redirects(options.redirects) .buffer(false) .end(function(err,res){ if(err && !err.status) return onError(err); // Check HTTP status code var isHTTPError = isRedirect(res.status) || isClientError(res.status) || isServerError(res.status); if(isHTTPError) { var reqFormated = req.req; var resFormated = err.response.res; return onError(new HTTPError(reqFormated, resFormated)); } // Attach event handlers and build the body var body = ''; res.on('data',function(chunk){ body += chunk; }); res.on('end',function(){ if(destroyed) return; // Check if a HTTP refresh/redirection is present into the HTML page, if yes refreshes/redirects. var matches = body.match(/<meta[ ]*http-equiv="REFRESH"[ ]*content="[0-9]{1,};[ ]*URL=(.*?)"[ ]*\/?>/i); if(matches && matches[1]){ options.url = matches[1]; return getRequest(options,callback); } callback(null,body); }); res.on('error',onError); // Check if content-type is an image, if yes destroy the response and build a HTML page with the image in it if(isImage(res.headers)){ res.destroy(); destroyed = true; body = '<!DOCTYPE html><html><head></head><body><img src="' + options.url + '" /></body></html>'; return callback(null,body); } }); // Error event handler function onError(err){ if(options.retries--) return getRequest(options,callback); callback(err); } return req; }
javascript
function getRequest(options,callback){ var destroyed = false; var req = request.get(options.url) .set(options.headers) .timeout(options.timeout) .redirects(options.redirects) .buffer(false) .end(function(err,res){ if(err && !err.status) return onError(err); // Check HTTP status code var isHTTPError = isRedirect(res.status) || isClientError(res.status) || isServerError(res.status); if(isHTTPError) { var reqFormated = req.req; var resFormated = err.response.res; return onError(new HTTPError(reqFormated, resFormated)); } // Attach event handlers and build the body var body = ''; res.on('data',function(chunk){ body += chunk; }); res.on('end',function(){ if(destroyed) return; // Check if a HTTP refresh/redirection is present into the HTML page, if yes refreshes/redirects. var matches = body.match(/<meta[ ]*http-equiv="REFRESH"[ ]*content="[0-9]{1,};[ ]*URL=(.*?)"[ ]*\/?>/i); if(matches && matches[1]){ options.url = matches[1]; return getRequest(options,callback); } callback(null,body); }); res.on('error',onError); // Check if content-type is an image, if yes destroy the response and build a HTML page with the image in it if(isImage(res.headers)){ res.destroy(); destroyed = true; body = '<!DOCTYPE html><html><head></head><body><img src="' + options.url + '" /></body></html>'; return callback(null,body); } }); // Error event handler function onError(err){ if(options.retries--) return getRequest(options,callback); callback(err); } return req; }
[ "function", "getRequest", "(", "options", ",", "callback", ")", "{", "var", "destroyed", "=", "false", ";", "var", "req", "=", "request", ".", "get", "(", "options", ".", "url", ")", ".", "set", "(", "options", ".", "headers", ")", ".", "timeout", "(...
Send an HTTP GET request to `options.url` @param {Object} options - configuration of the HTTP GET request @param {String} options.headers - set of headers @param {Number} options.timeout - timeout @param {Number} options.redirects - number of times the request will follow redirection instructions @param {Number} options.retries - number of times the request will be resend if the request failed @param {Function} callback - @return {http.ClientRequest} req @api private
[ "Send", "an", "HTTP", "GET", "request", "to", "options", ".", "url" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/browser.js#L66-L117
31,195
lbdremy/scrapinode
lib/browser.js
buildDOM
function buildDOM(body,engine,url,callback){ if(!body){ return callback(new ScrapinodeError('The HTTP response contains an empty body: "' + body +'"')); } if(engine === 'jsdom' || engine === 'jsdom+zepto'){ var library = engine === 'jsdom+zepto' ? zepto : jquery; try{ jsdom.env({ html: body, src : [library], done : function(err,window){ if(err) return callback(err); if(!window) return callback(new ScrapinodeError('The "window" provides by JSDOM is falsy: ' + window)); window.location.href = url; callback(err,window); window.close(); } }); }catch(err){ callback(err); } }else if(engine === 'cheerio'){ try{ var $ = cheerio.load(body); var window = { $ : $, location : { href : url } }; callback(null,window); }catch(err){ callback(err); } }else{ callback(new ScrapinodeError('The engine "' + engine + '" is not supported. Scrapinode only supports jsdom and cheerio.')); } }
javascript
function buildDOM(body,engine,url,callback){ if(!body){ return callback(new ScrapinodeError('The HTTP response contains an empty body: "' + body +'"')); } if(engine === 'jsdom' || engine === 'jsdom+zepto'){ var library = engine === 'jsdom+zepto' ? zepto : jquery; try{ jsdom.env({ html: body, src : [library], done : function(err,window){ if(err) return callback(err); if(!window) return callback(new ScrapinodeError('The "window" provides by JSDOM is falsy: ' + window)); window.location.href = url; callback(err,window); window.close(); } }); }catch(err){ callback(err); } }else if(engine === 'cheerio'){ try{ var $ = cheerio.load(body); var window = { $ : $, location : { href : url } }; callback(null,window); }catch(err){ callback(err); } }else{ callback(new ScrapinodeError('The engine "' + engine + '" is not supported. Scrapinode only supports jsdom and cheerio.')); } }
[ "function", "buildDOM", "(", "body", ",", "engine", ",", "url", ",", "callback", ")", "{", "if", "(", "!", "body", ")", "{", "return", "callback", "(", "new", "ScrapinodeError", "(", "'The HTTP response contains an empty body: \"'", "+", "body", "+", "'\"'", ...
Build a DOM representation of the given HTML `body` @param {String} body - html page @param {String} engine - name of the engine used to generate the DOM @param {String} url - url of the page containing the given `body` @param {Function} callback - @api private
[ "Build", "a", "DOM", "representation", "of", "the", "given", "HTML", "body" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/browser.js#L129-L167
31,196
lbdremy/scrapinode
lib/browser.js
isImage
function isImage(headers){ var regexImage = /image\//i; var contentType = headers ? headers['content-type'] : ''; return regexImage.test(contentType); }
javascript
function isImage(headers){ var regexImage = /image\//i; var contentType = headers ? headers['content-type'] : ''; return regexImage.test(contentType); }
[ "function", "isImage", "(", "headers", ")", "{", "var", "regexImage", "=", "/", "image\\/", "/", "i", ";", "var", "contentType", "=", "headers", "?", "headers", "[", "'content-type'", "]", ":", "''", ";", "return", "regexImage", ".", "test", "(", "conten...
Check if the content of the HTTP body is an image @param {Object} headers - @return {Boolean} @api private
[ "Check", "if", "the", "content", "of", "the", "HTTP", "body", "is", "an", "image" ]
c172c36fed7cce22516f3edbd71287c79ce6a4e2
https://github.com/lbdremy/scrapinode/blob/c172c36fed7cce22516f3edbd71287c79ce6a4e2/lib/browser.js#L213-L217
31,197
jonschlinkert/map-schema
index.js
Schema
function Schema(options) { this.options = options || {}; this.data = new Data(); this.isSchema = true; this.utils = utils; this.initSchema(); this.addFields(this.options); var only = utils.arrayify(this.options.pick || this.options.only); utils.define(this.options, 'only', only); }
javascript
function Schema(options) { this.options = options || {}; this.data = new Data(); this.isSchema = true; this.utils = utils; this.initSchema(); this.addFields(this.options); var only = utils.arrayify(this.options.pick || this.options.only); utils.define(this.options, 'only', only); }
[ "function", "Schema", "(", "options", ")", "{", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "data", "=", "new", "Data", "(", ")", ";", "this", ".", "isSchema", "=", "true", ";", "this", ".", "utils", "=", "utils", ";...
Create a new `Schema` with the given `options`. ```js var schema = new Schema() .field('name', 'string') .field('version', 'string') .field('license', 'string') .field('licenses', 'array', { normalize: function(val, key, config) { // convert license array to `license` string config.license = val[0].type; delete config[key]; } }) .normalize(require('./package')) ``` @param {Object} `options` @api public
[ "Create", "a", "new", "Schema", "with", "the", "given", "options", "." ]
08e11847e83ab91aa7460f6ee2249a64967a5d29
https://github.com/jonschlinkert/map-schema/blob/08e11847e83ab91aa7460f6ee2249a64967a5d29/index.js#L44-L53
31,198
phovea/generator-phovea
generators/workspace/index.js
rewriteDockerCompose
function rewriteDockerCompose(compose) { const services = compose.services; if (!services) { return compose; } const host = services._host; delete services._host; Object.keys(services).forEach((k) => { if (!isHelperContainer(k)) { mergeWith(services[k], host); } }); return compose; }
javascript
function rewriteDockerCompose(compose) { const services = compose.services; if (!services) { return compose; } const host = services._host; delete services._host; Object.keys(services).forEach((k) => { if (!isHelperContainer(k)) { mergeWith(services[k], host); } }); return compose; }
[ "function", "rewriteDockerCompose", "(", "compose", ")", "{", "const", "services", "=", "compose", ".", "services", ";", "if", "(", "!", "services", ")", "{", "return", "compose", ";", "}", "const", "host", "=", "services", ".", "_host", ";", "delete", "...
rewrite the compose by inlining _host to all services not containing a dash, such that both api and celery have the same entry @param compose
[ "rewrite", "the", "compose", "by", "inlining", "_host", "to", "all", "services", "not", "containing", "a", "dash", "such", "that", "both", "api", "and", "celery", "have", "the", "same", "entry" ]
913f21a458d1468b9319e3b1e796ec09f7e8e9fc
https://github.com/phovea/generator-phovea/blob/913f21a458d1468b9319e3b1e796ec09f7e8e9fc/generators/workspace/index.js#L29-L42
31,199
basisjs/basisjs-tools-build
lib/extract/js/index.js
function(token, this_, args, scope){ //fconsole.log('extend', arguments); if (this.file.jsScope == basisScope) { var arg0 = token.arguments[0]; if (arg0 && arg0.type == 'Identifier' && arg0.name == 'Object') flow.exit('Too old basis.js (prior 1.0) detected! Current tools doesn\'t support it. Use basisjs-tools 1.3 or lower.'); } astExtend(scope, args[0], args[1]); token.obj = args[0]; }
javascript
function(token, this_, args, scope){ //fconsole.log('extend', arguments); if (this.file.jsScope == basisScope) { var arg0 = token.arguments[0]; if (arg0 && arg0.type == 'Identifier' && arg0.name == 'Object') flow.exit('Too old basis.js (prior 1.0) detected! Current tools doesn\'t support it. Use basisjs-tools 1.3 or lower.'); } astExtend(scope, args[0], args[1]); token.obj = args[0]; }
[ "function", "(", "token", ",", "this_", ",", "args", ",", "scope", ")", "{", "//fconsole.log('extend', arguments);", "if", "(", "this", ".", "file", ".", "jsScope", "==", "basisScope", ")", "{", "var", "arg0", "=", "token", ".", "arguments", "[", "0", "]...
basis.object.extend
[ "basis", ".", "object", ".", "extend" ]
177018ab31b225cddb6a184693fe4746512e7af1
https://github.com/basisjs/basisjs-tools-build/blob/177018ab31b225cddb6a184693fe4746512e7af1/lib/extract/js/index.js#L604-L616