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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
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", "(", "n", ".", "clean", "(", ")", ")", ";", "}", "catch", "(", "err2", ")", "{", "int", "=", "key", ".", "getInterval", "(", "n", ".", "toggleAccidental", "(", ")", ")", ";", "}", "}", "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", ";", "}" ]
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
train
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", "]", ")", ".", "toString", "(", ")", ")", ".", "halfSteps", "(", ")", ";", "if", "(", "matches", "[", "1", "]", "===", "'b'", ")", "halfSteps", "-=", "1", ";", "if", "(", "matches", "[", "1", "]", "===", "'#'", ")", "halfSteps", "+=", "1", ";", "return", "halfSteps", ";", "}" ]
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
train
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", ")", "{", "this", ".", "numeral", "=", "numeral", ";", "this", ".", "quality", "=", "quality", ";", "if", "(", "!", "_", ".", "contains", "(", "[", "'M'", ",", "'m'", ",", "'x'", ",", "'o'", ",", "'ø',", ",", " ", "s']", "s", "]", ")", ",", " ", "uality)", " ", "}" ]
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
train
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", ".", "root", ")", ",", "getQuality", "(", "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
train
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", "(", "!", "cache", ")", "return", "fromString", "(", "mehegan", ")", ";", "if", "(", "!", "cache", "[", "mehegan", "]", ")", "cache", "[", "mehegan", "]", "=", "fromString", "(", "mehegan", ")", ";", "return", "cache", "[", "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", "string" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/mehegan.js#L136-L145
train
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", ",", "''", ")", ";", "number", "=", "parseInt", "(", "interval", ".", "replace", "(", "/", "\\D", "/", "g", ",", "''", ")", ",", "10", ")", ";", "if", "(", "!", "quality", ")", "{", "quality", "=", "isPerfect", "(", "number", ")", "?", "'P'", ":", "'M'", ";", "}", "return", "new", "Interval", "(", "number", ",", "quality", ")", ";", "}" ]
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
train
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
train
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", ";", "var", "symbol", ";", "root", "=", "note", ".", "create", "(", "root", ")", ";", "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", "}", ";", "}" ]
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
train
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
train
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", ")", "{", "if", "(", "number", "===", "10", "&&", "quality", "===", "'m'", ")", "{", "int", "=", "interval", ".", "create", "(", "9", ",", "'aug'", ")", ";", "}", "else", "{", "int", "=", "interval", ".", "create", "(", "number", ",", "quality", ")", ";", "}", "return", "root", ".", "transpose", "(", "int", ")", ";", "}", "}", ")", ".", "compact", "(", ")", ".", "value", "(", ")", ";", "var", "bassIndex", ";", "if", "(", "bass", "&&", "!", "root", ".", "enharmonic", "(", "bass", ")", ")", "{", "bassIndex", "=", "_", ".", "findIndex", "(", "chord", ",", "bass", ".", "enharmonic", ".", "bind", "(", "bass", ")", ")", ";", "if", "(", "bassIndex", ">", "-", "1", ")", "{", "chord", "=", "rotateArr", "(", "chord", ",", "bassIndex", ")", ";", "}", "else", "{", "chord", ".", "unshift", "(", "bass", ")", ";", "}", "}", "return", "chord", ";", "}" ]
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
train
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", "+=", "'/'", "+", "bass", ".", "name", ";", "return", "new", "Chord", "(", "name", ",", "octave", ")", ";", "}" ]
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
train
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", ")", "{", "var", "exclude", "=", "function", "(", "int", ")", "{", "scales", "=", "_", ".", "filter", "(", "scales", ",", "function", "(", "scale", ")", "{", "return", "!", "scale", ".", "hasInterval", "(", "int", ")", ";", "}", ")", ";", "}", ";", "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", ";", "}" ]
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
train
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
train
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", ")", "{", "if", "(", "n", ".", "lowerThan", "(", "lastNote", ")", ")", "octave", "+=", "1", ";", "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", ")", ";", "}", ")", ";", "}" ]
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
train
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", "(", "totalBytes", ")", ";", "buffer", ".", "fill", "(", "0", ")", ";", "buffer", ".", "writeUIntBE", "(", "num", ",", "totalBytes", "-", "numBytes", ",", "numBytes", ")", ";", "return", "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
train
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", ")", ";", "var", "ntracks", "=", "padNumber", "(", "numTracks", ",", "2", ")", ";", "var", "tickdiv", "=", "padNumber", "(", "ticksPerBeat", ",", "2", ")", ";", "format", "=", "padNumber", "(", "format", ",", "2", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "midiHeader", ",", "chunklen", ",", "format", ",", "ntracks", ",", "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
train
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", ";", "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", "]", ")", ";", "}" ]
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
train
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", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "deltaTime", ",", "new", "Buffer", "(", "[", "status", ",", "note", ",", "velocity", "]", ")", "]", ")", ";", "}" ]
Make a MIDI note event
[ "Make", "a", "MIDI", "note", "event" ]
4f5857c40535b1bccc102ffdcc42a086e213016a
https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/midi.js#L70-L77
train
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", "=", "[", "]", ";", "arr", ".", "push", "(", "makeNoteEvent", "(", "deltaTime", ",", "on", ",", "firstChannel", ",", "noteValue", "(", "_", ".", "first", "(", "chord", ")", ")", ",", "velocity", ")", ")", ";", "_", ".", "each", "(", "_", ".", "rest", "(", "chord", ")", ",", "function", "(", "note", ",", "i", ")", "{", "arr", ".", "push", "(", "makeNoteEvent", "(", "0", ",", "on", ",", "i", "+", "firstChannel", ",", "noteValue", "(", "note", ")", ",", "velocity", ")", ")", ";", "}", ")", ";", "return", "Buffer", ".", "concat", "(", "arr", ")", ";", "}" ]
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
train
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", ")", "{", "var", "ratio", "=", "settings", "&&", "settings", ".", "swingRatio", "?", "settings", ".", "swingRatio", ":", "1", ";", "return", "Math", ".", "round", "(", "ticksPerBeat", "*", "duration", ".", "value", "(", "ratio", ")", ")", ";", "}" ]
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
train
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", ".", "duration", ",", "settings", ")", ";", "if", "(", "obj", ".", "note", ")", "{", "arr", ".", "push", "(", "makeNoteEvent", "(", "restBuffer", ",", "true", ",", "0", ",", "noteValue", "(", "obj", ".", "note", ")", ",", "settings", ".", "noteVelocity", ")", ")", ";", "arr", ".", "push", "(", "makeNoteEvent", "(", "time", ",", "false", ",", "0", ",", "noteValue", "(", "obj", ".", "note", ")", ",", "settings", ".", "noteVelocity", ")", ")", ";", "restBuffer", "=", "0", ";", "}", "else", "{", "restBuffer", "+=", "time", ";", "}", "return", "arr", ";", "}", ",", "[", "]", ")", ";", "return", "Buffer", ".", "concat", "(", "events", ")", ";", "}" ]
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
train
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", ")", ";", "var", "chord", "=", "obj", ".", "chord", ".", "inOctave", "(", "settings", ".", "chordOctave", ")", ".", "chord", ";", "arr", ".", "push", "(", "makeChordEvent", "(", "0", ",", "true", ",", "1", ",", "chord", ",", "settings", ".", "chordVelocity", ")", ")", ";", "arr", ".", "push", "(", "makeChordEvent", "(", "time", ",", "false", ",", "1", ",", "chord", ",", "settings", ".", "chordVelocity", ")", ")", ";", "return", "arr", ";", "}", ",", "[", "]", ")", ";", "return", "Buffer", ".", "concat", "(", "events", ")", ";", "}" ]
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
train
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", "=", "setPatch", ".", "length", "+", "noteEvents", ".", "length", "+", "trackFooter", ".", "length", ";", "return", "Buffer", ".", "concat", "(", "[", "trackHeader", ",", "padNumber", "(", "length", ",", "4", ")", ",", "setPatch", ",", "noteEvents", ",", "trackFooter", "]", ")", ";", "}" ]
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
train
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", ")", ";", "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", "]", ")", ";", "}" ]
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
train
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", ")", ";", "}", "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", ";", "}" ]
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
train
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", ")", "{", "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", ";", "}", "}", "}", ";", "}" ]
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
train
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", "=", "req", ".", "url", ";", "if", "(", "host", "in", "except", ")", "{", "next", "(", ")", ";", "}", "else", "{", "var", "target", "=", "new", "URIjs", "(", "pathFunc", "(", "host", ",", "url", ")", ")", ".", "host", "(", "to", ")", ".", "protocol", "(", "protocol", "||", "''", ")", ".", "href", "(", ")", ";", "res", ".", "redirect", "(", "301", ",", "target", ")", ";", "}", "}", ";", "}" ]
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
train
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", "||", "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", ";", "}" ]
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
train
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
train
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", ",", "'Makefile'", ")", ";", "var", "context", "=", "{", "test_files", ":", "testFiles", ".", "join", "(", "' \\\\\\n '", ")", "}", ";", "\\\\", "\\n", "}" ]
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
train
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", "=", "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", ";", "}", "if", "(", "!", "autoIncrement", "&&", "data", "[", "keyPath", "]", "===", "undefined", ")", "{", "data", "[", "keyPath", "]", "=", "uuid", "(", ")", ";", "}", "}", "return", "key", "?", "[", "value", ",", "key", "]", ":", "[", "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
train
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", ",", "storeName", ")", "!==", "-", "1", ")", ";", "}", ",", "this", ")", ";", "}" ]
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
train
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", "=>", "{", "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", "(", "Array", ".", "isArray", "(", "objStore", ".", "keyPath", ")", ")", "{", "autoIncrement", "=", "false", ";", "}", "else", "{", "try", "{", "objStore", ".", "add", "(", "{", "}", ")", ";", "autoIncrement", "=", "true", ";", "}", "catch", "(", "ex", ")", "{", "autoIncrement", "=", "false", ";", "}", "}", "}", "else", "{", "try", "{", "objStore", ".", "add", "(", "'some value'", ")", ";", "autoIncrement", "=", "true", ";", "}", "catch", "(", "ex", ")", "{", "autoIncrement", "=", "false", ";", "}", "}", "dbMeta", ".", "set", "(", "objStoreName", ",", "{", "autoIncrement", ":", "autoIncrement", ",", "keyPath", ":", "objStore", ".", "keyPath", "}", ")", ";", "transaction", ".", "abort", "(", ")", ";", "}", ")", ";", "promises", ".", "push", "(", "promise", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ";", "}" ]
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
train
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", "(", ")", ";", "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", ")", ";", "var", "linked", "=", "gl", ".", "getProgramParameter", "(", "program", ",", "gl", ".", "LINK_STATUS", ")", ";", "if", "(", "!", "linked", ")", "{", "var", "lastError", "=", "gl", ".", "getProgramInfoLog", "(", "program", ")", ";", "errFn", "(", "\"Error in program linking:\"", "+", "lastError", ")", ";", "gl", ".", "deleteProgram", "(", "program", ")", ";", "return", "null", ";", "}", "return", "program", ";", "}" ]
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
train
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", ";", "if", "(", "type", "===", "gl", ".", "SAMPLER_CUBE", ")", "return", "gl", ".", "TEXTURE_CUBE_MAP", ";", "return", "undefined", ";", "}" ]
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
train
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", "]", "+", "name", ";", "var", "ext", "=", "gl", ".", "getExtension", "(", "prefixedName", ")", ";", "if", "(", "ext", ")", "{", "return", "ext", ";", "}", "}", "return", "undefined", ";", "}" ]
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
train
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", ".", "clientHeight", "*", "multiplier", "|", "0", ";", "if", "(", "canvas", ".", "width", "!==", "width", "||", "canvas", ".", "height", "!==", "height", ")", "{", "canvas", ".", "width", "=", "width", ";", "canvas", ".", "height", "=", "height", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
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
train
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", ")", ")", "{", "return", "array", ".", "numElements", ";", "}", "else", "{", "return", "array", ".", "data", ".", "length", "/", "array", ".", "numComponents", ";", "}", "}" ]
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
train
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", "===", "\"indices\"", "?", "gl", ".", "ELEMENT_ARRAY_BUFFER", ":", "gl", ".", "ARRAY_BUFFER", ";", "var", "array", "=", "makeTypedArray", "(", "arrays", "[", "key", "]", ",", "name", ")", ";", "buffers", "[", "key", "]", "=", "createBufferFromTypedArray", "(", "gl", ",", "array", ",", "type", ")", ";", "}", ")", ";", "if", "(", "arrays", ".", "indices", ")", "{", "buffers", ".", "numElements", "=", "arrays", ".", "indices", ".", "length", ";", "}", "else", "if", "(", "arrays", ".", "position", ")", "{", "buffers", ".", "numElements", "=", "arrays", ".", "position", ".", "length", "/", "3", ";", "}", "return", "buffers", ";", "}" ]
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
train
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", ".", "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", ")", ";", "}", "}" ]
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
train
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
train
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", ")", "{", "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", "(", "/", "^[\\\\\\/]", "/", ",", "''", ")", ")", ";", "}" ]
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
train
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", "=", "abspath", "(", "this", ".", "baseURI", ",", "fileRef", ")", ";", "file", "=", "this", ".", "map", "[", "filename", "]", ";", "if", "(", "!", "file", ")", "{", "this", ".", "flow", ".", "warn", "(", "{", "file", ":", "filename", ",", "message", ":", "'File `'", "+", "fileRef", "+", "'` not found in map'", "}", ")", ";", "return", ";", "}", "}", "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", ")", ";", "var", "index", "=", "this", ".", "queue", ".", "indexOf", "(", "file", ")", ";", "if", "(", "index", "!=", "-", "1", ")", "this", ".", "queue", ".", "splice", "(", "index", ",", "1", ")", ";", "if", "(", "filename", ")", "delete", "this", ".", "map", "[", "filename", "]", ";", "}" ]
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
train
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", "(", "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", ";", "}" ]
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
train
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'", "?", "collapsed", ":", "false", ";", "Handler", ".", "call", "(", "this", ",", "level", ")", ";", "this", ".", "_grouping", "=", "grouping", ";", "this", ".", "_groupMethod", "=", "collapsed", "?", "'groupCollapsed'", ":", "'group'", ";", "this", ".", "_openGroup", "=", "''", ";", "}" ]
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
train
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", ".", "message", "=", "message", ";", "}" ]
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
train
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", "=", "typeof", "delay", "!==", "'undefined'", "?", "delay", ":", "false", ";", "this", ".", "_filename", "=", "filename", ";", "this", ".", "_mode", "=", "mode", ";", "this", ".", "_encoding", "=", "encoding", ";", "if", "(", "delay", ")", "{", "StreamHandler", ".", "call", "(", "this", ")", ";", "this", ".", "_stream", "=", "null", ";", "}", "else", "{", "StreamHandler", ".", "call", "(", "this", ",", "this", ".", "_open", "(", ")", ")", ";", "}", "}" ]
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
train
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", ":", "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", ")", ";", "this", ".", "_maxBytes", "=", "maxBytes", ";", "this", ".", "_backupCount", "=", "backupCount", ";", "this", ".", "_chain", "=", "Promise", ".", "resolve", "(", ")", ";", "}" ]
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
train
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", ";", "if", "(", "validator", ".", "apply", "(", "this", ",", "args", ")", ")", "{", "return", "func", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "message", ".", "apply", "(", "this", ",", "args", ")", ")", ";", "}", "}", ";", "}" ]
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
train
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 `[email protected]:${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 `[email protected]:${url}.git`; } return `https://github.com/${url}.git`; }
[ "function", "toRepoUrl", "(", "url", ")", "{", "if", "(", "url", ".", "startsWith", "(", "'git@'", ")", ")", "{", "if", "(", "argv", ".", "useSSH", ")", "{", "return", "url", ";", "}", "const", "m", "=", "url", ".", "match", "(", "/", "(https?:\\/\\/([^/]+)\\/|git@(.+):)([\\w\\d-_/]+)(.git)?", "/", ")", ";", "return", "`", "${", "m", "[", "3", "]", "}", "${", "m", "[", "4", "]", "}", "`", ";", "}", "if", "(", "url", ".", "startsWith", "(", "'http'", ")", ")", "{", "if", "(", "!", "argv", ".", "useSSH", ")", "{", "return", "url", ";", "}", "const", "m", "=", "url", ".", "match", "(", "/", "(https?:\\/\\/([^/]+)\\/|git@(.+):)([\\w\\d-_/]+)(.git)?", "/", ")", ";", "return", "`", "${", "m", "[", "2", "]", "}", "${", "m", "[", "4", "]", "}", "`", ";", "}", "if", "(", "!", "url", ".", "includes", "(", "'/'", ")", ")", "{", "url", "=", "`", "${", "url", "}", "`", ";", "}", "if", "(", "argv", ".", "useSSH", ")", "{", "return", "`", "${", "url", "}", "`", ";", "}", "return", "`", "${", "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
train
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", ")", "{", "const", "host", "=", "repo", ".", "match", "(", "/", ":\\/\\/([^/]+)", "/", ")", "[", "1", "]", ";", "const", "hostClean", "=", "host", ".", "replace", "(", "/", "\\.", "/", "g", ",", "'_'", ")", ".", "toUpperCase", "(", ")", ";", "const", "envVar", "=", "process", ".", "env", "[", "`", "${", "hostClean", "}", "`", "]", ";", "if", "(", "envVar", ")", "{", "return", "envVar", ";", "}", "return", "process", ".", "env", ".", "PHOVEA_GITHUB_CREDENTIALS", ";", "}" ]
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
train
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", "(", "(", "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", ")", "{", "console", ".", "log", "(", "out", ".", "join", "(", "'\\n'", ")", ")", ";", "}", "\\n", "}", "}", ")", ";", "}", ")", ";", "}" ]
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
train
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'", ":", "'npm'", ";", "return", "spawn", "(", "npm", ",", "(", "cmd", "||", "'install'", ")", ".", "split", "(", "' '", ")", ",", "{", "cwd", ",", "env", "}", ")", ";", "}" ]
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
train
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 .'", ")", ".", "split", "(", "' '", ")", ",", "{", "cwd", ",", "env", "}", ")", ";", "}" ]
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
train
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'", ")", ";", "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", ")", ";", "}", "}", ")", ";", "}" ]
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
train
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", "=", "task", ".", "job", ".", "_id", ";", "task", ".", "key", "=", "task", ".", "job", ".", "project", "+", "branchFromJob", "(", "task", ".", "job", ")", ";", "this", ".", "tasks", ".", "push", "(", "task", ")", ";", "process", ".", "nextTick", "(", "this", ".", "drain", ".", "bind", "(", "this", ")", ")", ";", "}" ]
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", "call", "it", "when", "this", "job", "s", "task", "completes", "." ]
6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218
https://github.com/Strider-CD/strider-simple-runner/blob/6784fcfa605abf21fe3dc6ddd5d2a2f5e98a6218/lib/jobqueue.js#L23-L42
train
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", ";", "var", "launchCount", "=", "this", ".", "concurrency", "-", "Object", ".", "keys", "(", "this", ".", "active", ")", ".", "length", ";", "var", "offset", "=", "0", ";", "var", "launchTasks", "=", "[", "]", ";", "while", "(", "launchTasks", ".", "length", "<", "launchCount", "&&", "this", ".", "tasks", ".", "length", ">", "offset", ")", "{", "var", "task", "=", "this", ".", "tasks", "[", "offset", "]", ";", "if", "(", "task", ".", "key", "in", "this", ".", "active", ")", "{", "offset", "+=", "1", ";", "}", "else", "{", "this", ".", "tasks", ".", "splice", "(", "offset", ",", "1", ")", ";", "launchTasks", ".", "push", "(", "task", ")", ";", "}", "}", "function", "makeTaskHandler", "(", "task", ")", "{", "return", "function", "(", "err", ")", "{", "delete", "self", ".", "active", "[", "task", ".", "key", "]", ";", "task", ".", "callback", "(", "err", ")", ";", "process", ".", "nextTick", "(", "self", ".", "drain", ".", "bind", "(", "self", ")", ")", ";", "}", ";", "}", "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", ")", ")", ";", "}", "if", "(", "this", ".", "drainCallback", ")", "{", "var", "lastCallback", "=", "this", ".", "drainCallback", ";", "this", ".", "drainCallback", "=", "null", ";", "lastCallback", "(", ")", ";", "}", "}" ]
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
train
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", ";", "}", "}", "return", "false", ";", "}" ]
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
train
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", ")", "{", "gulp", ".", "src", "(", "srcs", ",", "opts", ")", ".", "pipe", "(", "files", ")", ";", "}", ")", ")", ";", "return", "es", ".", "duplex", "(", "paths", ",", "files", ")", ";", "}" ]
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
train
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", ";", "}", ")", ")", ".", "pipe", "(", "block", ")", ";", "}" ]
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
train
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", "=", "pattern", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "'\\\\s*'", ")", ";", "\\\\", "}" ]
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
train
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", "(", "line", ")", ";", "return", "match", "?", "match", "[", "1", "]", ":", "match", ";", "}" ]
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
train
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", "=", "[", "]", ";", "$", "(", "'meta[property=\"og:description\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "content", "=", "$", "(", "this", ")", ".", "attr", "(", "'content'", ")", ";", "if", "(", "content", ")", "descriptions", ".", "push", "(", "content", ")", ";", "}", ")", ";", "$", "(", "'[itemprop=\"description\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "text", "=", "$", "(", "this", ")", ".", "text", "(", ")", ";", "if", "(", "text", ")", "descriptions", ".", "push", "(", "text", ")", ";", "}", ")", ";", "$", "(", "'meta[name=\"description\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "description", "=", "utils", ".", "inline", "(", "$", "(", "this", ")", ".", "attr", "(", "'content'", ")", ")", ".", "trim", "(", ")", ";", "if", "(", "description", ")", "descriptions", ".", "push", "(", "description", ")", ";", "}", ")", ";", "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", ";", "}" ]
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
train
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", ":", "true", ";", "return", "isValid", ";", "}" ]
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
train
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", "=", "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", ")", ";", "}", "}", ";", "$", "(", "'meta[property=\"og:image\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "content", "=", "$", "(", "this", ")", ".", "attr", "(", "'content'", ")", ";", "if", "(", "content", ")", "thumbs", ".", "push", "(", "utils", ".", "toURL", "(", "content", ")", ")", ";", "}", ")", ";", "$", "(", "'img[itemprop=\"image\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "addToThumbs", "(", "this", ")", ";", "}", ")", ";", "if", "(", "thumbs", ".", "length", "<", "1", ")", "{", "$", "(", "'img[id*=\"product\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "addToThumbs", "(", "this", ")", ";", "}", ")", ";", "$", "(", "'img[class*=\"product\"]'", ")", ".", "each", "(", "function", "(", ")", "{", "addToThumbs", "(", "this", ")", ";", "}", ")", ";", "}", "if", "(", "thumbs", ".", "length", "<", "10", ")", "{", "$", "(", "'img'", ")", ".", "each", "(", "function", "(", ")", "{", "if", "(", "$", "(", "this", ")", ".", "attr", "(", "'itemprop'", ")", "===", "'image'", ")", "return", ";", "var", "alt", "=", "$", "(", "this", ")", ".", "attr", "(", "'alt'", ")", ";", "if", "(", "alt", "===", "title", ")", "{", "addToThumbs", "(", "this", ",", "true", ")", ";", "}", "else", "{", "addToThumbs", "(", "this", ")", ";", "}", "}", ")", ";", "}", "if", "(", "thumbs", ".", "length", "===", "0", ")", "{", "thumbs", "=", "thumbsRejected", ";", "}", "return", "thumbs", ";", "}" ]
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
train
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", ";", "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", "]", ";", "var", "nameWebsite", "=", "utils", ".", "getWebsiteName", "(", "url", ")", ";", "var", "regex", "=", "new", "RegExp", "(", "nameWebsite", ",", "'i'", ")", ";", "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", ")", ";", "}" ]
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
train
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", "=", "[", "]", ";", "$", "(", "'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", ";", "}" ]
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
train
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", "{", "}", ";", "}", "const", "versions", "=", "{", "}", ";", "file", ".", "split", "(", "'\\n'", ")", ".", "\\n", "forEach", ";", "(", "(", "line", ")", "=>", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "if", "(", "line", ".", "startsWith", "(", "'-e'", ")", ")", "{", "const", "branchSeparator", "=", "line", ".", "indexOf", "(", "'@'", ")", ";", "const", "name", "=", "line", ".", "slice", "(", "0", ",", "branchSeparator", ")", ".", "trim", "(", ")", ";", "versions", "[", "name", "]", "=", "line", ".", "slice", "(", "branchSeparator", ")", ".", "trim", "(", ")", ";", "return", ";", "}", "if", "(", "line", ".", "startsWith", "(", "'#'", ")", "||", "line", ".", "startsWith", "(", "'-'", ")", ")", "{", "return", ";", "}", "const", "versionSeparator", "=", "line", ".", "search", "(", "/", "[\\^~=>!]", "/", ")", ";", "if", "(", "versionSeparator", ">=", "0", ")", "{", "const", "name", "=", "line", ".", "slice", "(", "0", ",", "versionSeparator", ")", ".", "trim", "(", ")", ";", "versions", "[", "name", "]", "=", "line", ".", "slice", "(", "versionSeparator", ")", ".", "trim", "(", ")", ";", "}", "else", "{", "versions", "[", "line", "]", "=", "''", ";", "}", "}", ")", "}" ]
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
train
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
train
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
train
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'", ",", "initClient", ")", "}", ")", "(", ")", ".", "catch", "(", "console", ".", "error", ")", "}" ]
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
train
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_id", ",", "discoveryDocs", ":", "DISCOVERY_DOCS", ",", "scope", ":", "SCOPES", "}", ")", ".", "then", "(", "function", "(", ")", "{", "gapi", ".", "auth2", ".", "getAuthInstance", "(", ")", ".", "isSignedIn", ".", "listen", "(", "updateSigninStatus", ")", ";", "updateSigninStatus", "(", "gapi", ".", "auth2", ".", "getAuthInstance", "(", ")", ".", "isSignedIn", ".", "get", "(", ")", ")", ";", "authorizeButton", ".", "onclick", "=", "handleAuthClick", ";", "signoutButton", ".", "onclick", "=", "handleSignoutClick", ";", "}", ",", "function", "(", "error", ")", "{", "appendPre", "(", "JSON", ".", "stringify", "(", "error", ",", "null", ",", "2", ")", ")", ";", "}", ")", ";", "}" ]
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
train
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", "(", ")", ";", "}", "else", "{", "authorizeButton", ".", "style", ".", "display", "=", "'block'", ";", "signoutButton", ".", "style", ".", "display", "=", "'none'", ";", "}", "}" ]
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
train
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'", ")", ";", "\\n", "}" ]
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
train
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", ")", "{", "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.'", ")", ";", "}", "}", ")", ";", "}" ]
Print files.
[ "Print", "files", "." ]
9f6180f28635f6acfc84e21572e85b333f4aa88d
https://github.com/leonardpauli/docs/blob/9f6180f28635f6acfc84e21572e85b333f4aa88d/app/api/external/google/drive/example/script.js#L109-L125
train
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'", ";", "this", ".", "_format", "=", "format", ";", "this", ".", "_timeFormat", "=", "timeFormat", ";", "}" ]
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
train
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", ";", "maybeDollar", "=", "'$'", ";", "}", "else", "{", "runtime", ".", "str", "+=", "runtime", ".", "depth", "?", "' <Sentence>'", ":", "'<Sentence>'", ";", "return", ";", "}", "}", "if", "(", "runtime", ".", "preferQuotes", ")", "{", "return", "stringifyStringMaybeQuotes", "(", "v", ",", "runtime", ",", "maybeDollar", ")", ";", "}", "return", "stringifyStringMaybeStringLine", "(", "v", ",", "runtime", ",", "maybeDollar", ")", ";", "}" ]
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
train
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", "}", "`", ")", ";", "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", ";", "}" ]
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
train
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", "(", "options", ".", "timeout", ")", ".", "redirects", "(", "options", ".", "redirects", ")", ".", "buffer", "(", "false", ")", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", "&&", "!", "err", ".", "status", ")", "return", "onError", "(", "err", ")", ";", "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", ")", ")", ";", "}", "var", "body", "=", "''", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "body", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "destroyed", ")", "return", ";", "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", ")", ";", "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", ")", ";", "}", "}", ")", ";", "function", "onError", "(", "err", ")", "{", "if", "(", "options", ".", "retries", "--", ")", "return", "getRequest", "(", "options", ",", "callback", ")", ";", "callback", "(", "err", ")", ";", "}", "return", "req", ";", "}" ]
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
train
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", "+", "'\"'", ")", ")", ";", "}", "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.'", ")", ")", ";", "}", "}" ]
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
train
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", "(", "contentType", ")", ";", "}" ]
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
train
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", ";", "this", ".", "initSchema", "(", ")", ";", "this", ".", "addFields", "(", "this", ".", "options", ")", ";", "var", "only", "=", "utils", ".", "arrayify", "(", "this", ".", "options", ".", "pick", "||", "this", ".", "options", ".", "only", ")", ";", "utils", ".", "define", "(", "this", ".", "options", ",", "'only'", ",", "only", ")", ";", "}" ]
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
train
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", "services", ".", "_host", ";", "Object", ".", "keys", "(", "services", ")", ".", "forEach", "(", "(", "k", ")", "=>", "{", "if", "(", "!", "isHelperContainer", "(", "k", ")", ")", "{", "mergeWith", "(", "services", "[", "k", "]", ",", "host", ")", ";", "}", "}", ")", ";", "return", "compose", ";", "}" ]
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
train
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", ")", "{", "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", "]", ")", ";", "}" ]
basis.object.extend
[ "basis", ".", "object", ".", "extend" ]
177018ab31b225cddb6a184693fe4746512e7af1
https://github.com/basisjs/basisjs-tools-build/blob/177018ab31b225cddb6a184693fe4746512e7af1/lib/extract/js/index.js#L604-L616
train
basisjs/basisjs-tools-build
lib/extract/js/index.js
function(token, this_, args){ //fconsole.log('getNamespace', arguments); var namespace = args[0]; if (namespace && namespace.type == 'Literal') { var ns = getNamespace(namespace.value); token.obj = ns.obj; token.ref_ = ns.ref_; if (args[1]) token.obj.setWrapper.run(token, this_, [args[1]]); } }
javascript
function(token, this_, args){ //fconsole.log('getNamespace', arguments); var namespace = args[0]; if (namespace && namespace.type == 'Literal') { var ns = getNamespace(namespace.value); token.obj = ns.obj; token.ref_ = ns.ref_; if (args[1]) token.obj.setWrapper.run(token, this_, [args[1]]); } }
[ "function", "(", "token", ",", "this_", ",", "args", ")", "{", "var", "namespace", "=", "args", "[", "0", "]", ";", "if", "(", "namespace", "&&", "namespace", ".", "type", "==", "'Literal'", ")", "{", "var", "ns", "=", "getNamespace", "(", "namespace", ".", "value", ")", ";", "token", ".", "obj", "=", "ns", ".", "obj", ";", "token", ".", "ref_", "=", "ns", ".", "ref_", ";", "if", "(", "args", "[", "1", "]", ")", "token", ".", "obj", ".", "setWrapper", ".", "run", "(", "token", ",", "this_", ",", "[", "args", "[", "1", "]", "]", ")", ";", "}", "}" ]
basis.namespace
[ "basis", ".", "namespace" ]
177018ab31b225cddb6a184693fe4746512e7af1
https://github.com/basisjs/basisjs-tools-build/blob/177018ab31b225cddb6a184693fe4746512e7af1/lib/extract/js/index.js#L626-L637
train
CartoDB/tangram-cartocss
src/translate.js
getReferenceIndexedByCSS
function getReferenceIndexedByCSS(ref) { var newRef = {}; for (var symb in ref.symbolizers) { for (var property in ref.symbolizers[symb]) { newRef[ref.symbolizers[symb][property].css] = ref.symbolizers[symb][property]; } } return newRef; }
javascript
function getReferenceIndexedByCSS(ref) { var newRef = {}; for (var symb in ref.symbolizers) { for (var property in ref.symbolizers[symb]) { newRef[ref.symbolizers[symb][property].css] = ref.symbolizers[symb][property]; } } return newRef; }
[ "function", "getReferenceIndexedByCSS", "(", "ref", ")", "{", "var", "newRef", "=", "{", "}", ";", "for", "(", "var", "symb", "in", "ref", ".", "symbolizers", ")", "{", "for", "(", "var", "property", "in", "ref", ".", "symbolizers", "[", "symb", "]", ")", "{", "newRef", "[", "ref", ".", "symbolizers", "[", "symb", "]", "[", "property", "]", ".", "css", "]", "=", "ref", ".", "symbolizers", "[", "symb", "]", "[", "property", "]", ";", "}", "}", "return", "newRef", ";", "}" ]
getReferenceIndexedByCSS returns a reference based on ref indexed by the CSS property name instead of the reference original property name it does a shallow copy of each property, therefore, it's possible to change the returned reference by changing the original one, don't do it
[ "getReferenceIndexedByCSS", "returns", "a", "reference", "based", "on", "ref", "indexed", "by", "the", "CSS", "property", "name", "instead", "of", "the", "reference", "original", "property", "name", "it", "does", "a", "shallow", "copy", "of", "each", "property", "therefore", "it", "s", "possible", "to", "change", "the", "returned", "reference", "by", "changing", "the", "original", "one", "don", "t", "do", "it" ]
df5f15c01d24bb284510dbf7cf464c5c26059e4d
https://github.com/CartoDB/tangram-cartocss/blob/df5f15c01d24bb284510dbf7cf464c5c26059e4d/src/translate.js#L6-L14
train
CartoDB/tangram-cartocss
src/translate.js
getOpacityOverride
function getOpacityOverride(sceneDrawGroup, isFill) { var opacity; if (isFill) { opacity = sceneDrawGroup._hidden['opacity:fill']; } else { opacity = sceneDrawGroup._hidden['opacity:outline']; } if (sceneDrawGroup._hidden['opacity:general'] !== undefined) { opacity = sceneDrawGroup._hidden['opacity:general']; } return opacity; }
javascript
function getOpacityOverride(sceneDrawGroup, isFill) { var opacity; if (isFill) { opacity = sceneDrawGroup._hidden['opacity:fill']; } else { opacity = sceneDrawGroup._hidden['opacity:outline']; } if (sceneDrawGroup._hidden['opacity:general'] !== undefined) { opacity = sceneDrawGroup._hidden['opacity:general']; } return opacity; }
[ "function", "getOpacityOverride", "(", "sceneDrawGroup", ",", "isFill", ")", "{", "var", "opacity", ";", "if", "(", "isFill", ")", "{", "opacity", "=", "sceneDrawGroup", ".", "_hidden", "[", "'opacity:fill'", "]", ";", "}", "else", "{", "opacity", "=", "sceneDrawGroup", ".", "_hidden", "[", "'opacity:outline'", "]", ";", "}", "if", "(", "sceneDrawGroup", ".", "_hidden", "[", "'opacity:general'", "]", "!==", "undefined", ")", "{", "opacity", "=", "sceneDrawGroup", ".", "_hidden", "[", "'opacity:general'", "]", ";", "}", "return", "opacity", ";", "}" ]
Returns the final opacity override selecting between fill-opacity and outline-opacity. Returned value can be a float or a function string to be called at Tangram's runtime if the override is active A falseable value will be returned if the override is not active
[ "Returns", "the", "final", "opacity", "override", "selecting", "between", "fill", "-", "opacity", "and", "outline", "-", "opacity", ".", "Returned", "value", "can", "be", "a", "float", "or", "a", "function", "string", "to", "be", "called", "at", "Tangram", "s", "runtime", "if", "the", "override", "is", "active", "A", "falseable", "value", "will", "be", "returned", "if", "the", "override", "is", "not", "active" ]
df5f15c01d24bb284510dbf7cf464c5c26059e4d
https://github.com/CartoDB/tangram-cartocss/blob/df5f15c01d24bb284510dbf7cf464c5c26059e4d/src/translate.js#L40-L51
train
CartoDB/tangram-cartocss
src/translate.js
getFunctionFromDefaultAndShaderValue
function getFunctionFromDefaultAndShaderValue(sceneDrawGroup, ccssProperty, defaultValue, shaderValue) { if (referenceCSS[ccssProperty].type === 'color') { defaultValue = `'${color.normalize(defaultValue, tangramReference)}'`; } var fn = `var _value=${defaultValue};`; shaderValue.js.forEach(function (code) { if (code.search(/data\['mapnik::\S+'\]/) >= 0) { throw new Error('mapnik selector present in the CartoCSS'); } fn += code; }); if (referenceCSS[ccssProperty].type === 'color') { fn += getColorOverrideCode(sceneDrawGroup, ccssProperty.indexOf('fill') >= 0); } if (ccssProperty === 'line-width') { fn += '_value=_value*$meters_per_pixel;'; } fn += 'return _value;'; return wrapFn(fn); }
javascript
function getFunctionFromDefaultAndShaderValue(sceneDrawGroup, ccssProperty, defaultValue, shaderValue) { if (referenceCSS[ccssProperty].type === 'color') { defaultValue = `'${color.normalize(defaultValue, tangramReference)}'`; } var fn = `var _value=${defaultValue};`; shaderValue.js.forEach(function (code) { if (code.search(/data\['mapnik::\S+'\]/) >= 0) { throw new Error('mapnik selector present in the CartoCSS'); } fn += code; }); if (referenceCSS[ccssProperty].type === 'color') { fn += getColorOverrideCode(sceneDrawGroup, ccssProperty.indexOf('fill') >= 0); } if (ccssProperty === 'line-width') { fn += '_value=_value*$meters_per_pixel;'; } fn += 'return _value;'; return wrapFn(fn); }
[ "function", "getFunctionFromDefaultAndShaderValue", "(", "sceneDrawGroup", ",", "ccssProperty", ",", "defaultValue", ",", "shaderValue", ")", "{", "if", "(", "referenceCSS", "[", "ccssProperty", "]", ".", "type", "===", "'color'", ")", "{", "defaultValue", "=", "`", "${", "color", ".", "normalize", "(", "defaultValue", ",", "tangramReference", ")", "}", "`", ";", "}", "var", "fn", "=", "`", "${", "defaultValue", "}", "`", ";", "shaderValue", ".", "js", ".", "forEach", "(", "function", "(", "code", ")", "{", "if", "(", "code", ".", "search", "(", "/", "data\\['mapnik::\\S+'\\]", "/", ")", ">=", "0", ")", "{", "throw", "new", "Error", "(", "'mapnik selector present in the CartoCSS'", ")", ";", "}", "fn", "+=", "code", ";", "}", ")", ";", "if", "(", "referenceCSS", "[", "ccssProperty", "]", ".", "type", "===", "'color'", ")", "{", "fn", "+=", "getColorOverrideCode", "(", "sceneDrawGroup", ",", "ccssProperty", ".", "indexOf", "(", "'fill'", ")", ">=", "0", ")", ";", "}", "if", "(", "ccssProperty", "===", "'line-width'", ")", "{", "fn", "+=", "'_value=_value*$meters_per_pixel;'", ";", "}", "fn", "+=", "'return _value;'", ";", "return", "wrapFn", "(", "fn", ")", ";", "}" ]
Returns a function string that sets the value to the default one and then executes the shader value code
[ "Returns", "a", "function", "string", "that", "sets", "the", "value", "to", "the", "default", "one", "and", "then", "executes", "the", "shader", "value", "code" ]
df5f15c01d24bb284510dbf7cf464c5c26059e4d
https://github.com/CartoDB/tangram-cartocss/blob/df5f15c01d24bb284510dbf7cf464c5c26059e4d/src/translate.js#L84-L103
train
CartoDB/tangram-cartocss
src/translate.js
translateValue
function translateValue(sceneDrawGroup, ccssProperty, ccssValue) { if (ccssProperty.indexOf('comp-op') >= 0) { switch (ccssValue) { case 'src-over': return 'overlay'; case 'plus': return 'add'; default: return ccssValue; } } if (referenceCSS[ccssProperty].type === 'color') { return getColorFromLiteral(sceneDrawGroup, ccssValue, ccssProperty.indexOf('fill') >= 0); } if (ccssProperty.indexOf('width') >= 0) { ccssValue += 'px'; } if (ccssProperty.indexOf('allow-overlap') >= 0) { ccssValue = !ccssValue; } return ccssValue; }
javascript
function translateValue(sceneDrawGroup, ccssProperty, ccssValue) { if (ccssProperty.indexOf('comp-op') >= 0) { switch (ccssValue) { case 'src-over': return 'overlay'; case 'plus': return 'add'; default: return ccssValue; } } if (referenceCSS[ccssProperty].type === 'color') { return getColorFromLiteral(sceneDrawGroup, ccssValue, ccssProperty.indexOf('fill') >= 0); } if (ccssProperty.indexOf('width') >= 0) { ccssValue += 'px'; } if (ccssProperty.indexOf('allow-overlap') >= 0) { ccssValue = !ccssValue; } return ccssValue; }
[ "function", "translateValue", "(", "sceneDrawGroup", ",", "ccssProperty", ",", "ccssValue", ")", "{", "if", "(", "ccssProperty", ".", "indexOf", "(", "'comp-op'", ")", ">=", "0", ")", "{", "switch", "(", "ccssValue", ")", "{", "case", "'src-over'", ":", "return", "'overlay'", ";", "case", "'plus'", ":", "return", "'add'", ";", "default", ":", "return", "ccssValue", ";", "}", "}", "if", "(", "referenceCSS", "[", "ccssProperty", "]", ".", "type", "===", "'color'", ")", "{", "return", "getColorFromLiteral", "(", "sceneDrawGroup", ",", "ccssValue", ",", "ccssProperty", ".", "indexOf", "(", "'fill'", ")", ">=", "0", ")", ";", "}", "if", "(", "ccssProperty", ".", "indexOf", "(", "'width'", ")", ">=", "0", ")", "{", "ccssValue", "+=", "'px'", ";", "}", "if", "(", "ccssProperty", ".", "indexOf", "(", "'allow-overlap'", ")", ">=", "0", ")", "{", "ccssValue", "=", "!", "ccssValue", ";", "}", "return", "ccssValue", ";", "}" ]
Translates a ccssValue from the reference standard to the Tangram standard
[ "Translates", "a", "ccssValue", "from", "the", "reference", "standard", "to", "the", "Tangram", "standard" ]
df5f15c01d24bb284510dbf7cf464c5c26059e4d
https://github.com/CartoDB/tangram-cartocss/blob/df5f15c01d24bb284510dbf7cf464c5c26059e4d/src/translate.js#L106-L127
train
CartoDB/tangram-cartocss
src/translate.js
getFilterFn
function getFilterFn(layer, symbolizer) { const symbolizers = Object.keys(layer.shader) .filter(property => layer.shader[property].symbolizer === symbolizer); //No need to set a callback when at least one property is not filtered (i.e. it always activates the symbolizer) const alwaysActive = symbolizers .reduce((a, property) => a || !layer.shader[property].filtered, false); if (alwaysActive) { return undefined; } const fn = symbolizers .map((property) => layer.shader[property].js) .reduce((all, arr) => all.concat(arr), []) .join(''); return wrapFn(`var _value = null; ${fn} return _value !== null;`); }
javascript
function getFilterFn(layer, symbolizer) { const symbolizers = Object.keys(layer.shader) .filter(property => layer.shader[property].symbolizer === symbolizer); //No need to set a callback when at least one property is not filtered (i.e. it always activates the symbolizer) const alwaysActive = symbolizers .reduce((a, property) => a || !layer.shader[property].filtered, false); if (alwaysActive) { return undefined; } const fn = symbolizers .map((property) => layer.shader[property].js) .reduce((all, arr) => all.concat(arr), []) .join(''); return wrapFn(`var _value = null; ${fn} return _value !== null;`); }
[ "function", "getFilterFn", "(", "layer", ",", "symbolizer", ")", "{", "const", "symbolizers", "=", "Object", ".", "keys", "(", "layer", ".", "shader", ")", ".", "filter", "(", "property", "=>", "layer", ".", "shader", "[", "property", "]", ".", "symbolizer", "===", "symbolizer", ")", ";", "const", "alwaysActive", "=", "symbolizers", ".", "reduce", "(", "(", "a", ",", "property", ")", "=>", "a", "||", "!", "layer", ".", "shader", "[", "property", "]", ".", "filtered", ",", "false", ")", ";", "if", "(", "alwaysActive", ")", "{", "return", "undefined", ";", "}", "const", "fn", "=", "symbolizers", ".", "map", "(", "(", "property", ")", "=>", "layer", ".", "shader", "[", "property", "]", ".", "js", ")", ".", "reduce", "(", "(", "all", ",", "arr", ")", "=>", "all", ".", "concat", "(", "arr", ")", ",", "[", "]", ")", ".", "join", "(", "''", ")", ";", "return", "wrapFn", "(", "`", "${", "fn", "}", "`", ")", ";", "}" ]
Returns a function string that dynamically filters symbolizer based on conditional properties
[ "Returns", "a", "function", "string", "that", "dynamically", "filters", "symbolizer", "based", "on", "conditional", "properties" ]
df5f15c01d24bb284510dbf7cf464c5c26059e4d
https://github.com/CartoDB/tangram-cartocss/blob/df5f15c01d24bb284510dbf7cf464c5c26059e4d/src/translate.js#L165-L183
train
stealjs/steal-conditional
conditional.js
getGlob
function getGlob() { if (isNode) { return loader.import("@node-require", { name: module.id }) .then(function(nodeRequire) { return nodeRequire("glob"); }); } return Promise.resolve(); }
javascript
function getGlob() { if (isNode) { return loader.import("@node-require", { name: module.id }) .then(function(nodeRequire) { return nodeRequire("glob"); }); } return Promise.resolve(); }
[ "function", "getGlob", "(", ")", "{", "if", "(", "isNode", ")", "{", "return", "loader", ".", "import", "(", "\"@node-require\"", ",", "{", "name", ":", "module", ".", "id", "}", ")", ".", "then", "(", "function", "(", "nodeRequire", ")", "{", "return", "nodeRequire", "(", "\"glob\"", ")", ";", "}", ")", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}" ]
get some node modules through @node-require which is a noop in the browser
[ "get", "some", "node", "modules", "through" ]
04e1c363d5af183aef52c6cb5a75762ca69fc5bf
https://github.com/stealjs/steal-conditional/blob/04e1c363d5af183aef52c6cb5a75762ca69fc5bf/conditional.js#L36-L45
train
stealjs/steal-conditional
conditional.js
getModuleName
function getModuleName(nameWithConditional, variation) { var modName; var conditionIndex = nameWithConditional.search(conditionalRegEx); // look for any "/" after the condition var lastSlashIndex = nameWithConditional.indexOf("/", nameWithConditional.indexOf("}")); // substitution of a folder name if (lastSlashIndex !== -1) { modName = nameWithConditional.substr(0, conditionIndex) + variation; } else { modName = nameWithConditional.replace(conditionalRegEx, variation); } return modName; }
javascript
function getModuleName(nameWithConditional, variation) { var modName; var conditionIndex = nameWithConditional.search(conditionalRegEx); // look for any "/" after the condition var lastSlashIndex = nameWithConditional.indexOf("/", nameWithConditional.indexOf("}")); // substitution of a folder name if (lastSlashIndex !== -1) { modName = nameWithConditional.substr(0, conditionIndex) + variation; } else { modName = nameWithConditional.replace(conditionalRegEx, variation); } return modName; }
[ "function", "getModuleName", "(", "nameWithConditional", ",", "variation", ")", "{", "var", "modName", ";", "var", "conditionIndex", "=", "nameWithConditional", ".", "search", "(", "conditionalRegEx", ")", ";", "var", "lastSlashIndex", "=", "nameWithConditional", ".", "indexOf", "(", "\"/\"", ",", "nameWithConditional", ".", "indexOf", "(", "\"}\"", ")", ")", ";", "if", "(", "lastSlashIndex", "!==", "-", "1", ")", "{", "modName", "=", "nameWithConditional", ".", "substr", "(", "0", ",", "conditionIndex", ")", "+", "variation", ";", "}", "else", "{", "modName", "=", "nameWithConditional", ".", "replace", "(", "conditionalRegEx", ",", "variation", ")", ";", "}", "return", "modName", ";", "}" ]
Returns the bundle module name for a string substitution @param {string} nameWithConditional The module identifier including the condition @param {string} variation A match of the glob pattern @return {string} The bundle module name
[ "Returns", "the", "bundle", "module", "name", "for", "a", "string", "substitution" ]
04e1c363d5af183aef52c6cb5a75762ca69fc5bf
https://github.com/stealjs/steal-conditional/blob/04e1c363d5af183aef52c6cb5a75762ca69fc5bf/conditional.js#L57-L74
train
stealjs/steal-conditional
conditional.js
function(m) { var conditionValue = (typeof m === "object") ? readMemberExpression(conditionExport, m) : m; if (substitution) { if (typeof conditionValue !== "string") { throw new TypeError( "The condition value for " + conditionalMatch[0] + " doesn't resolve to a string." ); } name = name.replace(conditionalRegEx, conditionValue); } else { if (typeof conditionValue !== "boolean") { throw new TypeError( "The condition value for " + conditionalMatch[0] + " isn't resolving to a boolean." ); } if (booleanNegation) { conditionValue = !conditionValue; } if (!conditionValue) { name = "@empty"; } else { name = name.replace(conditionalRegEx, ""); } } if (name === "@empty") { return normalize.call(loader, name, parentName, parentAddress, pluginNormalize); } else { // call the full normalize in case the module name // is an npm package (that needs to be normalized) return loader.normalize.call(loader, name, parentName, parentAddress, pluginNormalize); } }
javascript
function(m) { var conditionValue = (typeof m === "object") ? readMemberExpression(conditionExport, m) : m; if (substitution) { if (typeof conditionValue !== "string") { throw new TypeError( "The condition value for " + conditionalMatch[0] + " doesn't resolve to a string." ); } name = name.replace(conditionalRegEx, conditionValue); } else { if (typeof conditionValue !== "boolean") { throw new TypeError( "The condition value for " + conditionalMatch[0] + " isn't resolving to a boolean." ); } if (booleanNegation) { conditionValue = !conditionValue; } if (!conditionValue) { name = "@empty"; } else { name = name.replace(conditionalRegEx, ""); } } if (name === "@empty") { return normalize.call(loader, name, parentName, parentAddress, pluginNormalize); } else { // call the full normalize in case the module name // is an npm package (that needs to be normalized) return loader.normalize.call(loader, name, parentName, parentAddress, pluginNormalize); } }
[ "function", "(", "m", ")", "{", "var", "conditionValue", "=", "(", "typeof", "m", "===", "\"object\"", ")", "?", "readMemberExpression", "(", "conditionExport", ",", "m", ")", ":", "m", ";", "if", "(", "substitution", ")", "{", "if", "(", "typeof", "conditionValue", "!==", "\"string\"", ")", "{", "throw", "new", "TypeError", "(", "\"The condition value for \"", "+", "conditionalMatch", "[", "0", "]", "+", "\" doesn't resolve to a string.\"", ")", ";", "}", "name", "=", "name", ".", "replace", "(", "conditionalRegEx", ",", "conditionValue", ")", ";", "}", "else", "{", "if", "(", "typeof", "conditionValue", "!==", "\"boolean\"", ")", "{", "throw", "new", "TypeError", "(", "\"The condition value for \"", "+", "conditionalMatch", "[", "0", "]", "+", "\" isn't resolving to a boolean.\"", ")", ";", "}", "if", "(", "booleanNegation", ")", "{", "conditionValue", "=", "!", "conditionValue", ";", "}", "if", "(", "!", "conditionValue", ")", "{", "name", "=", "\"@empty\"", ";", "}", "else", "{", "name", "=", "name", ".", "replace", "(", "conditionalRegEx", ",", "\"\"", ")", ";", "}", "}", "if", "(", "name", "===", "\"@empty\"", ")", "{", "return", "normalize", ".", "call", "(", "loader", ",", "name", ",", "parentName", ",", "parentAddress", ",", "pluginNormalize", ")", ";", "}", "else", "{", "return", "loader", ".", "normalize", ".", "call", "(", "loader", ",", "name", ",", "parentName", ",", "parentAddress", ",", "pluginNormalize", ")", ";", "}", "}" ]
!steal-remove-end
[ "!steal", "-", "remove", "-", "end" ]
04e1c363d5af183aef52c6cb5a75762ca69fc5bf
https://github.com/stealjs/steal-conditional/blob/04e1c363d5af183aef52c6cb5a75762ca69fc5bf/conditional.js#L341-L381
train
jose-pleonasm/py-logging
core/Handler.js
Handler
function Handler(level) { level = level || Logger.NOTSET; if (Logger.getLevelName(level) === '') { throw new Error('Argument 1 of Handler.constructor has unsupported' + ' value \'' + level + '\''); } Filterer.call(this); /** * @private * @type {number} */ this._level = level; /** * @private * @type {Object} */ this._formatter = null; }
javascript
function Handler(level) { level = level || Logger.NOTSET; if (Logger.getLevelName(level) === '') { throw new Error('Argument 1 of Handler.constructor has unsupported' + ' value \'' + level + '\''); } Filterer.call(this); /** * @private * @type {number} */ this._level = level; /** * @private * @type {Object} */ this._formatter = null; }
[ "function", "Handler", "(", "level", ")", "{", "level", "=", "level", "||", "Logger", ".", "NOTSET", ";", "if", "(", "Logger", ".", "getLevelName", "(", "level", ")", "===", "''", ")", "{", "throw", "new", "Error", "(", "'Argument 1 of Handler.constructor has unsupported'", "+", "' value \\''", "+", "\\'", "+", "level", ")", ";", "}", "'\\''", "\\'", "Filterer", ".", "call", "(", "this", ")", ";", "}" ]
An abstract handler. @constructor Handler @extends Filterer @param {number} [level=NOTSET]
[ "An", "abstract", "handler", "." ]
598f41284311ea6a837d4ba56236301abe689b09
https://github.com/jose-pleonasm/py-logging/blob/598f41284311ea6a837d4ba56236301abe689b09/core/Handler.js#L12-L33
train
sasaplus1/ltsv.js
cjs/parser.js
baseParse
function baseParse(text, strict) { const lines = String(text).replace(/(?:\r?\n)+$/, '').split(/\r?\n/); const records = []; for (let i = 0, len = lines.length; i < len; ++i) { records[i] = baseParseLine(lines[i], strict); } return records; }
javascript
function baseParse(text, strict) { const lines = String(text).replace(/(?:\r?\n)+$/, '').split(/\r?\n/); const records = []; for (let i = 0, len = lines.length; i < len; ++i) { records[i] = baseParseLine(lines[i], strict); } return records; }
[ "function", "baseParse", "(", "text", ",", "strict", ")", "{", "const", "lines", "=", "String", "(", "text", ")", ".", "replace", "(", "/", "(?:\\r?\\n)+$", "/", ",", "''", ")", ".", "split", "(", "/", "\\r?\\n", "/", ")", ";", "const", "records", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "lines", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "records", "[", "i", "]", "=", "baseParseLine", "(", "lines", "[", "i", "]", ",", "strict", ")", ";", "}", "return", "records", ";", "}" ]
parse LTSV text. @private @param {string} text @param {boolean} strict @returns {Object[]}
[ "parse", "LTSV", "text", "." ]
66eb96de5957905260864912e796f08e49ff222c
https://github.com/sasaplus1/ltsv.js/blob/66eb96de5957905260864912e796f08e49ff222c/cjs/parser.js#L61-L70
train
sasaplus1/ltsv.js
cjs/parser.js
baseParseLine
function baseParseLine(line, strict) { const fields = String(line).replace(/(?:\r?\n)+$/, '').split('\t'); const record = {}; for (let i = 0, len = fields.length; i < len; ++i) { const _splitField = splitField(fields[i], strict), label = _splitField.label, value = _splitField.value; record[label] = value; } return record; }
javascript
function baseParseLine(line, strict) { const fields = String(line).replace(/(?:\r?\n)+$/, '').split('\t'); const record = {}; for (let i = 0, len = fields.length; i < len; ++i) { const _splitField = splitField(fields[i], strict), label = _splitField.label, value = _splitField.value; record[label] = value; } return record; }
[ "function", "baseParseLine", "(", "line", ",", "strict", ")", "{", "const", "fields", "=", "String", "(", "line", ")", ".", "replace", "(", "/", "(?:\\r?\\n)+$", "/", ",", "''", ")", ".", "split", "(", "'\\t'", ")", ";", "\\t", "const", "record", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "fields", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "const", "_splitField", "=", "splitField", "(", "fields", "[", "i", "]", ",", "strict", ")", ",", "label", "=", "_splitField", ".", "label", ",", "value", "=", "_splitField", ".", "value", ";", "record", "[", "label", "]", "=", "value", ";", "}", "}" ]
parse LTSV record. @private @param {string} line @param {boolean} strict @returns {Object}
[ "parse", "LTSV", "record", "." ]
66eb96de5957905260864912e796f08e49ff222c
https://github.com/sasaplus1/ltsv.js/blob/66eb96de5957905260864912e796f08e49ff222c/cjs/parser.js#L81-L94
train
darrylwest/simple-node-db
examples/create-new-order.js
function(params) { const order = this; if (!params) { params = {}; } // the standards attributes this.id = params.id; this.dateCreated = params.dateCreated; this.lastUpdated = params.lastUpdated; this.version = params.version; this.customer = params.customer; this.orderDate = params.orderDate; this.total = params.total; this.items = params.items; this.calcTotal = function() { order.total = 0; order.items.forEach(function(item) { order.total += item.price; }); return order.total; }; }
javascript
function(params) { const order = this; if (!params) { params = {}; } // the standards attributes this.id = params.id; this.dateCreated = params.dateCreated; this.lastUpdated = params.lastUpdated; this.version = params.version; this.customer = params.customer; this.orderDate = params.orderDate; this.total = params.total; this.items = params.items; this.calcTotal = function() { order.total = 0; order.items.forEach(function(item) { order.total += item.price; }); return order.total; }; }
[ "function", "(", "params", ")", "{", "const", "order", "=", "this", ";", "if", "(", "!", "params", ")", "{", "params", "=", "{", "}", ";", "}", "this", ".", "id", "=", "params", ".", "id", ";", "this", ".", "dateCreated", "=", "params", ".", "dateCreated", ";", "this", ".", "lastUpdated", "=", "params", ".", "lastUpdated", ";", "this", ".", "version", "=", "params", ".", "version", ";", "this", ".", "customer", "=", "params", ".", "customer", ";", "this", ".", "orderDate", "=", "params", ".", "orderDate", ";", "this", ".", "total", "=", "params", ".", "total", ";", "this", ".", "items", "=", "params", ".", "items", ";", "this", ".", "calcTotal", "=", "function", "(", ")", "{", "order", ".", "total", "=", "0", ";", "order", ".", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "order", ".", "total", "+=", "item", ".", "price", ";", "}", ")", ";", "return", "order", ".", "total", ";", "}", ";", "}" ]
define the Order and Order Item objects
[ "define", "the", "Order", "and", "Order", "Item", "objects" ]
a456a653ef062a07bd6c5217c46000ac00ecf408
https://github.com/darrylwest/simple-node-db/blob/a456a653ef062a07bd6c5217c46000ac00ecf408/examples/create-new-order.js#L15-L43
train
bootprint/customize
index.js
customOverrider
function customOverrider (a, b, propertyName) { if (b == null) { return a } if (a == null) { // Invoke default overrider return undefined } // Some objects have custom overriders if (b._customize_custom_overrider && b._customize_custom_overrider instanceof Function) { return b._customize_custom_overrider(a, b, propertyName) } // Arrays should be concatenated if (Array.isArray(a)) { return a.concat(b) } // Merge values resolving promises, if they are not leaf-promises if (isPromiseAlike(a) || isPromiseAlike(b)) { return Promise.all([a, b]).then(function ([_a, _b]) { // Merge the promise results return mergeWith({}, { x: _a }, { x: _b }, customOverrider).x }) } // None of these options apply. Implicit "undefined" return value to invoke default overrider. }
javascript
function customOverrider (a, b, propertyName) { if (b == null) { return a } if (a == null) { // Invoke default overrider return undefined } // Some objects have custom overriders if (b._customize_custom_overrider && b._customize_custom_overrider instanceof Function) { return b._customize_custom_overrider(a, b, propertyName) } // Arrays should be concatenated if (Array.isArray(a)) { return a.concat(b) } // Merge values resolving promises, if they are not leaf-promises if (isPromiseAlike(a) || isPromiseAlike(b)) { return Promise.all([a, b]).then(function ([_a, _b]) { // Merge the promise results return mergeWith({}, { x: _a }, { x: _b }, customOverrider).x }) } // None of these options apply. Implicit "undefined" return value to invoke default overrider. }
[ "function", "customOverrider", "(", "a", ",", "b", ",", "propertyName", ")", "{", "if", "(", "b", "==", "null", ")", "{", "return", "a", "}", "if", "(", "a", "==", "null", ")", "{", "return", "undefined", "}", "if", "(", "b", ".", "_customize_custom_overrider", "&&", "b", ".", "_customize_custom_overrider", "instanceof", "Function", ")", "{", "return", "b", ".", "_customize_custom_overrider", "(", "a", ",", "b", ",", "propertyName", ")", "}", "if", "(", "Array", ".", "isArray", "(", "a", ")", ")", "{", "return", "a", ".", "concat", "(", "b", ")", "}", "if", "(", "isPromiseAlike", "(", "a", ")", "||", "isPromiseAlike", "(", "b", ")", ")", "{", "return", "Promise", ".", "all", "(", "[", "a", ",", "b", "]", ")", ".", "then", "(", "function", "(", "[", "_a", ",", "_b", "]", ")", "{", "return", "mergeWith", "(", "{", "}", ",", "{", "x", ":", "_a", "}", ",", "{", "x", ":", "_b", "}", ",", "customOverrider", ")", ".", "x", "}", ")", "}", "}" ]
Customize has predefined override rules for merging configs. * If the overriding object has a `_customize_custom_overrider` function-property, it isk called to perform the merger. * Arrays are concatenated * Promises are resolved and the results are merged @param a the overridden value @param b the overriding value @param propertyName the property name @returns {*} the merged value @private @readonly
[ "Customize", "has", "predefined", "override", "rules", "for", "merging", "configs", "." ]
0ea0c2c7a600cb6f4ea310e7c0a07f02ce8add18
https://github.com/bootprint/customize/blob/0ea0c2c7a600cb6f4ea310e7c0a07f02ce8add18/index.js#L343-L371
train
cronvel/kung-fig
lib/kfgCommon.js
MultiLine
function MultiLine( type , fold , applicable , options ) { this.type = type ; this.fold = !! fold ; this.applicable = !! applicable ; this.options = options ; this.lines = [] ; }
javascript
function MultiLine( type , fold , applicable , options ) { this.type = type ; this.fold = !! fold ; this.applicable = !! applicable ; this.options = options ; this.lines = [] ; }
[ "function", "MultiLine", "(", "type", ",", "fold", ",", "applicable", ",", "options", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "fold", "=", "!", "!", "fold", ";", "this", ".", "applicable", "=", "!", "!", "applicable", ";", "this", ".", "options", "=", "options", ";", "this", ".", "lines", "=", "[", "]", ";", "}" ]
An object to ease multi-line scalar values
[ "An", "object", "to", "ease", "multi", "-", "line", "scalar", "values" ]
a862c37237a283b4c0a4a5ff0bde6617d77104eb
https://github.com/cronvel/kung-fig/blob/a862c37237a283b4c0a4a5ff0bde6617d77104eb/lib/kfgCommon.js#L47-L53
train
cloudkick/whiskey
lib/common.js
function(callback) { self._getConnection(function(err, connection) { if (err) { callback(new Error('Unable to establish connection with the master ' + 'process')); return; } self._connection = connection; callback(); }); }
javascript
function(callback) { self._getConnection(function(err, connection) { if (err) { callback(new Error('Unable to establish connection with the master ' + 'process')); return; } self._connection = connection; callback(); }); }
[ "function", "(", "callback", ")", "{", "self", ".", "_getConnection", "(", "function", "(", "err", ",", "connection", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "new", "Error", "(", "'Unable to establish connection with the master '", "+", "'process'", ")", ")", ";", "return", ";", "}", "self", ".", "_connection", "=", "connection", ";", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Obtain the connection
[ "Obtain", "the", "connection" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/common.js#L333-L344
train