id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
22,000
web-perf/react-worker-dom
src/worker/index.js
render
function render(element) { // Is the given element valid? invariant( ReactElement.isValidElement(element), 'render(): You must pass a valid ReactElement.' ); const id = ReactInstanceHandles.createReactRootID(); // Creating a root id & creating the screen const component = instantiateReactComponent(element); // Mounting the app const transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); ReactWWIDOperations.setRoot(new WorkerDomNodeStub('0', 'div', {})); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(() => { transaction.perform(() => { component.mountComponent(id, transaction, {}); }); ReactUpdates.ReactReconcileTransaction.release(transaction); }); return component._instance; }
javascript
function render(element) { // Is the given element valid? invariant( ReactElement.isValidElement(element), 'render(): You must pass a valid ReactElement.' ); const id = ReactInstanceHandles.createReactRootID(); // Creating a root id & creating the screen const component = instantiateReactComponent(element); // Mounting the app const transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); ReactWWIDOperations.setRoot(new WorkerDomNodeStub('0', 'div', {})); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(() => { transaction.perform(() => { component.mountComponent(id, transaction, {}); }); ReactUpdates.ReactReconcileTransaction.release(transaction); }); return component._instance; }
[ "function", "render", "(", "element", ")", "{", "// Is the given element valid?", "invariant", "(", "ReactElement", ".", "isValidElement", "(", "element", ")", ",", "'render(): You must pass a valid ReactElement.'", ")", ";", "const", "id", "=", "ReactInstanceHandles", ".", "createReactRootID", "(", ")", ";", "// Creating a root id & creating the screen", "const", "component", "=", "instantiateReactComponent", "(", "element", ")", ";", "// Mounting the app", "const", "transaction", "=", "ReactUpdates", ".", "ReactReconcileTransaction", ".", "getPooled", "(", ")", ";", "ReactWWIDOperations", ".", "setRoot", "(", "new", "WorkerDomNodeStub", "(", "'0'", ",", "'div'", ",", "{", "}", ")", ")", ";", "// The initial render is synchronous but any updates that happen during", "// rendering, in componentWillMount or componentDidMount, will be batched", "// according to the current batching strategy.", "ReactUpdates", ".", "batchedUpdates", "(", "(", ")", "=>", "{", "transaction", ".", "perform", "(", "(", ")", "=>", "{", "component", ".", "mountComponent", "(", "id", ",", "transaction", ",", "{", "}", ")", ";", "}", ")", ";", "ReactUpdates", ".", "ReactReconcileTransaction", ".", "release", "(", "transaction", ")", ";", "}", ")", ";", "return", "component", ".", "_instance", ";", "}" ]
Renders the given react element using a web worker. @param {ReactElement} element - Node to update. @return {ReactComponent} - The rendered component instance.
[ "Renders", "the", "given", "react", "element", "using", "a", "web", "worker", "." ]
8fc5c011bc5c5ff43c6f5b184b60f6edd5872a6b
https://github.com/web-perf/react-worker-dom/blob/8fc5c011bc5c5ff43c6f5b184b60f6edd5872a6b/src/worker/index.js#L22-L46
22,001
brendanashworth/generate-password
src/generate.js
function(max) { // gives a number between 0 (inclusive) and max (exclusive) var rand = crypto.randomBytes(1)[0]; while (rand >= 256 - (256 % max)) { rand = crypto.randomBytes(1)[0]; } return rand % max; }
javascript
function(max) { // gives a number between 0 (inclusive) and max (exclusive) var rand = crypto.randomBytes(1)[0]; while (rand >= 256 - (256 % max)) { rand = crypto.randomBytes(1)[0]; } return rand % max; }
[ "function", "(", "max", ")", "{", "// gives a number between 0 (inclusive) and max (exclusive)", "var", "rand", "=", "crypto", ".", "randomBytes", "(", "1", ")", "[", "0", "]", ";", "while", "(", "rand", ">=", "256", "-", "(", "256", "%", "max", ")", ")", "{", "rand", "=", "crypto", ".", "randomBytes", "(", "1", ")", "[", "0", "]", ";", "}", "return", "rand", "%", "max", ";", "}" ]
Generates a random number
[ "Generates", "a", "random", "number" ]
75032c47a1a13283decab5e963c582084ab6e72a
https://github.com/brendanashworth/generate-password/blob/75032c47a1a13283decab5e963c582084ab6e72a/src/generate.js#L6-L13
22,002
speckjs/speckjs
src/parsing/parse-comments.js
onComment
function onComment(isBlock, text, _s, _e, sLoc, eLoc) { var tRegex = /test\s*>\s*(.*)/i; var aRegex = /#\s*(.*)/i; var isTest = R.test(tRegex); var extractTest = R.pipe(R.match(tRegex), R.last(), R.trim()); var isAssertion = R.test(aRegex); var extractAssertion = R.pipe(R.match(aRegex), R.last(), R.trim()); var lastTestFound = R.last(tests); var newTest; function belongToTest(locLine, test) { return (test === undefined) ? false : locLine - 1 === test.loc.endLine; } function createEmptyTest(title) { return { title: title || null, loc: { startLine: sLoc.line, endLine: eLoc.line }, assertions: [] }; } function addAssertionToTest(assertion, test) { test.assertions.push(assertion); test.loc.endLine = eLoc.line; return test; } function setTestTitle(title, test) { test.title = title; return test; } function buildTest(test, string) { if (isTest(string)) { setTestTitle(extractTest(string), test); } else if (isAssertion(string)) { addAssertionToTest(extractAssertion(string), test); } return test; } if (!isBlock) { if (isTest(text)) { newTest = R.pipe(extractTest, createEmptyTest)(text); tests.push(newTest); } else if (isAssertion(text) && belongToTest(sLoc.line, lastTestFound)) { addAssertionToTest(extractAssertion(text), lastTestFound); } } if (isBlock && isTest(text)) { newTest = R.reduce(buildTest, createEmptyTest(), R.split('\n', text)); tests.push(newTest); } }
javascript
function onComment(isBlock, text, _s, _e, sLoc, eLoc) { var tRegex = /test\s*>\s*(.*)/i; var aRegex = /#\s*(.*)/i; var isTest = R.test(tRegex); var extractTest = R.pipe(R.match(tRegex), R.last(), R.trim()); var isAssertion = R.test(aRegex); var extractAssertion = R.pipe(R.match(aRegex), R.last(), R.trim()); var lastTestFound = R.last(tests); var newTest; function belongToTest(locLine, test) { return (test === undefined) ? false : locLine - 1 === test.loc.endLine; } function createEmptyTest(title) { return { title: title || null, loc: { startLine: sLoc.line, endLine: eLoc.line }, assertions: [] }; } function addAssertionToTest(assertion, test) { test.assertions.push(assertion); test.loc.endLine = eLoc.line; return test; } function setTestTitle(title, test) { test.title = title; return test; } function buildTest(test, string) { if (isTest(string)) { setTestTitle(extractTest(string), test); } else if (isAssertion(string)) { addAssertionToTest(extractAssertion(string), test); } return test; } if (!isBlock) { if (isTest(text)) { newTest = R.pipe(extractTest, createEmptyTest)(text); tests.push(newTest); } else if (isAssertion(text) && belongToTest(sLoc.line, lastTestFound)) { addAssertionToTest(extractAssertion(text), lastTestFound); } } if (isBlock && isTest(text)) { newTest = R.reduce(buildTest, createEmptyTest(), R.split('\n', text)); tests.push(newTest); } }
[ "function", "onComment", "(", "isBlock", ",", "text", ",", "_s", ",", "_e", ",", "sLoc", ",", "eLoc", ")", "{", "var", "tRegex", "=", "/", "test\\s*>\\s*(.*)", "/", "i", ";", "var", "aRegex", "=", "/", "#\\s*(.*)", "/", "i", ";", "var", "isTest", "=", "R", ".", "test", "(", "tRegex", ")", ";", "var", "extractTest", "=", "R", ".", "pipe", "(", "R", ".", "match", "(", "tRegex", ")", ",", "R", ".", "last", "(", ")", ",", "R", ".", "trim", "(", ")", ")", ";", "var", "isAssertion", "=", "R", ".", "test", "(", "aRegex", ")", ";", "var", "extractAssertion", "=", "R", ".", "pipe", "(", "R", ".", "match", "(", "aRegex", ")", ",", "R", ".", "last", "(", ")", ",", "R", ".", "trim", "(", ")", ")", ";", "var", "lastTestFound", "=", "R", ".", "last", "(", "tests", ")", ";", "var", "newTest", ";", "function", "belongToTest", "(", "locLine", ",", "test", ")", "{", "return", "(", "test", "===", "undefined", ")", "?", "false", ":", "locLine", "-", "1", "===", "test", ".", "loc", ".", "endLine", ";", "}", "function", "createEmptyTest", "(", "title", ")", "{", "return", "{", "title", ":", "title", "||", "null", ",", "loc", ":", "{", "startLine", ":", "sLoc", ".", "line", ",", "endLine", ":", "eLoc", ".", "line", "}", ",", "assertions", ":", "[", "]", "}", ";", "}", "function", "addAssertionToTest", "(", "assertion", ",", "test", ")", "{", "test", ".", "assertions", ".", "push", "(", "assertion", ")", ";", "test", ".", "loc", ".", "endLine", "=", "eLoc", ".", "line", ";", "return", "test", ";", "}", "function", "setTestTitle", "(", "title", ",", "test", ")", "{", "test", ".", "title", "=", "title", ";", "return", "test", ";", "}", "function", "buildTest", "(", "test", ",", "string", ")", "{", "if", "(", "isTest", "(", "string", ")", ")", "{", "setTestTitle", "(", "extractTest", "(", "string", ")", ",", "test", ")", ";", "}", "else", "if", "(", "isAssertion", "(", "string", ")", ")", "{", "addAssertionToTest", "(", "extractAssertion", "(", "string", ")", ",", "test", ")", ";", "}", "return", "test", ";", "}", "if", "(", "!", "isBlock", ")", "{", "if", "(", "isTest", "(", "text", ")", ")", "{", "newTest", "=", "R", ".", "pipe", "(", "extractTest", ",", "createEmptyTest", ")", "(", "text", ")", ";", "tests", ".", "push", "(", "newTest", ")", ";", "}", "else", "if", "(", "isAssertion", "(", "text", ")", "&&", "belongToTest", "(", "sLoc", ".", "line", ",", "lastTestFound", ")", ")", "{", "addAssertionToTest", "(", "extractAssertion", "(", "text", ")", ",", "lastTestFound", ")", ";", "}", "}", "if", "(", "isBlock", "&&", "isTest", "(", "text", ")", ")", "{", "newTest", "=", "R", ".", "reduce", "(", "buildTest", ",", "createEmptyTest", "(", ")", ",", "R", ".", "split", "(", "'\\n'", ",", "text", ")", ")", ";", "tests", ".", "push", "(", "newTest", ")", ";", "}", "}" ]
Sanitizing iterator to run on each comment found during parsing
[ "Sanitizing", "iterator", "to", "run", "on", "each", "comment", "found", "during", "parsing" ]
860d90bc4479287f316c8dfa8695572c61cda879
https://github.com/speckjs/speckjs/blob/860d90bc4479287f316c8dfa8695572c61cda879/src/parsing/parse-comments.js#L32-L88
22,003
nol13/fuzzball.js
lib/xregexp/unicode-base.js
charCode
function charCode(chr) { var esc = /^\\[xu](.+)/.exec(chr); return esc ? dec(esc[1]) : chr.charCodeAt(chr.charAt(0) === '\\' ? 1 : 0); }
javascript
function charCode(chr) { var esc = /^\\[xu](.+)/.exec(chr); return esc ? dec(esc[1]) : chr.charCodeAt(chr.charAt(0) === '\\' ? 1 : 0); }
[ "function", "charCode", "(", "chr", ")", "{", "var", "esc", "=", "/", "^\\\\[xu](.+)", "/", ".", "exec", "(", "chr", ")", ";", "return", "esc", "?", "dec", "(", "esc", "[", "1", "]", ")", ":", "chr", ".", "charCodeAt", "(", "chr", ".", "charAt", "(", "0", ")", "===", "'\\\\'", "?", "1", ":", "0", ")", ";", "}" ]
Gets the decimal code of a literal code unit, \xHH, \uHHHH, or a backslash-escaped literal
[ "Gets", "the", "decimal", "code", "of", "a", "literal", "code", "unit", "\\", "xHH", "\\", "uHHHH", "or", "a", "backslash", "-", "escaped", "literal" ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/unicode-base.js#L42-L47
22,004
nol13/fuzzball.js
lib/xregexp/unicode-base.js
invertBmp
function invertBmp(range) { var output = ''; var lastEnd = -1; XRegExp.forEach( range, /(\\x..|\\u....|\\?[\s\S])(?:-(\\x..|\\u....|\\?[\s\S]))?/, function(m) { var start = charCode(m[1]); if (start > (lastEnd + 1)) { output += '\\u' + pad4(hex(lastEnd + 1)); if (start > (lastEnd + 2)) { output += '-\\u' + pad4(hex(start - 1)); } } lastEnd = charCode(m[2] || m[1]); } ); if (lastEnd < 0xFFFF) { output += '\\u' + pad4(hex(lastEnd + 1)); if (lastEnd < 0xFFFE) { output += '-\\uFFFF'; } } return output; }
javascript
function invertBmp(range) { var output = ''; var lastEnd = -1; XRegExp.forEach( range, /(\\x..|\\u....|\\?[\s\S])(?:-(\\x..|\\u....|\\?[\s\S]))?/, function(m) { var start = charCode(m[1]); if (start > (lastEnd + 1)) { output += '\\u' + pad4(hex(lastEnd + 1)); if (start > (lastEnd + 2)) { output += '-\\u' + pad4(hex(start - 1)); } } lastEnd = charCode(m[2] || m[1]); } ); if (lastEnd < 0xFFFF) { output += '\\u' + pad4(hex(lastEnd + 1)); if (lastEnd < 0xFFFE) { output += '-\\uFFFF'; } } return output; }
[ "function", "invertBmp", "(", "range", ")", "{", "var", "output", "=", "''", ";", "var", "lastEnd", "=", "-", "1", ";", "XRegExp", ".", "forEach", "(", "range", ",", "/", "(\\\\x..|\\\\u....|\\\\?[\\s\\S])(?:-(\\\\x..|\\\\u....|\\\\?[\\s\\S]))?", "/", ",", "function", "(", "m", ")", "{", "var", "start", "=", "charCode", "(", "m", "[", "1", "]", ")", ";", "if", "(", "start", ">", "(", "lastEnd", "+", "1", ")", ")", "{", "output", "+=", "'\\\\u'", "+", "pad4", "(", "hex", "(", "lastEnd", "+", "1", ")", ")", ";", "if", "(", "start", ">", "(", "lastEnd", "+", "2", ")", ")", "{", "output", "+=", "'-\\\\u'", "+", "pad4", "(", "hex", "(", "start", "-", "1", ")", ")", ";", "}", "}", "lastEnd", "=", "charCode", "(", "m", "[", "2", "]", "||", "m", "[", "1", "]", ")", ";", "}", ")", ";", "if", "(", "lastEnd", "<", "0xFFFF", ")", "{", "output", "+=", "'\\\\u'", "+", "pad4", "(", "hex", "(", "lastEnd", "+", "1", ")", ")", ";", "if", "(", "lastEnd", "<", "0xFFFE", ")", "{", "output", "+=", "'-\\\\uFFFF'", ";", "}", "}", "return", "output", ";", "}" ]
Inverts a list of ordered BMP characters and ranges
[ "Inverts", "a", "list", "of", "ordered", "BMP", "characters", "and", "ranges" ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/unicode-base.js#L50-L77
22,005
nol13/fuzzball.js
lib/xregexp/unicode-base.js
cacheInvertedBmp
function cacheInvertedBmp(slug) { var prop = 'b!'; return ( unicode[slug][prop] || (unicode[slug][prop] = invertBmp(unicode[slug].bmp)) ); }
javascript
function cacheInvertedBmp(slug) { var prop = 'b!'; return ( unicode[slug][prop] || (unicode[slug][prop] = invertBmp(unicode[slug].bmp)) ); }
[ "function", "cacheInvertedBmp", "(", "slug", ")", "{", "var", "prop", "=", "'b!'", ";", "return", "(", "unicode", "[", "slug", "]", "[", "prop", "]", "||", "(", "unicode", "[", "slug", "]", "[", "prop", "]", "=", "invertBmp", "(", "unicode", "[", "slug", "]", ".", "bmp", ")", ")", ")", ";", "}" ]
Generates an inverted BMP range on first use
[ "Generates", "an", "inverted", "BMP", "range", "on", "first", "use" ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/unicode-base.js#L80-L86
22,006
nol13/fuzzball.js
lib/xregexp/xregexp.js
augment
function augment(regex, captureNames, xSource, xFlags, isInternalOnly) { var p; regex[REGEX_DATA] = { captureNames: captureNames }; if (isInternalOnly) { return regex; } // Can't auto-inherit these since the XRegExp constructor returns a nonprimitive value if (regex.__proto__) { regex.__proto__ = XRegExp.prototype; } else { for (p in XRegExp.prototype) { // An `XRegExp.prototype.hasOwnProperty(p)` check wouldn't be worth it here, since this // is performance sensitive, and enumerable `Object.prototype` or `RegExp.prototype` // extensions exist on `regex.prototype` anyway regex[p] = XRegExp.prototype[p]; } } regex[REGEX_DATA].source = xSource; // Emulate the ES6 `flags` prop by ensuring flags are in alphabetical order regex[REGEX_DATA].flags = xFlags ? xFlags.split('').sort().join('') : xFlags; return regex; }
javascript
function augment(regex, captureNames, xSource, xFlags, isInternalOnly) { var p; regex[REGEX_DATA] = { captureNames: captureNames }; if (isInternalOnly) { return regex; } // Can't auto-inherit these since the XRegExp constructor returns a nonprimitive value if (regex.__proto__) { regex.__proto__ = XRegExp.prototype; } else { for (p in XRegExp.prototype) { // An `XRegExp.prototype.hasOwnProperty(p)` check wouldn't be worth it here, since this // is performance sensitive, and enumerable `Object.prototype` or `RegExp.prototype` // extensions exist on `regex.prototype` anyway regex[p] = XRegExp.prototype[p]; } } regex[REGEX_DATA].source = xSource; // Emulate the ES6 `flags` prop by ensuring flags are in alphabetical order regex[REGEX_DATA].flags = xFlags ? xFlags.split('').sort().join('') : xFlags; return regex; }
[ "function", "augment", "(", "regex", ",", "captureNames", ",", "xSource", ",", "xFlags", ",", "isInternalOnly", ")", "{", "var", "p", ";", "regex", "[", "REGEX_DATA", "]", "=", "{", "captureNames", ":", "captureNames", "}", ";", "if", "(", "isInternalOnly", ")", "{", "return", "regex", ";", "}", "// Can't auto-inherit these since the XRegExp constructor returns a nonprimitive value", "if", "(", "regex", ".", "__proto__", ")", "{", "regex", ".", "__proto__", "=", "XRegExp", ".", "prototype", ";", "}", "else", "{", "for", "(", "p", "in", "XRegExp", ".", "prototype", ")", "{", "// An `XRegExp.prototype.hasOwnProperty(p)` check wouldn't be worth it here, since this", "// is performance sensitive, and enumerable `Object.prototype` or `RegExp.prototype`", "// extensions exist on `regex.prototype` anyway", "regex", "[", "p", "]", "=", "XRegExp", ".", "prototype", "[", "p", "]", ";", "}", "}", "regex", "[", "REGEX_DATA", "]", ".", "source", "=", "xSource", ";", "// Emulate the ES6 `flags` prop by ensuring flags are in alphabetical order", "regex", "[", "REGEX_DATA", "]", ".", "flags", "=", "xFlags", "?", "xFlags", ".", "split", "(", "''", ")", ".", "sort", "(", ")", ".", "join", "(", "''", ")", ":", "xFlags", ";", "return", "regex", ";", "}" ]
Attaches extended data and `XRegExp.prototype` properties to a regex object. @private @param {RegExp} regex Regex to augment. @param {Array} captureNames Array with capture names, or `null`. @param {String} xSource XRegExp pattern used to generate `regex`, or `null` if N/A. @param {String} xFlags XRegExp flags used to generate `regex`, or `null` if N/A. @param {Boolean} [isInternalOnly=false] Whether the regex will be used only for internal operations, and never exposed to users. For internal-only regexes, we can improve perf by skipping some operations like attaching `XRegExp.prototype` properties. @returns {RegExp} Augmented regex.
[ "Attaches", "extended", "data", "and", "XRegExp", ".", "prototype", "properties", "to", "a", "regex", "object", "." ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/xregexp.js#L107-L135
22,007
nol13/fuzzball.js
lib/xregexp/xregexp.js
getNativeFlags
function getNativeFlags(regex) { return hasFlagsProp ? regex.flags : // Explicitly using `RegExp.prototype.toString` (rather than e.g. `String` or concatenation // with an empty string) allows this to continue working predictably when // `XRegExp.proptotype.toString` is overridden nativ.exec.call(/\/([a-z]*)$/i, RegExp.prototype.toString.call(regex))[1]; }
javascript
function getNativeFlags(regex) { return hasFlagsProp ? regex.flags : // Explicitly using `RegExp.prototype.toString` (rather than e.g. `String` or concatenation // with an empty string) allows this to continue working predictably when // `XRegExp.proptotype.toString` is overridden nativ.exec.call(/\/([a-z]*)$/i, RegExp.prototype.toString.call(regex))[1]; }
[ "function", "getNativeFlags", "(", "regex", ")", "{", "return", "hasFlagsProp", "?", "regex", ".", "flags", ":", "// Explicitly using `RegExp.prototype.toString` (rather than e.g. `String` or concatenation", "// with an empty string) allows this to continue working predictably when", "// `XRegExp.proptotype.toString` is overridden", "nativ", ".", "exec", ".", "call", "(", "/", "\\/([a-z]*)$", "/", "i", ",", "RegExp", ".", "prototype", ".", "toString", ".", "call", "(", "regex", ")", ")", "[", "1", "]", ";", "}" ]
Returns native `RegExp` flags used by a regex object. @private @param {RegExp} regex Regex to check. @returns {String} Native flags in use.
[ "Returns", "native", "RegExp", "flags", "used", "by", "a", "regex", "object", "." ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/xregexp.js#L238-L245
22,008
nol13/fuzzball.js
lib/xregexp/xregexp.js
runTokens
function runTokens(pattern, flags, pos, scope, context) { var i = tokens.length, leadChar = pattern.charAt(pos), result = null, match, t; // Run in reverse insertion order while (i--) { t = tokens[i]; if ( (t.leadChar && t.leadChar !== leadChar) || (t.scope !== scope && t.scope !== 'all') || (t.flag && flags.indexOf(t.flag) === -1) ) { continue; } match = XRegExp.exec(pattern, t.regex, pos, 'sticky'); if (match) { result = { matchLength: match[0].length, output: t.handler.call(context, match, scope, flags), reparse: t.reparse }; // Finished with token tests break; } } return result; }
javascript
function runTokens(pattern, flags, pos, scope, context) { var i = tokens.length, leadChar = pattern.charAt(pos), result = null, match, t; // Run in reverse insertion order while (i--) { t = tokens[i]; if ( (t.leadChar && t.leadChar !== leadChar) || (t.scope !== scope && t.scope !== 'all') || (t.flag && flags.indexOf(t.flag) === -1) ) { continue; } match = XRegExp.exec(pattern, t.regex, pos, 'sticky'); if (match) { result = { matchLength: match[0].length, output: t.handler.call(context, match, scope, flags), reparse: t.reparse }; // Finished with token tests break; } } return result; }
[ "function", "runTokens", "(", "pattern", ",", "flags", ",", "pos", ",", "scope", ",", "context", ")", "{", "var", "i", "=", "tokens", ".", "length", ",", "leadChar", "=", "pattern", ".", "charAt", "(", "pos", ")", ",", "result", "=", "null", ",", "match", ",", "t", ";", "// Run in reverse insertion order", "while", "(", "i", "--", ")", "{", "t", "=", "tokens", "[", "i", "]", ";", "if", "(", "(", "t", ".", "leadChar", "&&", "t", ".", "leadChar", "!==", "leadChar", ")", "||", "(", "t", ".", "scope", "!==", "scope", "&&", "t", ".", "scope", "!==", "'all'", ")", "||", "(", "t", ".", "flag", "&&", "flags", ".", "indexOf", "(", "t", ".", "flag", ")", "===", "-", "1", ")", ")", "{", "continue", ";", "}", "match", "=", "XRegExp", ".", "exec", "(", "pattern", ",", "t", ".", "regex", ",", "pos", ",", "'sticky'", ")", ";", "if", "(", "match", ")", "{", "result", "=", "{", "matchLength", ":", "match", "[", "0", "]", ".", "length", ",", "output", ":", "t", ".", "handler", ".", "call", "(", "context", ",", "match", ",", "scope", ",", "flags", ")", ",", "reparse", ":", "t", ".", "reparse", "}", ";", "// Finished with token tests", "break", ";", "}", "}", "return", "result", ";", "}" ]
Runs built-in and custom regex syntax tokens in reverse insertion order at the specified position, until a match is found. @private @param {String} pattern Original pattern from which an XRegExp object is being built. @param {String} flags Flags being used to construct the regex. @param {Number} pos Position to search for tokens within `pattern`. @param {Number} scope Regex scope to apply: 'default' or 'class'. @param {Object} context Context object to use for token handler functions. @returns {Object} Object with properties `matchLength`, `output`, and `reparse`; or `null`.
[ "Runs", "built", "-", "in", "and", "custom", "regex", "syntax", "tokens", "in", "reverse", "insertion", "order", "at", "the", "specified", "position", "until", "a", "match", "is", "found", "." ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/xregexp.js#L422-L453
22,009
nol13/fuzzball.js
lib/xregexp/xregexp.js
setNatives
function setNatives(on) { RegExp.prototype.exec = (on ? fixed : nativ).exec; RegExp.prototype.test = (on ? fixed : nativ).test; String.prototype.match = (on ? fixed : nativ).match; String.prototype.replace = (on ? fixed : nativ).replace; String.prototype.split = (on ? fixed : nativ).split; features.natives = on; }
javascript
function setNatives(on) { RegExp.prototype.exec = (on ? fixed : nativ).exec; RegExp.prototype.test = (on ? fixed : nativ).test; String.prototype.match = (on ? fixed : nativ).match; String.prototype.replace = (on ? fixed : nativ).replace; String.prototype.split = (on ? fixed : nativ).split; features.natives = on; }
[ "function", "setNatives", "(", "on", ")", "{", "RegExp", ".", "prototype", ".", "exec", "=", "(", "on", "?", "fixed", ":", "nativ", ")", ".", "exec", ";", "RegExp", ".", "prototype", ".", "test", "=", "(", "on", "?", "fixed", ":", "nativ", ")", ".", "test", ";", "String", ".", "prototype", ".", "match", "=", "(", "on", "?", "fixed", ":", "nativ", ")", ".", "match", ";", "String", ".", "prototype", ".", "replace", "=", "(", "on", "?", "fixed", ":", "nativ", ")", ".", "replace", ";", "String", ".", "prototype", ".", "split", "=", "(", "on", "?", "fixed", ":", "nativ", ")", ".", "split", ";", "features", ".", "natives", "=", "on", ";", "}" ]
Enables or disables implicit astral mode opt-in. When enabled, flag A is automatically added to all new regexes created by XRegExp. This causes an error to be thrown when creating regexes if the Unicode Base addon is not available, since flag A is registered by that addon. @private @param {Boolean} on `true` to enable; `false` to disable. /* function setAstral(on) { features.astral = on; } Enables or disables native method overrides. @private @param {Boolean} on `true` to enable; `false` to disable.
[ "Enables", "or", "disables", "implicit", "astral", "mode", "opt", "-", "in", ".", "When", "enabled", "flag", "A", "is", "automatically", "added", "to", "all", "new", "regexes", "created", "by", "XRegExp", ".", "This", "causes", "an", "error", "to", "be", "thrown", "when", "creating", "regexes", "if", "the", "Unicode", "Base", "addon", "is", "not", "available", "since", "flag", "A", "is", "registered", "by", "that", "addon", "." ]
740315fd9c531325cccd0b729f379ed7e448766a
https://github.com/nol13/fuzzball.js/blob/740315fd9c531325cccd0b729f379ed7e448766a/lib/xregexp/xregexp.js#L473-L481
22,010
Samsung/jalangi2
src/js/instrument/esnstrument.js
hoistFunctionDeclaration
function hoistFunctionDeclaration(ast, hoisteredFunctions) { var key, child, startIndex = 0; if (ast.body) { var newBody = []; if (ast.body.length > 0) { // do not hoister function declaration before J$.Fe or J$.Se if (ast.body[0].type === 'ExpressionStatement') { if (ast.body[0].expression.type === 'CallExpression') { if (ast.body[0].expression.callee.object && ast.body[0].expression.callee.object.name === 'J$' && ast.body[0].expression.callee.property && (ast.body[0].expression.callee.property.name === 'Se' || ast.body[0]. expression.callee.property.name === 'Fe')) { newBody.push(ast.body[0]); startIndex = 1; } } } } for (var i = startIndex; i < ast.body.length; i++) { if (ast.body[i].type === 'FunctionDeclaration') { newBody.push(ast.body[i]); if (newBody.length !== i + 1) { hoisteredFunctions.push(ast.body[i].id.name); } } } for (var i = startIndex; i < ast.body.length; i++) { if (ast.body[i].type !== 'FunctionDeclaration') { newBody.push(ast.body[i]); } } while (ast.body.length > 0) { ast.body.pop(); } for (var i = 0; i < newBody.length; i++) { ast.body.push(newBody[i]); } } else { //console.log(typeof ast.body); } for (key in ast) { if (ast.hasOwnProperty(key)) { child = ast[key]; if (typeof child === 'object' && child !== null && key !== "scope") { hoistFunctionDeclaration(child, hoisteredFunctions); } } } return ast; }
javascript
function hoistFunctionDeclaration(ast, hoisteredFunctions) { var key, child, startIndex = 0; if (ast.body) { var newBody = []; if (ast.body.length > 0) { // do not hoister function declaration before J$.Fe or J$.Se if (ast.body[0].type === 'ExpressionStatement') { if (ast.body[0].expression.type === 'CallExpression') { if (ast.body[0].expression.callee.object && ast.body[0].expression.callee.object.name === 'J$' && ast.body[0].expression.callee.property && (ast.body[0].expression.callee.property.name === 'Se' || ast.body[0]. expression.callee.property.name === 'Fe')) { newBody.push(ast.body[0]); startIndex = 1; } } } } for (var i = startIndex; i < ast.body.length; i++) { if (ast.body[i].type === 'FunctionDeclaration') { newBody.push(ast.body[i]); if (newBody.length !== i + 1) { hoisteredFunctions.push(ast.body[i].id.name); } } } for (var i = startIndex; i < ast.body.length; i++) { if (ast.body[i].type !== 'FunctionDeclaration') { newBody.push(ast.body[i]); } } while (ast.body.length > 0) { ast.body.pop(); } for (var i = 0; i < newBody.length; i++) { ast.body.push(newBody[i]); } } else { //console.log(typeof ast.body); } for (key in ast) { if (ast.hasOwnProperty(key)) { child = ast[key]; if (typeof child === 'object' && child !== null && key !== "scope") { hoistFunctionDeclaration(child, hoisteredFunctions); } } } return ast; }
[ "function", "hoistFunctionDeclaration", "(", "ast", ",", "hoisteredFunctions", ")", "{", "var", "key", ",", "child", ",", "startIndex", "=", "0", ";", "if", "(", "ast", ".", "body", ")", "{", "var", "newBody", "=", "[", "]", ";", "if", "(", "ast", ".", "body", ".", "length", ">", "0", ")", "{", "// do not hoister function declaration before J$.Fe or J$.Se", "if", "(", "ast", ".", "body", "[", "0", "]", ".", "type", "===", "'ExpressionStatement'", ")", "{", "if", "(", "ast", ".", "body", "[", "0", "]", ".", "expression", ".", "type", "===", "'CallExpression'", ")", "{", "if", "(", "ast", ".", "body", "[", "0", "]", ".", "expression", ".", "callee", ".", "object", "&&", "ast", ".", "body", "[", "0", "]", ".", "expression", ".", "callee", ".", "object", ".", "name", "===", "'J$'", "&&", "ast", ".", "body", "[", "0", "]", ".", "expression", ".", "callee", ".", "property", "&&", "(", "ast", ".", "body", "[", "0", "]", ".", "expression", ".", "callee", ".", "property", ".", "name", "===", "'Se'", "||", "ast", ".", "body", "[", "0", "]", ".", "expression", ".", "callee", ".", "property", ".", "name", "===", "'Fe'", ")", ")", "{", "newBody", ".", "push", "(", "ast", ".", "body", "[", "0", "]", ")", ";", "startIndex", "=", "1", ";", "}", "}", "}", "}", "for", "(", "var", "i", "=", "startIndex", ";", "i", "<", "ast", ".", "body", ".", "length", ";", "i", "++", ")", "{", "if", "(", "ast", ".", "body", "[", "i", "]", ".", "type", "===", "'FunctionDeclaration'", ")", "{", "newBody", ".", "push", "(", "ast", ".", "body", "[", "i", "]", ")", ";", "if", "(", "newBody", ".", "length", "!==", "i", "+", "1", ")", "{", "hoisteredFunctions", ".", "push", "(", "ast", ".", "body", "[", "i", "]", ".", "id", ".", "name", ")", ";", "}", "}", "}", "for", "(", "var", "i", "=", "startIndex", ";", "i", "<", "ast", ".", "body", ".", "length", ";", "i", "++", ")", "{", "if", "(", "ast", ".", "body", "[", "i", "]", ".", "type", "!==", "'FunctionDeclaration'", ")", "{", "newBody", ".", "push", "(", "ast", ".", "body", "[", "i", "]", ")", ";", "}", "}", "while", "(", "ast", ".", "body", ".", "length", ">", "0", ")", "{", "ast", ".", "body", ".", "pop", "(", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "newBody", ".", "length", ";", "i", "++", ")", "{", "ast", ".", "body", ".", "push", "(", "newBody", "[", "i", "]", ")", ";", "}", "}", "else", "{", "//console.log(typeof ast.body);", "}", "for", "(", "key", "in", "ast", ")", "{", "if", "(", "ast", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "child", "=", "ast", "[", "key", "]", ";", "if", "(", "typeof", "child", "===", "'object'", "&&", "child", "!==", "null", "&&", "key", "!==", "\"scope\"", ")", "{", "hoistFunctionDeclaration", "(", "child", ",", "hoisteredFunctions", ")", ";", "}", "}", "}", "return", "ast", ";", "}" ]
START of Liang Gong's AST post-processor
[ "START", "of", "Liang", "Gong", "s", "AST", "post", "-", "processor" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/instrument/esnstrument.js#L1800-L1855
22,011
Samsung/jalangi2
src/js/instrument/esnstrument.js
transformString
function transformString(code, visitorsPost, visitorsPre) { // StatCollector.resumeTimer("parse"); // console.time("parse") // var newAst = esprima.parse(code, {loc:true, range:true}); var newAst = acorn.parse(code, {locations: true, ecmaVersion: 6 }); // console.timeEnd("parse") // StatCollector.suspendTimer("parse"); // StatCollector.resumeTimer("transform"); // console.time("transform") addScopes(newAst); var len = visitorsPost.length; for (var i = 0; i < len; i++) { newAst = astUtil.transformAst(newAst, visitorsPost[i], visitorsPre[i], astUtil.CONTEXT.RHS); } // console.timeEnd("transform") // StatCollector.suspendTimer("transform"); // console.log(JSON.stringify(newAst,null," ")); return newAst; }
javascript
function transformString(code, visitorsPost, visitorsPre) { // StatCollector.resumeTimer("parse"); // console.time("parse") // var newAst = esprima.parse(code, {loc:true, range:true}); var newAst = acorn.parse(code, {locations: true, ecmaVersion: 6 }); // console.timeEnd("parse") // StatCollector.suspendTimer("parse"); // StatCollector.resumeTimer("transform"); // console.time("transform") addScopes(newAst); var len = visitorsPost.length; for (var i = 0; i < len; i++) { newAst = astUtil.transformAst(newAst, visitorsPost[i], visitorsPre[i], astUtil.CONTEXT.RHS); } // console.timeEnd("transform") // StatCollector.suspendTimer("transform"); // console.log(JSON.stringify(newAst,null," ")); return newAst; }
[ "function", "transformString", "(", "code", ",", "visitorsPost", ",", "visitorsPre", ")", "{", "// StatCollector.resumeTimer(\"parse\");", "// console.time(\"parse\")", "// var newAst = esprima.parse(code, {loc:true, range:true});", "var", "newAst", "=", "acorn", ".", "parse", "(", "code", ",", "{", "locations", ":", "true", ",", "ecmaVersion", ":", "6", "}", ")", ";", "// console.timeEnd(\"parse\")", "// StatCollector.suspendTimer(\"parse\");", "// StatCollector.resumeTimer(\"transform\");", "// console.time(\"transform\")", "addScopes", "(", "newAst", ")", ";", "var", "len", "=", "visitorsPost", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "newAst", "=", "astUtil", ".", "transformAst", "(", "newAst", ",", "visitorsPost", "[", "i", "]", ",", "visitorsPre", "[", "i", "]", ",", "astUtil", ".", "CONTEXT", ".", "RHS", ")", ";", "}", "// console.timeEnd(\"transform\")", "// StatCollector.suspendTimer(\"transform\");", "// console.log(JSON.stringify(newAst,null,\" \"));", "return", "newAst", ";", "}" ]
END of Liang Gong's AST post-processor
[ "END", "of", "Liang", "Gong", "s", "AST", "post", "-", "processor" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/instrument/esnstrument.js#L1859-L1877
22,012
Samsung/jalangi2
src/js/instrument/esnstrument.js
instrumentCode
function instrumentCode(options) { var aret, skip = false; var isEval = options.isEval, code = options.code, thisIid = options.thisIid, inlineSource = options.inlineSource, url = options.url; iidSourceInfo = {}; initializeIIDCounters(isEval); instCodeFileName = options.instCodeFileName ? options.instCodeFileName : (options.isDirect?"eval":"evalIndirect"); origCodeFileName = options.origCodeFileName ? options.origCodeFileName : (options.isDirect?"eval":"evalIndirect"); if (sandbox.analysis && sandbox.analysis.instrumentCodePre) { aret = sandbox.analysis.instrumentCodePre(thisIid, code, options.isDirect); if (aret) { code = aret.code; skip = aret.skip; } } if (!skip && typeof code === 'string' && code.indexOf(noInstr) < 0) { try { code = removeShebang(code); iidSourceInfo = {}; var newAst; if (Config.ENABLE_SAMPLING) { newAst = transformString(code, [visitorCloneBodyPre, visitorRRPost, visitorOps, visitorMergeBodyPre], [undefined, visitorRRPre, undefined, undefined]); } else { newAst = transformString(code, [visitorRRPost, visitorOps], [visitorRRPre, undefined]); } // post-process AST to hoist function declarations (required for Firefox) var hoistedFcts = []; newAst = hoistFunctionDeclaration(newAst, hoistedFcts); var newCode = esotope.generate(newAst, {comment: true ,parse: acorn.parse}); code = newCode + "\n" + noInstr + "\n"; } catch(ex) { console.log("Failed to instrument", code); throw ex; } } var tmp = {}; tmp.nBranches = iidSourceInfo.nBranches = (condIid / IID_INC_STEP - 1) * 2; tmp.originalCodeFileName = iidSourceInfo.originalCodeFileName = origCodeFileName; tmp.instrumentedCodeFileName = iidSourceInfo.instrumentedCodeFileName = instCodeFileName; if (url) { tmp.url = iidSourceInfo.url = url; } if (isEval) { tmp.evalSid = iidSourceInfo.evalSid = sandbox.sid; tmp.evalIid = iidSourceInfo.evalIid = thisIid; } if (inlineSource) { tmp.code = iidSourceInfo.code = options.code; } var prepend = JSON.stringify(iidSourceInfo); var instCode; if (options.inlineSourceMap) { instCode = JALANGI_VAR + ".iids = " + prepend + ";\n" + code; } else { instCode = JALANGI_VAR + ".iids = " + JSON.stringify(tmp) + ";\n" + code; } if (isEval && sandbox.analysis && sandbox.analysis.instrumentCode) { aret = sandbox.analysis.instrumentCode(thisIid, instCode, newAst, options.isDirect); if (aret) { instCode = aret.result; } } return {code: instCode, instAST: newAst, sourceMapObject: iidSourceInfo, sourceMapString: prepend}; }
javascript
function instrumentCode(options) { var aret, skip = false; var isEval = options.isEval, code = options.code, thisIid = options.thisIid, inlineSource = options.inlineSource, url = options.url; iidSourceInfo = {}; initializeIIDCounters(isEval); instCodeFileName = options.instCodeFileName ? options.instCodeFileName : (options.isDirect?"eval":"evalIndirect"); origCodeFileName = options.origCodeFileName ? options.origCodeFileName : (options.isDirect?"eval":"evalIndirect"); if (sandbox.analysis && sandbox.analysis.instrumentCodePre) { aret = sandbox.analysis.instrumentCodePre(thisIid, code, options.isDirect); if (aret) { code = aret.code; skip = aret.skip; } } if (!skip && typeof code === 'string' && code.indexOf(noInstr) < 0) { try { code = removeShebang(code); iidSourceInfo = {}; var newAst; if (Config.ENABLE_SAMPLING) { newAst = transformString(code, [visitorCloneBodyPre, visitorRRPost, visitorOps, visitorMergeBodyPre], [undefined, visitorRRPre, undefined, undefined]); } else { newAst = transformString(code, [visitorRRPost, visitorOps], [visitorRRPre, undefined]); } // post-process AST to hoist function declarations (required for Firefox) var hoistedFcts = []; newAst = hoistFunctionDeclaration(newAst, hoistedFcts); var newCode = esotope.generate(newAst, {comment: true ,parse: acorn.parse}); code = newCode + "\n" + noInstr + "\n"; } catch(ex) { console.log("Failed to instrument", code); throw ex; } } var tmp = {}; tmp.nBranches = iidSourceInfo.nBranches = (condIid / IID_INC_STEP - 1) * 2; tmp.originalCodeFileName = iidSourceInfo.originalCodeFileName = origCodeFileName; tmp.instrumentedCodeFileName = iidSourceInfo.instrumentedCodeFileName = instCodeFileName; if (url) { tmp.url = iidSourceInfo.url = url; } if (isEval) { tmp.evalSid = iidSourceInfo.evalSid = sandbox.sid; tmp.evalIid = iidSourceInfo.evalIid = thisIid; } if (inlineSource) { tmp.code = iidSourceInfo.code = options.code; } var prepend = JSON.stringify(iidSourceInfo); var instCode; if (options.inlineSourceMap) { instCode = JALANGI_VAR + ".iids = " + prepend + ";\n" + code; } else { instCode = JALANGI_VAR + ".iids = " + JSON.stringify(tmp) + ";\n" + code; } if (isEval && sandbox.analysis && sandbox.analysis.instrumentCode) { aret = sandbox.analysis.instrumentCode(thisIid, instCode, newAst, options.isDirect); if (aret) { instCode = aret.result; } } return {code: instCode, instAST: newAst, sourceMapObject: iidSourceInfo, sourceMapString: prepend}; }
[ "function", "instrumentCode", "(", "options", ")", "{", "var", "aret", ",", "skip", "=", "false", ";", "var", "isEval", "=", "options", ".", "isEval", ",", "code", "=", "options", ".", "code", ",", "thisIid", "=", "options", ".", "thisIid", ",", "inlineSource", "=", "options", ".", "inlineSource", ",", "url", "=", "options", ".", "url", ";", "iidSourceInfo", "=", "{", "}", ";", "initializeIIDCounters", "(", "isEval", ")", ";", "instCodeFileName", "=", "options", ".", "instCodeFileName", "?", "options", ".", "instCodeFileName", ":", "(", "options", ".", "isDirect", "?", "\"eval\"", ":", "\"evalIndirect\"", ")", ";", "origCodeFileName", "=", "options", ".", "origCodeFileName", "?", "options", ".", "origCodeFileName", ":", "(", "options", ".", "isDirect", "?", "\"eval\"", ":", "\"evalIndirect\"", ")", ";", "if", "(", "sandbox", ".", "analysis", "&&", "sandbox", ".", "analysis", ".", "instrumentCodePre", ")", "{", "aret", "=", "sandbox", ".", "analysis", ".", "instrumentCodePre", "(", "thisIid", ",", "code", ",", "options", ".", "isDirect", ")", ";", "if", "(", "aret", ")", "{", "code", "=", "aret", ".", "code", ";", "skip", "=", "aret", ".", "skip", ";", "}", "}", "if", "(", "!", "skip", "&&", "typeof", "code", "===", "'string'", "&&", "code", ".", "indexOf", "(", "noInstr", ")", "<", "0", ")", "{", "try", "{", "code", "=", "removeShebang", "(", "code", ")", ";", "iidSourceInfo", "=", "{", "}", ";", "var", "newAst", ";", "if", "(", "Config", ".", "ENABLE_SAMPLING", ")", "{", "newAst", "=", "transformString", "(", "code", ",", "[", "visitorCloneBodyPre", ",", "visitorRRPost", ",", "visitorOps", ",", "visitorMergeBodyPre", "]", ",", "[", "undefined", ",", "visitorRRPre", ",", "undefined", ",", "undefined", "]", ")", ";", "}", "else", "{", "newAst", "=", "transformString", "(", "code", ",", "[", "visitorRRPost", ",", "visitorOps", "]", ",", "[", "visitorRRPre", ",", "undefined", "]", ")", ";", "}", "// post-process AST to hoist function declarations (required for Firefox)", "var", "hoistedFcts", "=", "[", "]", ";", "newAst", "=", "hoistFunctionDeclaration", "(", "newAst", ",", "hoistedFcts", ")", ";", "var", "newCode", "=", "esotope", ".", "generate", "(", "newAst", ",", "{", "comment", ":", "true", ",", "parse", ":", "acorn", ".", "parse", "}", ")", ";", "code", "=", "newCode", "+", "\"\\n\"", "+", "noInstr", "+", "\"\\n\"", ";", "}", "catch", "(", "ex", ")", "{", "console", ".", "log", "(", "\"Failed to instrument\"", ",", "code", ")", ";", "throw", "ex", ";", "}", "}", "var", "tmp", "=", "{", "}", ";", "tmp", ".", "nBranches", "=", "iidSourceInfo", ".", "nBranches", "=", "(", "condIid", "/", "IID_INC_STEP", "-", "1", ")", "*", "2", ";", "tmp", ".", "originalCodeFileName", "=", "iidSourceInfo", ".", "originalCodeFileName", "=", "origCodeFileName", ";", "tmp", ".", "instrumentedCodeFileName", "=", "iidSourceInfo", ".", "instrumentedCodeFileName", "=", "instCodeFileName", ";", "if", "(", "url", ")", "{", "tmp", ".", "url", "=", "iidSourceInfo", ".", "url", "=", "url", ";", "}", "if", "(", "isEval", ")", "{", "tmp", ".", "evalSid", "=", "iidSourceInfo", ".", "evalSid", "=", "sandbox", ".", "sid", ";", "tmp", ".", "evalIid", "=", "iidSourceInfo", ".", "evalIid", "=", "thisIid", ";", "}", "if", "(", "inlineSource", ")", "{", "tmp", ".", "code", "=", "iidSourceInfo", ".", "code", "=", "options", ".", "code", ";", "}", "var", "prepend", "=", "JSON", ".", "stringify", "(", "iidSourceInfo", ")", ";", "var", "instCode", ";", "if", "(", "options", ".", "inlineSourceMap", ")", "{", "instCode", "=", "JALANGI_VAR", "+", "\".iids = \"", "+", "prepend", "+", "\";\\n\"", "+", "code", ";", "}", "else", "{", "instCode", "=", "JALANGI_VAR", "+", "\".iids = \"", "+", "JSON", ".", "stringify", "(", "tmp", ")", "+", "\";\\n\"", "+", "code", ";", "}", "if", "(", "isEval", "&&", "sandbox", ".", "analysis", "&&", "sandbox", ".", "analysis", ".", "instrumentCode", ")", "{", "aret", "=", "sandbox", ".", "analysis", ".", "instrumentCode", "(", "thisIid", ",", "instCode", ",", "newAst", ",", "options", ".", "isDirect", ")", ";", "if", "(", "aret", ")", "{", "instCode", "=", "aret", ".", "result", ";", "}", "}", "return", "{", "code", ":", "instCode", ",", "instAST", ":", "newAst", ",", "sourceMapObject", ":", "iidSourceInfo", ",", "sourceMapString", ":", "prepend", "}", ";", "}" ]
Instruments the provided code. @param {{isEval: boolean, code: string, thisIid: int, origCodeFileName: string, instCodeFileName: string, inlineSourceMap: boolean, inlineSource: boolean, url: string, isDirect: boolean }} options @return {{code:string, instAST: object, sourceMapObject: object, sourceMapString: string}}
[ "Instruments", "the", "provided", "code", "." ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/instrument/esnstrument.js#L1916-L1989
22,013
Samsung/jalangi2
src/js/runtime/analysis.js
R
function R(iid, name, val, flags) { var aret; var bFlags = decodeBitPattern(flags, 2); // [isGlobal, isScriptLocal] if (sandbox.analysis && sandbox.analysis.read) { aret = sandbox.analysis.read(iid, name, val, bFlags[0], bFlags[1]); if (aret) { val = aret.result; } } return (lastComputedValue = val); }
javascript
function R(iid, name, val, flags) { var aret; var bFlags = decodeBitPattern(flags, 2); // [isGlobal, isScriptLocal] if (sandbox.analysis && sandbox.analysis.read) { aret = sandbox.analysis.read(iid, name, val, bFlags[0], bFlags[1]); if (aret) { val = aret.result; } } return (lastComputedValue = val); }
[ "function", "R", "(", "iid", ",", "name", ",", "val", ",", "flags", ")", "{", "var", "aret", ";", "var", "bFlags", "=", "decodeBitPattern", "(", "flags", ",", "2", ")", ";", "// [isGlobal, isScriptLocal]", "if", "(", "sandbox", ".", "analysis", "&&", "sandbox", ".", "analysis", ".", "read", ")", "{", "aret", "=", "sandbox", ".", "analysis", ".", "read", "(", "iid", ",", "name", ",", "val", ",", "bFlags", "[", "0", "]", ",", "bFlags", "[", "1", "]", ")", ";", "if", "(", "aret", ")", "{", "val", "=", "aret", ".", "result", ";", "}", "}", "return", "(", "lastComputedValue", "=", "val", ")", ";", "}" ]
variable write isGlobal means that the variable is global and not declared as var isScriptLocal means that the variable is global and is declared as var
[ "variable", "write", "isGlobal", "means", "that", "the", "variable", "is", "global", "and", "not", "declared", "as", "var", "isScriptLocal", "means", "that", "the", "variable", "is", "global", "and", "is", "declared", "as", "var" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/runtime/analysis.js#L372-L383
22,014
Samsung/jalangi2
src/js/runtime/analysis.js
A
function A(iid, base, offset, op, flags) { var bFlags = decodeBitPattern(flags, 1); // [isComputed] // avoid iid collision: make sure that iid+2 has the same source map as iid (@todo) var oprnd1 = G(iid+2, base, offset, createBitPattern(bFlags[0], true, false)); return function (oprnd2) { // still possible to get iid collision with a mem operation var val = B(iid, op, oprnd1, oprnd2, createBitPattern(false, true, false)); return P(iid, base, offset, val, createBitPattern(bFlags[0], true)); }; }
javascript
function A(iid, base, offset, op, flags) { var bFlags = decodeBitPattern(flags, 1); // [isComputed] // avoid iid collision: make sure that iid+2 has the same source map as iid (@todo) var oprnd1 = G(iid+2, base, offset, createBitPattern(bFlags[0], true, false)); return function (oprnd2) { // still possible to get iid collision with a mem operation var val = B(iid, op, oprnd1, oprnd2, createBitPattern(false, true, false)); return P(iid, base, offset, val, createBitPattern(bFlags[0], true)); }; }
[ "function", "A", "(", "iid", ",", "base", ",", "offset", ",", "op", ",", "flags", ")", "{", "var", "bFlags", "=", "decodeBitPattern", "(", "flags", ",", "1", ")", ";", "// [isComputed]", "// avoid iid collision: make sure that iid+2 has the same source map as iid (@todo)", "var", "oprnd1", "=", "G", "(", "iid", "+", "2", ",", "base", ",", "offset", ",", "createBitPattern", "(", "bFlags", "[", "0", "]", ",", "true", ",", "false", ")", ")", ";", "return", "function", "(", "oprnd2", ")", "{", "// still possible to get iid collision with a mem operation", "var", "val", "=", "B", "(", "iid", ",", "op", ",", "oprnd1", ",", "oprnd2", ",", "createBitPattern", "(", "false", ",", "true", ",", "false", ")", ")", ";", "return", "P", "(", "iid", ",", "base", ",", "offset", ",", "val", ",", "createBitPattern", "(", "bFlags", "[", "0", "]", ",", "true", ")", ")", ";", "}", ";", "}" ]
Modify and assign +=, -= ...
[ "Modify", "and", "assign", "+", "=", "-", "=", "..." ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/runtime/analysis.js#L522-L531
22,015
Samsung/jalangi2
src/js/runtime/analysis.js
C2
function C2(iid, right) { var aret, result; // avoid iid collision; iid may not have a map in the sourcemap result = B(iid+1, "===", switchLeft, right, createBitPattern(false, false, true)); if (sandbox.analysis && sandbox.analysis.conditional) { aret = sandbox.analysis.conditional(iid, result); if (aret) { if (result && !aret.result) { right = !right; } else if (result && aret.result) { right = switchLeft; } } } return (lastComputedValue = right); }
javascript
function C2(iid, right) { var aret, result; // avoid iid collision; iid may not have a map in the sourcemap result = B(iid+1, "===", switchLeft, right, createBitPattern(false, false, true)); if (sandbox.analysis && sandbox.analysis.conditional) { aret = sandbox.analysis.conditional(iid, result); if (aret) { if (result && !aret.result) { right = !right; } else if (result && aret.result) { right = switchLeft; } } } return (lastComputedValue = right); }
[ "function", "C2", "(", "iid", ",", "right", ")", "{", "var", "aret", ",", "result", ";", "// avoid iid collision; iid may not have a map in the sourcemap", "result", "=", "B", "(", "iid", "+", "1", ",", "\"===\"", ",", "switchLeft", ",", "right", ",", "createBitPattern", "(", "false", ",", "false", ",", "true", ")", ")", ";", "if", "(", "sandbox", ".", "analysis", "&&", "sandbox", ".", "analysis", ".", "conditional", ")", "{", "aret", "=", "sandbox", ".", "analysis", ".", "conditional", "(", "iid", ",", "result", ")", ";", "if", "(", "aret", ")", "{", "if", "(", "result", "&&", "!", "aret", ".", "result", ")", "{", "right", "=", "!", "right", ";", "}", "else", "if", "(", "result", "&&", "aret", ".", "result", ")", "{", "right", "=", "switchLeft", ";", "}", "}", "}", "return", "(", "lastComputedValue", "=", "right", ")", ";", "}" ]
case label inside switch
[ "case", "label", "inside", "switch" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/runtime/analysis.js#L702-L719
22,016
Samsung/jalangi2
src/js/runtime/analysis.js
C
function C(iid, left) { var aret; if (sandbox.analysis && sandbox.analysis.conditional) { aret = sandbox.analysis.conditional(iid, left); if (aret) { left = aret.result; } } lastVal = left; return (lastComputedValue = left); }
javascript
function C(iid, left) { var aret; if (sandbox.analysis && sandbox.analysis.conditional) { aret = sandbox.analysis.conditional(iid, left); if (aret) { left = aret.result; } } lastVal = left; return (lastComputedValue = left); }
[ "function", "C", "(", "iid", ",", "left", ")", "{", "var", "aret", ";", "if", "(", "sandbox", ".", "analysis", "&&", "sandbox", ".", "analysis", ".", "conditional", ")", "{", "aret", "=", "sandbox", ".", "analysis", ".", "conditional", "(", "iid", ",", "left", ")", ";", "if", "(", "aret", ")", "{", "left", "=", "aret", ".", "result", ";", "}", "}", "lastVal", "=", "left", ";", "return", "(", "lastComputedValue", "=", "left", ")", ";", "}" ]
Expression in conditional
[ "Expression", "in", "conditional" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/runtime/analysis.js#L722-L733
22,017
Samsung/jalangi2
src/js/commands/instrument.js
accumulateData
function accumulateData(chunk, enc, cb) { this.data = this.data == null ? chunk : Buffer.concat([this.data,chunk]);; cb(); }
javascript
function accumulateData(chunk, enc, cb) { this.data = this.data == null ? chunk : Buffer.concat([this.data,chunk]);; cb(); }
[ "function", "accumulateData", "(", "chunk", ",", "enc", ",", "cb", ")", "{", "this", ".", "data", "=", "this", ".", "data", "==", "null", "?", "chunk", ":", "Buffer", ".", "concat", "(", "[", "this", ".", "data", ",", "chunk", "]", ")", ";", ";", "cb", "(", ")", ";", "}" ]
shared between HTMLRewriteStream and InstrumentJSStream
[ "shared", "between", "HTMLRewriteStream", "and", "InstrumentJSStream" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/commands/instrument.js#L154-L157
22,018
Samsung/jalangi2
src/js/commands/instrument.js
includedFile
function includedFile(fileName) { var relativePath = fileName.substring(appDir.length + 1); var result = false; for (var i = 0; i < onlyIncludeList.length; i++) { var prefix = onlyIncludeList[i]; if (relativePath.indexOf(prefix) === 0) { result = true; break; } } return result; }
javascript
function includedFile(fileName) { var relativePath = fileName.substring(appDir.length + 1); var result = false; for (var i = 0; i < onlyIncludeList.length; i++) { var prefix = onlyIncludeList[i]; if (relativePath.indexOf(prefix) === 0) { result = true; break; } } return result; }
[ "function", "includedFile", "(", "fileName", ")", "{", "var", "relativePath", "=", "fileName", ".", "substring", "(", "appDir", ".", "length", "+", "1", ")", ";", "var", "result", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "onlyIncludeList", ".", "length", ";", "i", "++", ")", "{", "var", "prefix", "=", "onlyIncludeList", "[", "i", "]", ";", "if", "(", "relativePath", ".", "indexOf", "(", "prefix", ")", "===", "0", ")", "{", "result", "=", "true", ";", "break", ";", "}", "}", "return", "result", ";", "}" ]
determine if a file is in the include list @param fileName @returns {boolean}
[ "determine", "if", "a", "file", "is", "in", "the", "include", "list" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/commands/instrument.js#L324-L335
22,019
Samsung/jalangi2
src/js/commands/instrument.js
function () { var outputDir = path.join(copyDir, jalangiRuntimeDir); mkdirp.sync(outputDir); var copyFile = function (srcFile) { if (jalangiRoot) { srcFile = path.join(jalangiRoot, srcFile); } var outputFile = path.join(outputDir, path.basename(srcFile)); fs.writeFileSync(outputFile, String(fs.readFileSync(srcFile))); }; instUtil.headerSources.forEach(copyFile); if (analyses) { analyses.forEach(function (f) { var outputFile = path.join(outputDir, path.basename(f)); fs.writeFileSync(outputFile, String(fs.readFileSync(f))); }); } }
javascript
function () { var outputDir = path.join(copyDir, jalangiRuntimeDir); mkdirp.sync(outputDir); var copyFile = function (srcFile) { if (jalangiRoot) { srcFile = path.join(jalangiRoot, srcFile); } var outputFile = path.join(outputDir, path.basename(srcFile)); fs.writeFileSync(outputFile, String(fs.readFileSync(srcFile))); }; instUtil.headerSources.forEach(copyFile); if (analyses) { analyses.forEach(function (f) { var outputFile = path.join(outputDir, path.basename(f)); fs.writeFileSync(outputFile, String(fs.readFileSync(f))); }); } }
[ "function", "(", ")", "{", "var", "outputDir", "=", "path", ".", "join", "(", "copyDir", ",", "jalangiRuntimeDir", ")", ";", "mkdirp", ".", "sync", "(", "outputDir", ")", ";", "var", "copyFile", "=", "function", "(", "srcFile", ")", "{", "if", "(", "jalangiRoot", ")", "{", "srcFile", "=", "path", ".", "join", "(", "jalangiRoot", ",", "srcFile", ")", ";", "}", "var", "outputFile", "=", "path", ".", "join", "(", "outputDir", ",", "path", ".", "basename", "(", "srcFile", ")", ")", ";", "fs", ".", "writeFileSync", "(", "outputFile", ",", "String", "(", "fs", ".", "readFileSync", "(", "srcFile", ")", ")", ")", ";", "}", ";", "instUtil", ".", "headerSources", ".", "forEach", "(", "copyFile", ")", ";", "if", "(", "analyses", ")", "{", "analyses", ".", "forEach", "(", "function", "(", "f", ")", "{", "var", "outputFile", "=", "path", ".", "join", "(", "outputDir", ",", "path", ".", "basename", "(", "f", ")", ")", ";", "fs", ".", "writeFileSync", "(", "outputFile", ",", "String", "(", "fs", ".", "readFileSync", "(", "f", ")", ")", ")", ";", "}", ")", ";", "}", "}" ]
copy the Jalangi runtime files into the directory with instrumented code, so they can be loaded with relative paths
[ "copy", "the", "Jalangi", "runtime", "files", "into", "the", "directory", "with", "instrumented", "code", "so", "they", "can", "be", "loaded", "with", "relative", "paths" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/commands/instrument.js#L369-L386
22,020
Samsung/jalangi2
src/js/utils/api.js
setupConfig
function setupConfig(instHandler) { var conf = J$.Config; conf.INSTR_READ = instHandler.instrRead; conf.INSTR_WRITE = instHandler.instrWrite; conf.INSTR_GETFIELD = instHandler.instrGetfield; conf.INSTR_PUTFIELD = instHandler.instrPutfield; conf.INSTR_BINARY = instHandler.instrBinary; conf.INSTR_PROPERTY_BINARY_ASSIGNMENT = instHandler.instrPropBinaryAssignment; conf.INSTR_UNARY = instHandler.instrUnary; conf.INSTR_LITERAL = instHandler.instrLiteral; conf.INSTR_CONDITIONAL = instHandler.instrConditional; }
javascript
function setupConfig(instHandler) { var conf = J$.Config; conf.INSTR_READ = instHandler.instrRead; conf.INSTR_WRITE = instHandler.instrWrite; conf.INSTR_GETFIELD = instHandler.instrGetfield; conf.INSTR_PUTFIELD = instHandler.instrPutfield; conf.INSTR_BINARY = instHandler.instrBinary; conf.INSTR_PROPERTY_BINARY_ASSIGNMENT = instHandler.instrPropBinaryAssignment; conf.INSTR_UNARY = instHandler.instrUnary; conf.INSTR_LITERAL = instHandler.instrLiteral; conf.INSTR_CONDITIONAL = instHandler.instrConditional; }
[ "function", "setupConfig", "(", "instHandler", ")", "{", "var", "conf", "=", "J$", ".", "Config", ";", "conf", ".", "INSTR_READ", "=", "instHandler", ".", "instrRead", ";", "conf", ".", "INSTR_WRITE", "=", "instHandler", ".", "instrWrite", ";", "conf", ".", "INSTR_GETFIELD", "=", "instHandler", ".", "instrGetfield", ";", "conf", ".", "INSTR_PUTFIELD", "=", "instHandler", ".", "instrPutfield", ";", "conf", ".", "INSTR_BINARY", "=", "instHandler", ".", "instrBinary", ";", "conf", ".", "INSTR_PROPERTY_BINARY_ASSIGNMENT", "=", "instHandler", ".", "instrPropBinaryAssignment", ";", "conf", ".", "INSTR_UNARY", "=", "instHandler", ".", "instrUnary", ";", "conf", ".", "INSTR_LITERAL", "=", "instHandler", ".", "instrLiteral", ";", "conf", ".", "INSTR_CONDITIONAL", "=", "instHandler", ".", "instrConditional", ";", "}" ]
setup the global Config object based on the given instrumentation handler object @param instHandler
[ "setup", "the", "global", "Config", "object", "based", "on", "the", "given", "instrumentation", "handler", "object" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/utils/api.js#L49-L60
22,021
Samsung/jalangi2
src/js/utils/api.js
clearConfig
function clearConfig() { var conf = J$.Config; conf.INSTR_READ = null; conf.INSTR_WRITE = null; conf.INSTR_GETFIELD = null; conf.INSTR_PUTFIELD = null; conf.INSTR_BINARY = null; conf.INSTR_PROPERTY_BINARY_ASSIGNMENT = null; conf.INSTR_UNARY = null; conf.INSTR_LITERAL = null; conf.INSTR_CONDITIONAL = null; }
javascript
function clearConfig() { var conf = J$.Config; conf.INSTR_READ = null; conf.INSTR_WRITE = null; conf.INSTR_GETFIELD = null; conf.INSTR_PUTFIELD = null; conf.INSTR_BINARY = null; conf.INSTR_PROPERTY_BINARY_ASSIGNMENT = null; conf.INSTR_UNARY = null; conf.INSTR_LITERAL = null; conf.INSTR_CONDITIONAL = null; }
[ "function", "clearConfig", "(", ")", "{", "var", "conf", "=", "J$", ".", "Config", ";", "conf", ".", "INSTR_READ", "=", "null", ";", "conf", ".", "INSTR_WRITE", "=", "null", ";", "conf", ".", "INSTR_GETFIELD", "=", "null", ";", "conf", ".", "INSTR_PUTFIELD", "=", "null", ";", "conf", ".", "INSTR_BINARY", "=", "null", ";", "conf", ".", "INSTR_PROPERTY_BINARY_ASSIGNMENT", "=", "null", ";", "conf", ".", "INSTR_UNARY", "=", "null", ";", "conf", ".", "INSTR_LITERAL", "=", "null", ";", "conf", ".", "INSTR_CONDITIONAL", "=", "null", ";", "}" ]
clear any configured instrumentation control functions from the global Config object
[ "clear", "any", "configured", "instrumentation", "control", "functions", "from", "the", "global", "Config", "object" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/utils/api.js#L65-L76
22,022
Samsung/jalangi2
src/js/utils/api.js
runChildAndCaptureOutput
function runChildAndCaptureOutput(forkedProcess) { var stdout_parts = [], stdoutLength = 0, stderr_parts = [], stderrLength = 0, deferred = Q.defer(); forkedProcess.stdout.on('data', function (data) { stdout_parts.push(data); stdoutLength += data.length; }); forkedProcess.stderr.on('data', function (data) { stderr_parts.push(data); stderrLength += data.length; }); forkedProcess.on('close', function (code) { var child_stdout = convertToString(stdout_parts, stdoutLength), child_stderr = convertToString(stderr_parts, stderrLength); var resultVal = { exitCode: code, stdout: child_stdout, stderr: child_stderr, toString: function () { return child_stderr; } }; if (code !== 0) { deferred.reject(resultVal); } else { deferred.resolve(resultVal); } }); return deferred.promise; }
javascript
function runChildAndCaptureOutput(forkedProcess) { var stdout_parts = [], stdoutLength = 0, stderr_parts = [], stderrLength = 0, deferred = Q.defer(); forkedProcess.stdout.on('data', function (data) { stdout_parts.push(data); stdoutLength += data.length; }); forkedProcess.stderr.on('data', function (data) { stderr_parts.push(data); stderrLength += data.length; }); forkedProcess.on('close', function (code) { var child_stdout = convertToString(stdout_parts, stdoutLength), child_stderr = convertToString(stderr_parts, stderrLength); var resultVal = { exitCode: code, stdout: child_stdout, stderr: child_stderr, toString: function () { return child_stderr; } }; if (code !== 0) { deferred.reject(resultVal); } else { deferred.resolve(resultVal); } }); return deferred.promise; }
[ "function", "runChildAndCaptureOutput", "(", "forkedProcess", ")", "{", "var", "stdout_parts", "=", "[", "]", ",", "stdoutLength", "=", "0", ",", "stderr_parts", "=", "[", "]", ",", "stderrLength", "=", "0", ",", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "forkedProcess", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "stdout_parts", ".", "push", "(", "data", ")", ";", "stdoutLength", "+=", "data", ".", "length", ";", "}", ")", ";", "forkedProcess", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "stderr_parts", ".", "push", "(", "data", ")", ";", "stderrLength", "+=", "data", ".", "length", ";", "}", ")", ";", "forkedProcess", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "var", "child_stdout", "=", "convertToString", "(", "stdout_parts", ",", "stdoutLength", ")", ",", "child_stderr", "=", "convertToString", "(", "stderr_parts", ",", "stderrLength", ")", ";", "var", "resultVal", "=", "{", "exitCode", ":", "code", ",", "stdout", ":", "child_stdout", ",", "stderr", ":", "child_stderr", ",", "toString", ":", "function", "(", ")", "{", "return", "child_stderr", ";", "}", "}", ";", "if", "(", "code", "!==", "0", ")", "{", "deferred", ".", "reject", "(", "resultVal", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "resultVal", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Runs a process created via the node child_process API and captures its output. @param forkedProcess the process @returns {promise|Q.promise} A promise that, when process execution completes normally, is resolved with an object with the following properties: 'stdout': the stdout output of the process 'stderr': the stderr output of the process If process completes abnormally (with non-zero exit code), the promise is rejected with a value similar to above, except that 'exitCode' holds the exit code.
[ "Runs", "a", "process", "created", "via", "the", "node", "child_process", "API", "and", "captures", "its", "output", "." ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/utils/api.js#L180-L210
22,023
Samsung/jalangi2
src/js/utils/api.js
analyze
function analyze(script, clientAnalyses, initParam) { var directJSScript = path.resolve(__dirname, "../commands/direct.js"); var cliArgs = []; if (!script) { throw new Error("must provide a script to analyze"); } if (!clientAnalyses) { throw new Error("must provide an analysis to run"); } clientAnalyses.forEach(function (analysis) { cliArgs.push('--analysis'); cliArgs.push(analysis); }); if (initParam) { Object.keys(initParam).forEach(function (k) { cliArgs.push('--initParam') cliArgs.push(k + ':' + initParam[k]); }); } cliArgs.push(script); var proc = cp.fork(directJSScript, cliArgs, { silent: true }); return runChildAndCaptureOutput(proc); }
javascript
function analyze(script, clientAnalyses, initParam) { var directJSScript = path.resolve(__dirname, "../commands/direct.js"); var cliArgs = []; if (!script) { throw new Error("must provide a script to analyze"); } if (!clientAnalyses) { throw new Error("must provide an analysis to run"); } clientAnalyses.forEach(function (analysis) { cliArgs.push('--analysis'); cliArgs.push(analysis); }); if (initParam) { Object.keys(initParam).forEach(function (k) { cliArgs.push('--initParam') cliArgs.push(k + ':' + initParam[k]); }); } cliArgs.push(script); var proc = cp.fork(directJSScript, cliArgs, { silent: true }); return runChildAndCaptureOutput(proc); }
[ "function", "analyze", "(", "script", ",", "clientAnalyses", ",", "initParam", ")", "{", "var", "directJSScript", "=", "path", ".", "resolve", "(", "__dirname", ",", "\"../commands/direct.js\"", ")", ";", "var", "cliArgs", "=", "[", "]", ";", "if", "(", "!", "script", ")", "{", "throw", "new", "Error", "(", "\"must provide a script to analyze\"", ")", ";", "}", "if", "(", "!", "clientAnalyses", ")", "{", "throw", "new", "Error", "(", "\"must provide an analysis to run\"", ")", ";", "}", "clientAnalyses", ".", "forEach", "(", "function", "(", "analysis", ")", "{", "cliArgs", ".", "push", "(", "'--analysis'", ")", ";", "cliArgs", ".", "push", "(", "analysis", ")", ";", "}", ")", ";", "if", "(", "initParam", ")", "{", "Object", ".", "keys", "(", "initParam", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "cliArgs", ".", "push", "(", "'--initParam'", ")", "cliArgs", ".", "push", "(", "k", "+", "':'", "+", "initParam", "[", "k", "]", ")", ";", "}", ")", ";", "}", "cliArgs", ".", "push", "(", "script", ")", ";", "var", "proc", "=", "cp", ".", "fork", "(", "directJSScript", ",", "cliArgs", ",", "{", "silent", ":", "true", "}", ")", ";", "return", "runChildAndCaptureOutput", "(", "proc", ")", ";", "}" ]
direct analysis of an instrumented file using analysis2 engine @param {string} script the instrumented script to analyze @param {string[]} clientAnalyses the analyses to run @param {object} [initParam] parameter to pass to client init() function @return promise|Q.promise promise that gets resolved at the end of analysis. The promise is resolved with an object with properties: 'exitCode': the exit code from the process doing replay 'stdout': the stdout of the replay process 'stderr': the stderr of the replay process 'result': the result returned by the analysis, if any
[ "direct", "analysis", "of", "an", "instrumented", "file", "using", "analysis2", "engine" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/utils/api.js#L224-L246
22,024
Samsung/jalangi2
src/js/sample_analyses/datatraces/TraceWriter.js
tryRemoteLog2
function tryRemoteLog2() { trying = false; remoteBuffer.shift(); if (remoteBuffer.length === 0) { if (cb) { cb(); cb = undefined; } } tryRemoteLog(); }
javascript
function tryRemoteLog2() { trying = false; remoteBuffer.shift(); if (remoteBuffer.length === 0) { if (cb) { cb(); cb = undefined; } } tryRemoteLog(); }
[ "function", "tryRemoteLog2", "(", ")", "{", "trying", "=", "false", ";", "remoteBuffer", ".", "shift", "(", ")", ";", "if", "(", "remoteBuffer", ".", "length", "===", "0", ")", "{", "if", "(", "cb", ")", "{", "cb", "(", ")", ";", "cb", "=", "undefined", ";", "}", "}", "tryRemoteLog", "(", ")", ";", "}" ]
invoked when we receive a message over the websocket, indicating that the last trace chunk in the remoteBuffer has been received
[ "invoked", "when", "we", "receive", "a", "message", "over", "the", "websocket", "indicating", "that", "the", "last", "trace", "chunk", "in", "the", "remoteBuffer", "has", "been", "received" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/sample_analyses/datatraces/TraceWriter.js#L84-L94
22,025
Samsung/jalangi2
src/js/instrument/astUtil.js
serialize
function serialize(root) { // Stores a pointer to the most-recently encountered node representing a function or a // top-level script. We need this stored pointer since a function expression or declaration // has no associated IID, but we'd like to have the ASTs as entries in the table. Instead, // we associate the AST with the IID for the corresponding function-enter or script-enter IID. // We don't need a stack here since we only use this pointer at the next function-enter or script-enter, // and there cannot be a nested function declaration in-between. var parentFunOrScript = root; var iidToAstTable = {}; function handleFun(node) { parentFunOrScript = node; } var visitorPre = { 'Program':handleFun, 'FunctionDeclaration':handleFun, 'FunctionExpression':handleFun }; function canMakeSymbolic(node) { if (node.callee.object) { var callee = node.callee; // we can replace calls to J$ functions with a SymbolicReference iff they have an IID as their first // argument. 'instrumentCode', 'getConcrete', and 'I' do not take an IID. // TODO are we missing other cases? if (callee.object.name === 'J$' && callee.property.name !== "instrumentCode" && callee.property.name !== "getConcrete" && callee.property.name !== "I" && node.arguments[0]) { return true; } } return false; } function setSerializedAST(iid, ast) { var entry = iidToAstTable[iid]; if (!entry) { entry = {}; iidToAstTable[iid] = entry; } entry.serializedAST = ast; } var visitorPost = { 'CallExpression':function (node) { try { if (node.callee.object && node.callee.object.name === 'J$' && (node.callee.property.name === 'Se' || node.callee.property.name === 'Fe')) { // associate IID with the AST of the containing function / script setSerializedAST(node.arguments[0].value, parentFunOrScript); return node; } else if (canMakeSymbolic(node)) { setSerializedAST(node.arguments[0].value, node); return {type:"SymbolicReference", value:node.arguments[0].value}; } return node; } catch (e) { console.log(JSON.stringify(node)); throw e; } } }; transformAst(root, visitorPost, visitorPre); return iidToAstTable; }
javascript
function serialize(root) { // Stores a pointer to the most-recently encountered node representing a function or a // top-level script. We need this stored pointer since a function expression or declaration // has no associated IID, but we'd like to have the ASTs as entries in the table. Instead, // we associate the AST with the IID for the corresponding function-enter or script-enter IID. // We don't need a stack here since we only use this pointer at the next function-enter or script-enter, // and there cannot be a nested function declaration in-between. var parentFunOrScript = root; var iidToAstTable = {}; function handleFun(node) { parentFunOrScript = node; } var visitorPre = { 'Program':handleFun, 'FunctionDeclaration':handleFun, 'FunctionExpression':handleFun }; function canMakeSymbolic(node) { if (node.callee.object) { var callee = node.callee; // we can replace calls to J$ functions with a SymbolicReference iff they have an IID as their first // argument. 'instrumentCode', 'getConcrete', and 'I' do not take an IID. // TODO are we missing other cases? if (callee.object.name === 'J$' && callee.property.name !== "instrumentCode" && callee.property.name !== "getConcrete" && callee.property.name !== "I" && node.arguments[0]) { return true; } } return false; } function setSerializedAST(iid, ast) { var entry = iidToAstTable[iid]; if (!entry) { entry = {}; iidToAstTable[iid] = entry; } entry.serializedAST = ast; } var visitorPost = { 'CallExpression':function (node) { try { if (node.callee.object && node.callee.object.name === 'J$' && (node.callee.property.name === 'Se' || node.callee.property.name === 'Fe')) { // associate IID with the AST of the containing function / script setSerializedAST(node.arguments[0].value, parentFunOrScript); return node; } else if (canMakeSymbolic(node)) { setSerializedAST(node.arguments[0].value, node); return {type:"SymbolicReference", value:node.arguments[0].value}; } return node; } catch (e) { console.log(JSON.stringify(node)); throw e; } } }; transformAst(root, visitorPost, visitorPre); return iidToAstTable; }
[ "function", "serialize", "(", "root", ")", "{", "// Stores a pointer to the most-recently encountered node representing a function or a", "// top-level script. We need this stored pointer since a function expression or declaration", "// has no associated IID, but we'd like to have the ASTs as entries in the table. Instead,", "// we associate the AST with the IID for the corresponding function-enter or script-enter IID.", "// We don't need a stack here since we only use this pointer at the next function-enter or script-enter,", "// and there cannot be a nested function declaration in-between.", "var", "parentFunOrScript", "=", "root", ";", "var", "iidToAstTable", "=", "{", "}", ";", "function", "handleFun", "(", "node", ")", "{", "parentFunOrScript", "=", "node", ";", "}", "var", "visitorPre", "=", "{", "'Program'", ":", "handleFun", ",", "'FunctionDeclaration'", ":", "handleFun", ",", "'FunctionExpression'", ":", "handleFun", "}", ";", "function", "canMakeSymbolic", "(", "node", ")", "{", "if", "(", "node", ".", "callee", ".", "object", ")", "{", "var", "callee", "=", "node", ".", "callee", ";", "// we can replace calls to J$ functions with a SymbolicReference iff they have an IID as their first", "// argument. 'instrumentCode', 'getConcrete', and 'I' do not take an IID.", "// TODO are we missing other cases?", "if", "(", "callee", ".", "object", ".", "name", "===", "'J$'", "&&", "callee", ".", "property", ".", "name", "!==", "\"instrumentCode\"", "&&", "callee", ".", "property", ".", "name", "!==", "\"getConcrete\"", "&&", "callee", ".", "property", ".", "name", "!==", "\"I\"", "&&", "node", ".", "arguments", "[", "0", "]", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "function", "setSerializedAST", "(", "iid", ",", "ast", ")", "{", "var", "entry", "=", "iidToAstTable", "[", "iid", "]", ";", "if", "(", "!", "entry", ")", "{", "entry", "=", "{", "}", ";", "iidToAstTable", "[", "iid", "]", "=", "entry", ";", "}", "entry", ".", "serializedAST", "=", "ast", ";", "}", "var", "visitorPost", "=", "{", "'CallExpression'", ":", "function", "(", "node", ")", "{", "try", "{", "if", "(", "node", ".", "callee", ".", "object", "&&", "node", ".", "callee", ".", "object", ".", "name", "===", "'J$'", "&&", "(", "node", ".", "callee", ".", "property", ".", "name", "===", "'Se'", "||", "node", ".", "callee", ".", "property", ".", "name", "===", "'Fe'", ")", ")", "{", "// associate IID with the AST of the containing function / script", "setSerializedAST", "(", "node", ".", "arguments", "[", "0", "]", ".", "value", ",", "parentFunOrScript", ")", ";", "return", "node", ";", "}", "else", "if", "(", "canMakeSymbolic", "(", "node", ")", ")", "{", "setSerializedAST", "(", "node", ".", "arguments", "[", "0", "]", ".", "value", ",", "node", ")", ";", "return", "{", "type", ":", "\"SymbolicReference\"", ",", "value", ":", "node", ".", "arguments", "[", "0", "]", ".", "value", "}", ";", "}", "return", "node", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "JSON", ".", "stringify", "(", "node", ")", ")", ";", "throw", "e", ";", "}", "}", "}", ";", "transformAst", "(", "root", ",", "visitorPost", ",", "visitorPre", ")", ";", "return", "iidToAstTable", ";", "}" ]
computes a map from iids to the corresponding AST nodes for root. The root AST is destructively updated to include SymbolicReference nodes that reference other nodes by iid, in order to save space in the map.
[ "computes", "a", "map", "from", "iids", "to", "the", "corresponding", "AST", "nodes", "for", "root", ".", "The", "root", "AST", "is", "destructively", "updated", "to", "include", "SymbolicReference", "nodes", "that", "reference", "other", "nodes", "by", "iid", "in", "order", "to", "save", "space", "in", "the", "map", "." ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/instrument/astUtil.js#L164-L228
22,026
Samsung/jalangi2
src/js/instrument/astUtil.js
computeTopLevelExpressions
function computeTopLevelExpressions(ast) { var exprDepth = 0; var exprDepthStack = []; var topLevelExprs = []; var visitorIdentifyTopLevelExprPre = { "CallExpression":function (node) { if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === JALANGI_VAR) { var funName = node.callee.property.name; if ((exprDepth === 0 && (funName === 'A' || funName === 'P' || funName === 'G' || funName === 'R' || funName === 'W' || funName === 'H' || funName === 'T' || funName === 'Rt' || funName === 'B' || funName === 'U' || funName === 'C' || funName === 'C1' || funName === 'C2' )) || (exprDepth === 1 && (funName === 'F' || funName === 'M'))) { topLevelExprs.push(node.arguments[0].value); } exprDepth++; } else if (node.callee.type === 'CallExpression' && node.callee.callee.type === 'MemberExpression' && node.callee.callee.object.type === 'Identifier' && node.callee.callee.object.name === JALANGI_VAR && (node.callee.callee.property.name === 'F' || node.callee.callee.property.name === 'M')) { exprDepth++; } }, "FunctionExpression":function (node, context) { exprDepthStack.push(exprDepth); exprDepth = 0; }, "FunctionDeclaration":function (node) { exprDepthStack.push(exprDepth); exprDepth = 0; } }; var visitorIdentifyTopLevelExprPost = { "CallExpression":function (node) { if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === JALANGI_VAR) { exprDepth--; } else if (node.callee.type === 'CallExpression' && node.callee.callee.type === 'MemberExpression' && node.callee.callee.object.type === 'Identifier' && node.callee.callee.object.name === JALANGI_VAR && (node.callee.callee.property.name === 'F' || node.callee.callee.property.name === 'M')) { exprDepth--; } return node; }, "FunctionExpression":function (node, context) { exprDepth = exprDepthStack.pop(); return node; }, "FunctionDeclaration":function (node) { exprDepth = exprDepthStack.pop(); return node; } }; transformAst(ast, visitorIdentifyTopLevelExprPost, visitorIdentifyTopLevelExprPre, CONTEXT.RHS); return topLevelExprs; }
javascript
function computeTopLevelExpressions(ast) { var exprDepth = 0; var exprDepthStack = []; var topLevelExprs = []; var visitorIdentifyTopLevelExprPre = { "CallExpression":function (node) { if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === JALANGI_VAR) { var funName = node.callee.property.name; if ((exprDepth === 0 && (funName === 'A' || funName === 'P' || funName === 'G' || funName === 'R' || funName === 'W' || funName === 'H' || funName === 'T' || funName === 'Rt' || funName === 'B' || funName === 'U' || funName === 'C' || funName === 'C1' || funName === 'C2' )) || (exprDepth === 1 && (funName === 'F' || funName === 'M'))) { topLevelExprs.push(node.arguments[0].value); } exprDepth++; } else if (node.callee.type === 'CallExpression' && node.callee.callee.type === 'MemberExpression' && node.callee.callee.object.type === 'Identifier' && node.callee.callee.object.name === JALANGI_VAR && (node.callee.callee.property.name === 'F' || node.callee.callee.property.name === 'M')) { exprDepth++; } }, "FunctionExpression":function (node, context) { exprDepthStack.push(exprDepth); exprDepth = 0; }, "FunctionDeclaration":function (node) { exprDepthStack.push(exprDepth); exprDepth = 0; } }; var visitorIdentifyTopLevelExprPost = { "CallExpression":function (node) { if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === JALANGI_VAR) { exprDepth--; } else if (node.callee.type === 'CallExpression' && node.callee.callee.type === 'MemberExpression' && node.callee.callee.object.type === 'Identifier' && node.callee.callee.object.name === JALANGI_VAR && (node.callee.callee.property.name === 'F' || node.callee.callee.property.name === 'M')) { exprDepth--; } return node; }, "FunctionExpression":function (node, context) { exprDepth = exprDepthStack.pop(); return node; }, "FunctionDeclaration":function (node) { exprDepth = exprDepthStack.pop(); return node; } }; transformAst(ast, visitorIdentifyTopLevelExprPost, visitorIdentifyTopLevelExprPre, CONTEXT.RHS); return topLevelExprs; }
[ "function", "computeTopLevelExpressions", "(", "ast", ")", "{", "var", "exprDepth", "=", "0", ";", "var", "exprDepthStack", "=", "[", "]", ";", "var", "topLevelExprs", "=", "[", "]", ";", "var", "visitorIdentifyTopLevelExprPre", "=", "{", "\"CallExpression\"", ":", "function", "(", "node", ")", "{", "if", "(", "node", ".", "callee", ".", "type", "===", "'MemberExpression'", "&&", "node", ".", "callee", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "callee", ".", "object", ".", "name", "===", "JALANGI_VAR", ")", "{", "var", "funName", "=", "node", ".", "callee", ".", "property", ".", "name", ";", "if", "(", "(", "exprDepth", "===", "0", "&&", "(", "funName", "===", "'A'", "||", "funName", "===", "'P'", "||", "funName", "===", "'G'", "||", "funName", "===", "'R'", "||", "funName", "===", "'W'", "||", "funName", "===", "'H'", "||", "funName", "===", "'T'", "||", "funName", "===", "'Rt'", "||", "funName", "===", "'B'", "||", "funName", "===", "'U'", "||", "funName", "===", "'C'", "||", "funName", "===", "'C1'", "||", "funName", "===", "'C2'", ")", ")", "||", "(", "exprDepth", "===", "1", "&&", "(", "funName", "===", "'F'", "||", "funName", "===", "'M'", ")", ")", ")", "{", "topLevelExprs", ".", "push", "(", "node", ".", "arguments", "[", "0", "]", ".", "value", ")", ";", "}", "exprDepth", "++", ";", "}", "else", "if", "(", "node", ".", "callee", ".", "type", "===", "'CallExpression'", "&&", "node", ".", "callee", ".", "callee", ".", "type", "===", "'MemberExpression'", "&&", "node", ".", "callee", ".", "callee", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "callee", ".", "callee", ".", "object", ".", "name", "===", "JALANGI_VAR", "&&", "(", "node", ".", "callee", ".", "callee", ".", "property", ".", "name", "===", "'F'", "||", "node", ".", "callee", ".", "callee", ".", "property", ".", "name", "===", "'M'", ")", ")", "{", "exprDepth", "++", ";", "}", "}", ",", "\"FunctionExpression\"", ":", "function", "(", "node", ",", "context", ")", "{", "exprDepthStack", ".", "push", "(", "exprDepth", ")", ";", "exprDepth", "=", "0", ";", "}", ",", "\"FunctionDeclaration\"", ":", "function", "(", "node", ")", "{", "exprDepthStack", ".", "push", "(", "exprDepth", ")", ";", "exprDepth", "=", "0", ";", "}", "}", ";", "var", "visitorIdentifyTopLevelExprPost", "=", "{", "\"CallExpression\"", ":", "function", "(", "node", ")", "{", "if", "(", "node", ".", "callee", ".", "type", "===", "'MemberExpression'", "&&", "node", ".", "callee", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "callee", ".", "object", ".", "name", "===", "JALANGI_VAR", ")", "{", "exprDepth", "--", ";", "}", "else", "if", "(", "node", ".", "callee", ".", "type", "===", "'CallExpression'", "&&", "node", ".", "callee", ".", "callee", ".", "type", "===", "'MemberExpression'", "&&", "node", ".", "callee", ".", "callee", ".", "object", ".", "type", "===", "'Identifier'", "&&", "node", ".", "callee", ".", "callee", ".", "object", ".", "name", "===", "JALANGI_VAR", "&&", "(", "node", ".", "callee", ".", "callee", ".", "property", ".", "name", "===", "'F'", "||", "node", ".", "callee", ".", "callee", ".", "property", ".", "name", "===", "'M'", ")", ")", "{", "exprDepth", "--", ";", "}", "return", "node", ";", "}", ",", "\"FunctionExpression\"", ":", "function", "(", "node", ",", "context", ")", "{", "exprDepth", "=", "exprDepthStack", ".", "pop", "(", ")", ";", "return", "node", ";", "}", ",", "\"FunctionDeclaration\"", ":", "function", "(", "node", ")", "{", "exprDepth", "=", "exprDepthStack", ".", "pop", "(", ")", ";", "return", "node", ";", "}", "}", ";", "transformAst", "(", "ast", ",", "visitorIdentifyTopLevelExprPost", ",", "visitorIdentifyTopLevelExprPre", ",", "CONTEXT", ".", "RHS", ")", ";", "return", "topLevelExprs", ";", "}" ]
given an instrumented AST, returns an array of IIDs corresponding to "top-level expressions," i.e., expressions that are not nested within another @param ast
[ "given", "an", "instrumented", "AST", "returns", "an", "array", "of", "IIDs", "corresponding", "to", "top", "-", "level", "expressions", "i", ".", "e", ".", "expressions", "that", "are", "not", "nested", "within", "another" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/instrument/astUtil.js#L258-L336
22,027
Samsung/jalangi2
src/js/instrument/instUtil.js
createFilenameForScript
function createFilenameForScript(url) { // TODO make this much more robust console.log("url:" + url); var parsed = urlParser.parse(url); if (inlineRegexp.test(url)) { return parsed.hash.substring(1) + ".js"; } else { return parsed.pathname.substring(parsed.pathname.lastIndexOf("/") + 1); } }
javascript
function createFilenameForScript(url) { // TODO make this much more robust console.log("url:" + url); var parsed = urlParser.parse(url); if (inlineRegexp.test(url)) { return parsed.hash.substring(1) + ".js"; } else { return parsed.pathname.substring(parsed.pathname.lastIndexOf("/") + 1); } }
[ "function", "createFilenameForScript", "(", "url", ")", "{", "// TODO make this much more robust", "console", ".", "log", "(", "\"url:\"", "+", "url", ")", ";", "var", "parsed", "=", "urlParser", ".", "parse", "(", "url", ")", ";", "if", "(", "inlineRegexp", ".", "test", "(", "url", ")", ")", "{", "return", "parsed", ".", "hash", ".", "substring", "(", "1", ")", "+", "\".js\"", ";", "}", "else", "{", "return", "parsed", ".", "pathname", ".", "substring", "(", "parsed", ".", "pathname", ".", "lastIndexOf", "(", "\"/\"", ")", "+", "1", ")", ";", "}", "}" ]
generate a filename for a script with the given url
[ "generate", "a", "filename", "for", "a", "script", "with", "the", "given", "url" ]
08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110
https://github.com/Samsung/jalangi2/blob/08f6f38abc2f5a09ffa48d173b7f0d92d6d8b110/src/js/instrument/instUtil.js#L188-L197
22,028
Mevrael/bunny
src/bunny.route.js
function(uri) { var original_segments = window.location.pathname.split('/'); var route_segments = uri.split('/'); var route_length = route_segments.length; var params = {}; for (var i = 1; i < route_length; i++) { if (route_segments[i].indexOf('{') !== -1) { var name = route_segments[i].substr(1, route_segments[i].length-2); params[name] = original_segments[i]; } } return params; }
javascript
function(uri) { var original_segments = window.location.pathname.split('/'); var route_segments = uri.split('/'); var route_length = route_segments.length; var params = {}; for (var i = 1; i < route_length; i++) { if (route_segments[i].indexOf('{') !== -1) { var name = route_segments[i].substr(1, route_segments[i].length-2); params[name] = original_segments[i]; } } return params; }
[ "function", "(", "uri", ")", "{", "var", "original_segments", "=", "window", ".", "location", ".", "pathname", ".", "split", "(", "'/'", ")", ";", "var", "route_segments", "=", "uri", ".", "split", "(", "'/'", ")", ";", "var", "route_length", "=", "route_segments", ".", "length", ";", "var", "params", "=", "{", "}", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "route_length", ";", "i", "++", ")", "{", "if", "(", "route_segments", "[", "i", "]", ".", "indexOf", "(", "'{'", ")", "!==", "-", "1", ")", "{", "var", "name", "=", "route_segments", "[", "i", "]", ".", "substr", "(", "1", ",", "route_segments", "[", "i", "]", ".", "length", "-", "2", ")", ";", "params", "[", "name", "]", "=", "original_segments", "[", "i", "]", ";", "}", "}", "return", "params", ";", "}" ]
Get route params @param uri @returns {{}}
[ "Get", "route", "params" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/src/bunny.route.js#L35-L47
22,029
Mevrael/bunny
src/bunny.route.js
function(uri) { if (this._routes[uri] !== undefined) { return uri; } for (var route in this._routes) { if (this.is(route, uri)) { return route; } } return false; }
javascript
function(uri) { if (this._routes[uri] !== undefined) { return uri; } for (var route in this._routes) { if (this.is(route, uri)) { return route; } } return false; }
[ "function", "(", "uri", ")", "{", "if", "(", "this", ".", "_routes", "[", "uri", "]", "!==", "undefined", ")", "{", "return", "uri", ";", "}", "for", "(", "var", "route", "in", "this", ".", "_routes", ")", "{", "if", "(", "this", ".", "is", "(", "route", ",", "uri", ")", ")", "{", "return", "route", ";", "}", "}", "return", "false", ";", "}" ]
Check if route is defined. Returns route if found or false @param uri @returns {*}
[ "Check", "if", "route", "is", "defined", ".", "Returns", "route", "if", "found", "or", "false" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/src/bunny.route.js#L81-L94
22,030
Mevrael/bunny
src/bunny.route.js
function(uri) { if (this.defined(uri)) { history.pushState(null, null, uri); var event = new CustomEvent('onRouteChange'); event.route = uri; document.dispatchEvent(event, uri); } else { console.error('Route "' + uri + '" is not defined.'); return false; } }
javascript
function(uri) { if (this.defined(uri)) { history.pushState(null, null, uri); var event = new CustomEvent('onRouteChange'); event.route = uri; document.dispatchEvent(event, uri); } else { console.error('Route "' + uri + '" is not defined.'); return false; } }
[ "function", "(", "uri", ")", "{", "if", "(", "this", ".", "defined", "(", "uri", ")", ")", "{", "history", ".", "pushState", "(", "null", ",", "null", ",", "uri", ")", ";", "var", "event", "=", "new", "CustomEvent", "(", "'onRouteChange'", ")", ";", "event", ".", "route", "=", "uri", ";", "document", ".", "dispatchEvent", "(", "event", ",", "uri", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'Route \"'", "+", "uri", "+", "'\" is not defined.'", ")", ";", "return", "false", ";", "}", "}" ]
Redirect to new route @param uri @returns {boolean}
[ "Redirect", "to", "new", "route" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/src/bunny.route.js#L125-L135
22,031
Mevrael/bunny
examples/dropdown/dist/index.js
iteratorFor
function iteratorFor(items) { var iterator = { next: function next() { var value = items.shift(); return { done: value === undefined, value: value }; } }; if (support.iterable) { iterator[Symbol.iterator] = function () { return iterator; }; } return iterator; }
javascript
function iteratorFor(items) { var iterator = { next: function next() { var value = items.shift(); return { done: value === undefined, value: value }; } }; if (support.iterable) { iterator[Symbol.iterator] = function () { return iterator; }; } return iterator; }
[ "function", "iteratorFor", "(", "items", ")", "{", "var", "iterator", "=", "{", "next", ":", "function", "next", "(", ")", "{", "var", "value", "=", "items", ".", "shift", "(", ")", ";", "return", "{", "done", ":", "value", "===", "undefined", ",", "value", ":", "value", "}", ";", "}", "}", ";", "if", "(", "support", ".", "iterable", ")", "{", "iterator", "[", "Symbol", ".", "iterator", "]", "=", "function", "(", ")", "{", "return", "iterator", ";", "}", ";", "}", "return", "iterator", ";", "}" ]
Build a destructive iterator for the value list
[ "Build", "a", "destructive", "iterator", "for", "the", "value", "list" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L376-L391
22,032
Mevrael/bunny
examples/dropdown/dist/index.js
addEventOnce
function addEventOnce(element, eventName, eventListener) { var delay = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 500; var timeout = 0; return addEvent(element, eventName, function (e) { clearTimeout(timeout); timeout = setTimeout(function () { eventListener(e); }, delay); }); }
javascript
function addEventOnce(element, eventName, eventListener) { var delay = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 500; var timeout = 0; return addEvent(element, eventName, function (e) { clearTimeout(timeout); timeout = setTimeout(function () { eventListener(e); }, delay); }); }
[ "function", "addEventOnce", "(", "element", ",", "eventName", ",", "eventListener", ")", "{", "var", "delay", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "500", ";", "var", "timeout", "=", "0", ";", "return", "addEvent", "(", "element", ",", "eventName", ",", "function", "(", "e", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "eventListener", "(", "e", ")", ";", "}", ",", "delay", ")", ";", "}", ")", ";", "}" ]
Call event listener only once after "delay" ms Useful for scroll, keydown and other events when the actions must be done only once when user stopped typing or scrolling for example @param {HTMLElement} element @param {String} eventName @param {Function} eventListener @param {Number} delay @returns {Number}
[ "Call", "event", "listener", "only", "once", "after", "delay", "ms", "Useful", "for", "scroll", "keydown", "and", "other", "events", "when", "the", "actions", "must", "be", "done", "only", "once", "when", "user", "stopped", "typing", "or", "scrolling", "for", "example" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L919-L929
22,033
Mevrael/bunny
examples/dropdown/dist/index.js
addEventKeyNavigation
function addEventKeyNavigation(element, items, itemSelectCallback) { var itemSwitchCallback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var currentItemIndex = null; for (var k = 0; k < items.length; k++) { if (items[k].hasAttribute('aria-selected')) { currentItemIndex = k; break; } } /*let currentActiveItems = []; for (let k = 0; k < items.length; k++) { if (items[k].classList.contains(activeClass)) { currentActiveItems.push(items[k]); } }*/ var _itemAdd = function _itemAdd() { items[currentItemIndex].focus(); //items[currentItemIndex].classList.add(activeClass); //items[currentItemIndex].setAttribute('aria-selected', 'true'); /*if (!BunnyElement.isInViewport(items[currentItemIndex])) { BunnyElement.scrollTo(items[currentItemIndex], 400, -200); }*/ //items[currentItemIndex].scrollIntoView(false); if (itemSwitchCallback !== null) { itemSwitchCallback(items[currentItemIndex]); } }; var _itemRemove = function _itemRemove() { //items[currentItemIndex].classList.remove(activeClass); //items[currentItemIndex].removeAttribute('aria-selected'); }; var handler = function handler(e) { var c = e.keyCode; var maxItemIndex = items.length - 1; if (c === KEY_ENTER || c === KEY_SPACE) { e.preventDefault(); if (currentItemIndex !== null) { items[currentItemIndex].click(); itemSelectCallback(items[currentItemIndex]); } else { itemSelectCallback(null); } } else if (c === KEY_ESCAPE) { e.preventDefault(); /*for (let k = 0; k < items.length; k++) { if (currentActiveItems.indexOf(items[k]) === -1) { // remove active state items[k].classList.remove(activeClass); items[k].removeAttribute('aria-selected'); } else { // set active state items[k].classList.add(activeClass); items[k].setAttribute('aria-selected', 'true'); } }*/ itemSelectCallback(false); } else if (c === KEY_ARROW_UP || c === KEY_ARROW_LEFT) { e.preventDefault(); if (currentItemIndex !== null && currentItemIndex > 0) { _itemRemove(); currentItemIndex -= 1; _itemAdd(); } } else if (c === KEY_ARROW_DOWN || c === KEY_ARROW_RIGHT) { e.preventDefault(); if (currentItemIndex === null) { currentItemIndex = 0; _itemAdd(); } else if (currentItemIndex < maxItemIndex) { _itemRemove(); currentItemIndex += 1; _itemAdd(); } } }; if (items.length > 0) { element.addEventListener('keydown', handler); } return handler; }
javascript
function addEventKeyNavigation(element, items, itemSelectCallback) { var itemSwitchCallback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var currentItemIndex = null; for (var k = 0; k < items.length; k++) { if (items[k].hasAttribute('aria-selected')) { currentItemIndex = k; break; } } /*let currentActiveItems = []; for (let k = 0; k < items.length; k++) { if (items[k].classList.contains(activeClass)) { currentActiveItems.push(items[k]); } }*/ var _itemAdd = function _itemAdd() { items[currentItemIndex].focus(); //items[currentItemIndex].classList.add(activeClass); //items[currentItemIndex].setAttribute('aria-selected', 'true'); /*if (!BunnyElement.isInViewport(items[currentItemIndex])) { BunnyElement.scrollTo(items[currentItemIndex], 400, -200); }*/ //items[currentItemIndex].scrollIntoView(false); if (itemSwitchCallback !== null) { itemSwitchCallback(items[currentItemIndex]); } }; var _itemRemove = function _itemRemove() { //items[currentItemIndex].classList.remove(activeClass); //items[currentItemIndex].removeAttribute('aria-selected'); }; var handler = function handler(e) { var c = e.keyCode; var maxItemIndex = items.length - 1; if (c === KEY_ENTER || c === KEY_SPACE) { e.preventDefault(); if (currentItemIndex !== null) { items[currentItemIndex].click(); itemSelectCallback(items[currentItemIndex]); } else { itemSelectCallback(null); } } else if (c === KEY_ESCAPE) { e.preventDefault(); /*for (let k = 0; k < items.length; k++) { if (currentActiveItems.indexOf(items[k]) === -1) { // remove active state items[k].classList.remove(activeClass); items[k].removeAttribute('aria-selected'); } else { // set active state items[k].classList.add(activeClass); items[k].setAttribute('aria-selected', 'true'); } }*/ itemSelectCallback(false); } else if (c === KEY_ARROW_UP || c === KEY_ARROW_LEFT) { e.preventDefault(); if (currentItemIndex !== null && currentItemIndex > 0) { _itemRemove(); currentItemIndex -= 1; _itemAdd(); } } else if (c === KEY_ARROW_DOWN || c === KEY_ARROW_RIGHT) { e.preventDefault(); if (currentItemIndex === null) { currentItemIndex = 0; _itemAdd(); } else if (currentItemIndex < maxItemIndex) { _itemRemove(); currentItemIndex += 1; _itemAdd(); } } }; if (items.length > 0) { element.addEventListener('keydown', handler); } return handler; }
[ "function", "addEventKeyNavigation", "(", "element", ",", "items", ",", "itemSelectCallback", ")", "{", "var", "itemSwitchCallback", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "null", ";", "var", "currentItemIndex", "=", "null", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "items", ".", "length", ";", "k", "++", ")", "{", "if", "(", "items", "[", "k", "]", ".", "hasAttribute", "(", "'aria-selected'", ")", ")", "{", "currentItemIndex", "=", "k", ";", "break", ";", "}", "}", "/*let currentActiveItems = [];\n for (let k = 0; k < items.length; k++) {\n if (items[k].classList.contains(activeClass)) {\n currentActiveItems.push(items[k]);\n }\n }*/", "var", "_itemAdd", "=", "function", "_itemAdd", "(", ")", "{", "items", "[", "currentItemIndex", "]", ".", "focus", "(", ")", ";", "//items[currentItemIndex].classList.add(activeClass);", "//items[currentItemIndex].setAttribute('aria-selected', 'true');", "/*if (!BunnyElement.isInViewport(items[currentItemIndex])) {\n BunnyElement.scrollTo(items[currentItemIndex], 400, -200);\n }*/", "//items[currentItemIndex].scrollIntoView(false);", "if", "(", "itemSwitchCallback", "!==", "null", ")", "{", "itemSwitchCallback", "(", "items", "[", "currentItemIndex", "]", ")", ";", "}", "}", ";", "var", "_itemRemove", "=", "function", "_itemRemove", "(", ")", "{", "//items[currentItemIndex].classList.remove(activeClass);", "//items[currentItemIndex].removeAttribute('aria-selected');", "}", ";", "var", "handler", "=", "function", "handler", "(", "e", ")", "{", "var", "c", "=", "e", ".", "keyCode", ";", "var", "maxItemIndex", "=", "items", ".", "length", "-", "1", ";", "if", "(", "c", "===", "KEY_ENTER", "||", "c", "===", "KEY_SPACE", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "currentItemIndex", "!==", "null", ")", "{", "items", "[", "currentItemIndex", "]", ".", "click", "(", ")", ";", "itemSelectCallback", "(", "items", "[", "currentItemIndex", "]", ")", ";", "}", "else", "{", "itemSelectCallback", "(", "null", ")", ";", "}", "}", "else", "if", "(", "c", "===", "KEY_ESCAPE", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "/*for (let k = 0; k < items.length; k++) {\n if (currentActiveItems.indexOf(items[k]) === -1) {\n // remove active state\n items[k].classList.remove(activeClass);\n items[k].removeAttribute('aria-selected');\n } else {\n // set active state\n items[k].classList.add(activeClass);\n items[k].setAttribute('aria-selected', 'true');\n }\n }*/", "itemSelectCallback", "(", "false", ")", ";", "}", "else", "if", "(", "c", "===", "KEY_ARROW_UP", "||", "c", "===", "KEY_ARROW_LEFT", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "currentItemIndex", "!==", "null", "&&", "currentItemIndex", ">", "0", ")", "{", "_itemRemove", "(", ")", ";", "currentItemIndex", "-=", "1", ";", "_itemAdd", "(", ")", ";", "}", "}", "else", "if", "(", "c", "===", "KEY_ARROW_DOWN", "||", "c", "===", "KEY_ARROW_RIGHT", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "currentItemIndex", "===", "null", ")", "{", "currentItemIndex", "=", "0", ";", "_itemAdd", "(", ")", ";", "}", "else", "if", "(", "currentItemIndex", "<", "maxItemIndex", ")", "{", "_itemRemove", "(", ")", ";", "currentItemIndex", "+=", "1", ";", "_itemAdd", "(", ")", ";", "}", "}", "}", ";", "if", "(", "items", ".", "length", ">", "0", ")", "{", "element", ".", "addEventListener", "(", "'keydown'", ",", "handler", ")", ";", "}", "return", "handler", ";", "}" ]
Adds up, down, esc, enter keypress event on 'element' to traverse though 'items' @param {HTMLElement} element @param {HTMLCollection|NodeList} items @param {function} itemSelectCallback callback(null) if Enter was pressed and no item was selected (for example custom value entered) callback(false) if Esc was pressed (canceled) callback({HTMLElement} item) - selected item on Enter @param {function} itemSwitchCallback = null callback({HTMLElement} item) - new item on arrow up/down @returns {function(*)}
[ "Adds", "up", "down", "esc", "enter", "keypress", "event", "on", "element", "to", "traverse", "though", "items" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L1003-L1092
22,034
Mevrael/bunny
examples/dropdown/dist/index.js
checkPromise
function checkPromise(index) { var res = cb(callbacks[index]); // actually calling callback if (res instanceof Promise) { res.then(function (cbRes) { if (cbRes !== false) { // keep going if (index > 0) { checkPromise(index - 1); } } }); } else { if (res !== false) { // keep going if (index > 0) { checkPromise(index - 1); } } } }
javascript
function checkPromise(index) { var res = cb(callbacks[index]); // actually calling callback if (res instanceof Promise) { res.then(function (cbRes) { if (cbRes !== false) { // keep going if (index > 0) { checkPromise(index - 1); } } }); } else { if (res !== false) { // keep going if (index > 0) { checkPromise(index - 1); } } } }
[ "function", "checkPromise", "(", "index", ")", "{", "var", "res", "=", "cb", "(", "callbacks", "[", "index", "]", ")", ";", "// actually calling callback", "if", "(", "res", "instanceof", "Promise", ")", "{", "res", ".", "then", "(", "function", "(", "cbRes", ")", "{", "if", "(", "cbRes", "!==", "false", ")", "{", "// keep going", "if", "(", "index", ">", "0", ")", "{", "checkPromise", "(", "index", "-", "1", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "if", "(", "res", "!==", "false", ")", "{", "// keep going", "if", "(", "index", ">", "0", ")", "{", "checkPromise", "(", "index", "-", "1", ")", ";", "}", "}", "}", "}" ]
process each promise in direct order if promise returns false, do not execute further promises
[ "process", "each", "promise", "in", "direct", "order", "if", "promise", "returns", "false", "do", "not", "execute", "further", "promises" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L1248-L1267
22,035
Mevrael/bunny
examples/dropdown/dist/index.js
rgbaToColorMatrix
function rgbaToColorMatrix(red, green, blue) { var alpha = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var decToFloat = function decToFloat(value) { return Math.round(value / 255 * 10) / 10; }; var redFloat = decToFloat(red); var greenFloat = decToFloat(green); var blueFloat = decToFloat(blue); var alphaFloat = decToFloat(alpha); return '0 0 0 0 ' + redFloat + ' 0 0 0 0 ' + greenFloat + ' 0 0 0 0 ' + blueFloat + ' 0 0 0 1 ' + alphaFloat; }
javascript
function rgbaToColorMatrix(red, green, blue) { var alpha = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var decToFloat = function decToFloat(value) { return Math.round(value / 255 * 10) / 10; }; var redFloat = decToFloat(red); var greenFloat = decToFloat(green); var blueFloat = decToFloat(blue); var alphaFloat = decToFloat(alpha); return '0 0 0 0 ' + redFloat + ' 0 0 0 0 ' + greenFloat + ' 0 0 0 0 ' + blueFloat + ' 0 0 0 1 ' + alphaFloat; }
[ "function", "rgbaToColorMatrix", "(", "red", ",", "green", ",", "blue", ")", "{", "var", "alpha", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "0", ";", "var", "decToFloat", "=", "function", "decToFloat", "(", "value", ")", "{", "return", "Math", ".", "round", "(", "value", "/", "255", "*", "10", ")", "/", "10", ";", "}", ";", "var", "redFloat", "=", "decToFloat", "(", "red", ")", ";", "var", "greenFloat", "=", "decToFloat", "(", "green", ")", ";", "var", "blueFloat", "=", "decToFloat", "(", "blue", ")", ";", "var", "alphaFloat", "=", "decToFloat", "(", "alpha", ")", ";", "return", "'0 0 0 0 '", "+", "redFloat", "+", "' 0 0 0 0 '", "+", "greenFloat", "+", "' 0 0 0 0 '", "+", "blueFloat", "+", "' 0 0 0 1 '", "+", "alphaFloat", ";", "}" ]
SVG color matrix filter
[ "SVG", "color", "matrix", "filter" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L2202-L2213
22,036
Mevrael/bunny
examples/dropdown/dist/index.js
syncUI
function syncUI(customSelect, defaultValue, isMultiple) { var _this2 = this; console.log(defaultValue, isMultiple); var menuItems = this.getMenuItems(customSelect); var tglBtn = this.getToggleBtn(customSelect); var hasSelected = false; [].forEach.call(menuItems, function (menuItem) { if (defaultValue !== '') { var value = _this2.getItemValue(menuItem); if (isMultiple) { for (var k = 0; k < defaultValue.length; k++) { if (defaultValue[k] == value) { _this2.setItemActive(menuItem); hasSelected = true; _this2.getOptionByValue(customSelect, value).selected = true; break; } } } else if (value == defaultValue) { _this2.setItemActive(menuItem); hasSelected = true; _this2.getOptionByValue(customSelect, value).selected = true; if (tglBtn.innerHTML === '') { tglBtn.innerHTML = menuItem.innerHTML; } } } else if (menuItem.hasAttribute('aria-selected')) { _this2.setItemActive(menuItem); hasSelected = true; if (tglBtn.innerHTML === '') { tglBtn.innerHTML = menuItem.innerHTML; } } else if (menuItem.classList.contains(_this2.Config.classNameActive)) { _this2.setItemInactive(menuItem); } }); if (!hasSelected) { this.setItemActive(menuItems[0]); this.getHiddenSelect(customSelect).options[0].setAttribute('selected', ''); if (tglBtn.innerHTML === '') { tglBtn.innerHTML = menuItems[0].innerHTML; } } }
javascript
function syncUI(customSelect, defaultValue, isMultiple) { var _this2 = this; console.log(defaultValue, isMultiple); var menuItems = this.getMenuItems(customSelect); var tglBtn = this.getToggleBtn(customSelect); var hasSelected = false; [].forEach.call(menuItems, function (menuItem) { if (defaultValue !== '') { var value = _this2.getItemValue(menuItem); if (isMultiple) { for (var k = 0; k < defaultValue.length; k++) { if (defaultValue[k] == value) { _this2.setItemActive(menuItem); hasSelected = true; _this2.getOptionByValue(customSelect, value).selected = true; break; } } } else if (value == defaultValue) { _this2.setItemActive(menuItem); hasSelected = true; _this2.getOptionByValue(customSelect, value).selected = true; if (tglBtn.innerHTML === '') { tglBtn.innerHTML = menuItem.innerHTML; } } } else if (menuItem.hasAttribute('aria-selected')) { _this2.setItemActive(menuItem); hasSelected = true; if (tglBtn.innerHTML === '') { tglBtn.innerHTML = menuItem.innerHTML; } } else if (menuItem.classList.contains(_this2.Config.classNameActive)) { _this2.setItemInactive(menuItem); } }); if (!hasSelected) { this.setItemActive(menuItems[0]); this.getHiddenSelect(customSelect).options[0].setAttribute('selected', ''); if (tglBtn.innerHTML === '') { tglBtn.innerHTML = menuItems[0].innerHTML; } } }
[ "function", "syncUI", "(", "customSelect", ",", "defaultValue", ",", "isMultiple", ")", "{", "var", "_this2", "=", "this", ";", "console", ".", "log", "(", "defaultValue", ",", "isMultiple", ")", ";", "var", "menuItems", "=", "this", ".", "getMenuItems", "(", "customSelect", ")", ";", "var", "tglBtn", "=", "this", ".", "getToggleBtn", "(", "customSelect", ")", ";", "var", "hasSelected", "=", "false", ";", "[", "]", ".", "forEach", ".", "call", "(", "menuItems", ",", "function", "(", "menuItem", ")", "{", "if", "(", "defaultValue", "!==", "''", ")", "{", "var", "value", "=", "_this2", ".", "getItemValue", "(", "menuItem", ")", ";", "if", "(", "isMultiple", ")", "{", "for", "(", "var", "k", "=", "0", ";", "k", "<", "defaultValue", ".", "length", ";", "k", "++", ")", "{", "if", "(", "defaultValue", "[", "k", "]", "==", "value", ")", "{", "_this2", ".", "setItemActive", "(", "menuItem", ")", ";", "hasSelected", "=", "true", ";", "_this2", ".", "getOptionByValue", "(", "customSelect", ",", "value", ")", ".", "selected", "=", "true", ";", "break", ";", "}", "}", "}", "else", "if", "(", "value", "==", "defaultValue", ")", "{", "_this2", ".", "setItemActive", "(", "menuItem", ")", ";", "hasSelected", "=", "true", ";", "_this2", ".", "getOptionByValue", "(", "customSelect", ",", "value", ")", ".", "selected", "=", "true", ";", "if", "(", "tglBtn", ".", "innerHTML", "===", "''", ")", "{", "tglBtn", ".", "innerHTML", "=", "menuItem", ".", "innerHTML", ";", "}", "}", "}", "else", "if", "(", "menuItem", ".", "hasAttribute", "(", "'aria-selected'", ")", ")", "{", "_this2", ".", "setItemActive", "(", "menuItem", ")", ";", "hasSelected", "=", "true", ";", "if", "(", "tglBtn", ".", "innerHTML", "===", "''", ")", "{", "tglBtn", ".", "innerHTML", "=", "menuItem", ".", "innerHTML", ";", "}", "}", "else", "if", "(", "menuItem", ".", "classList", ".", "contains", "(", "_this2", ".", "Config", ".", "classNameActive", ")", ")", "{", "_this2", ".", "setItemInactive", "(", "menuItem", ")", ";", "}", "}", ")", ";", "if", "(", "!", "hasSelected", ")", "{", "this", ".", "setItemActive", "(", "menuItems", "[", "0", "]", ")", ";", "this", ".", "getHiddenSelect", "(", "customSelect", ")", ".", "options", "[", "0", "]", ".", "setAttribute", "(", "'selected'", ",", "''", ")", ";", "if", "(", "tglBtn", ".", "innerHTML", "===", "''", ")", "{", "tglBtn", ".", "innerHTML", "=", "menuItems", "[", "0", "]", ".", "innerHTML", ";", "}", "}", "}" ]
Synchronizes default value and selected options with UI If dropdown item has aria-selected but has no active class, add it If dropdown item has no aria-selected but has active class, remove it If no dropdown item selected, select 1st item and hidden option If customselect has value attribute, sets selected option according to it in highest priority @param {HTMLElement} customSelect @param {String|Array} defaultValue @param {boolean} isMultiple
[ "Synchronizes", "default", "value", "and", "selected", "options", "with", "UI", "If", "dropdown", "item", "has", "aria", "-", "selected", "but", "has", "no", "active", "class", "add", "it", "If", "dropdown", "item", "has", "no", "aria", "-", "selected", "but", "has", "active", "class", "remove", "it", "If", "no", "dropdown", "item", "selected", "select", "1st", "item", "and", "hidden", "option", "If", "customselect", "has", "value", "attribute", "sets", "selected", "option", "according", "to", "it", "in", "highest", "priority" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L2521-L2566
22,037
Mevrael/bunny
examples/dropdown/dist/index.js
getDefaultValue
function getDefaultValue(customSelect) { var val = customSelect.getAttribute('value'); if (val === null) { return ''; } var firstChar = val[0]; if (firstChar === undefined) { return ''; } else if (firstChar === '[') { return JSON.parse(val); } return val; }
javascript
function getDefaultValue(customSelect) { var val = customSelect.getAttribute('value'); if (val === null) { return ''; } var firstChar = val[0]; if (firstChar === undefined) { return ''; } else if (firstChar === '[') { return JSON.parse(val); } return val; }
[ "function", "getDefaultValue", "(", "customSelect", ")", "{", "var", "val", "=", "customSelect", ".", "getAttribute", "(", "'value'", ")", ";", "if", "(", "val", "===", "null", ")", "{", "return", "''", ";", "}", "var", "firstChar", "=", "val", "[", "0", "]", ";", "if", "(", "firstChar", "===", "undefined", ")", "{", "return", "''", ";", "}", "else", "if", "(", "firstChar", "===", "'['", ")", "{", "return", "JSON", ".", "parse", "(", "val", ")", ";", "}", "return", "val", ";", "}" ]
Get default value from value="" attribute which might be a string representing a single selected option value or a JSON array representing selected options in multiple select This attribute has highest priority over aria-selected which will be updated in syncUI() If value is empty string or no value attribute found then 1st option is selected @param customSelect @returns {String|Array}
[ "Get", "default", "value", "from", "value", "=", "attribute", "which", "might", "be", "a", "string", "representing", "a", "single", "selected", "option", "value", "or", "a", "JSON", "array", "representing", "selected", "options", "in", "multiple", "select" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L2655-L2667
22,038
Mevrael/bunny
examples/dropdown/dist/index.js
getSelectedValue
function getSelectedValue(customSelect) { var hiddenSelect = this.UI.getHiddenSelect(customSelect); if (this.isMultiple(customSelect)) { var selectedOptions = []; [].forEach.call(hiddenSelect.options, function (option) { if (option.selected) { selectedOptions.push(option.value); } }); return selectedOptions; } else { return hiddenSelect.options[hiddenSelect.selectedIndex].value; } }
javascript
function getSelectedValue(customSelect) { var hiddenSelect = this.UI.getHiddenSelect(customSelect); if (this.isMultiple(customSelect)) { var selectedOptions = []; [].forEach.call(hiddenSelect.options, function (option) { if (option.selected) { selectedOptions.push(option.value); } }); return selectedOptions; } else { return hiddenSelect.options[hiddenSelect.selectedIndex].value; } }
[ "function", "getSelectedValue", "(", "customSelect", ")", "{", "var", "hiddenSelect", "=", "this", ".", "UI", ".", "getHiddenSelect", "(", "customSelect", ")", ";", "if", "(", "this", ".", "isMultiple", "(", "customSelect", ")", ")", "{", "var", "selectedOptions", "=", "[", "]", ";", "[", "]", ".", "forEach", ".", "call", "(", "hiddenSelect", ".", "options", ",", "function", "(", "option", ")", "{", "if", "(", "option", ".", "selected", ")", "{", "selectedOptions", ".", "push", "(", "option", ".", "value", ")", ";", "}", "}", ")", ";", "return", "selectedOptions", ";", "}", "else", "{", "return", "hiddenSelect", ".", "options", "[", "hiddenSelect", ".", "selectedIndex", "]", ".", "value", ";", "}", "}" ]
Get selected value If select is multiple then returns array @param customSelect @returns {String|Array}
[ "Get", "selected", "value", "If", "select", "is", "multiple", "then", "returns", "array" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/dropdown/dist/index.js#L2712-L2725
22,039
Mevrael/bunny
examples/form/dist/index.js
_attachChangeAndDefaultFileEvent
function _attachChangeAndDefaultFileEvent(form_id) { var _this = this; var elements = this._collection[form_id].getInputs(); [].forEach.call(elements, function (form_control) { _this.__attachSingleChangeEvent(form_id, form_control); _this.__observeSingleValueChange(form_id, form_control); // set default file input value if (form_control.type === 'file' && form_control.hasAttribute('value')) { var url = form_control.getAttribute('value'); if (url !== '') { _this.setFileFromUrl(form_id, form_control.name, url); } } }); }
javascript
function _attachChangeAndDefaultFileEvent(form_id) { var _this = this; var elements = this._collection[form_id].getInputs(); [].forEach.call(elements, function (form_control) { _this.__attachSingleChangeEvent(form_id, form_control); _this.__observeSingleValueChange(form_id, form_control); // set default file input value if (form_control.type === 'file' && form_control.hasAttribute('value')) { var url = form_control.getAttribute('value'); if (url !== '') { _this.setFileFromUrl(form_id, form_control.name, url); } } }); }
[ "function", "_attachChangeAndDefaultFileEvent", "(", "form_id", ")", "{", "var", "_this", "=", "this", ";", "var", "elements", "=", "this", ".", "_collection", "[", "form_id", "]", ".", "getInputs", "(", ")", ";", "[", "]", ".", "forEach", ".", "call", "(", "elements", ",", "function", "(", "form_control", ")", "{", "_this", ".", "__attachSingleChangeEvent", "(", "form_id", ",", "form_control", ")", ";", "_this", ".", "__observeSingleValueChange", "(", "form_id", ",", "form_control", ")", ";", "// set default file input value", "if", "(", "form_control", ".", "type", "===", "'file'", "&&", "form_control", ".", "hasAttribute", "(", "'value'", ")", ")", "{", "var", "url", "=", "form_control", ".", "getAttribute", "(", "'value'", ")", ";", "if", "(", "url", "!==", "''", ")", "{", "_this", ".", "setFileFromUrl", "(", "form_id", ",", "form_control", ".", "name", ",", "url", ")", ";", "}", "}", "}", ")", ";", "}" ]
Update FormData when user changed input's value or when value changed from script Also init default value for File inputs @param {string} form_id @private
[ "Update", "FormData", "when", "user", "changed", "input", "s", "value", "or", "when", "value", "changed", "from", "script" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/form/dist/index.js#L742-L759
22,040
Mevrael/bunny
examples/form/dist/index.js
_parseFormControl
function _parseFormControl(form_id, form_control) { var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var type = this._collection[form_id].getInputType(form_control); console.log(type); // check if parser for specific input type exists and call it instead var method = type.toLowerCase(); method = method.charAt(0).toUpperCase() + method.slice(1); // upper case first char method = '_parseFormControl' + method; if (value === undefined) { method = method + 'Getter'; } if (this[method] !== undefined) { return this[method](form_id, form_control, value); } else { // call default parser // if input with same name exists - override if (value === undefined) { return this._parseFormControlDefaultGetter(form_id, form_control); } else { this._parseFormControlDefault(form_id, form_control, value); } } }
javascript
function _parseFormControl(form_id, form_control) { var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var type = this._collection[form_id].getInputType(form_control); console.log(type); // check if parser for specific input type exists and call it instead var method = type.toLowerCase(); method = method.charAt(0).toUpperCase() + method.slice(1); // upper case first char method = '_parseFormControl' + method; if (value === undefined) { method = method + 'Getter'; } if (this[method] !== undefined) { return this[method](form_id, form_control, value); } else { // call default parser // if input with same name exists - override if (value === undefined) { return this._parseFormControlDefaultGetter(form_id, form_control); } else { this._parseFormControlDefault(form_id, form_control, value); } } }
[ "function", "_parseFormControl", "(", "form_id", ",", "form_control", ")", "{", "var", "value", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "undefined", ";", "var", "type", "=", "this", ".", "_collection", "[", "form_id", "]", ".", "getInputType", "(", "form_control", ")", ";", "console", ".", "log", "(", "type", ")", ";", "// check if parser for specific input type exists and call it instead", "var", "method", "=", "type", ".", "toLowerCase", "(", ")", ";", "method", "=", "method", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "method", ".", "slice", "(", "1", ")", ";", "// upper case first char", "method", "=", "'_parseFormControl'", "+", "method", ";", "if", "(", "value", "===", "undefined", ")", "{", "method", "=", "method", "+", "'Getter'", ";", "}", "if", "(", "this", "[", "method", "]", "!==", "undefined", ")", "{", "return", "this", "[", "method", "]", "(", "form_id", ",", "form_control", ",", "value", ")", ";", "}", "else", "{", "// call default parser", "// if input with same name exists - override", "if", "(", "value", "===", "undefined", ")", "{", "return", "this", ".", "_parseFormControlDefaultGetter", "(", "form_id", ",", "form_control", ")", ";", "}", "else", "{", "this", ".", "_parseFormControlDefault", "(", "form_id", ",", "form_control", ",", "value", ")", ";", "}", "}", "}" ]
handlers for different input types with 4th argument - setter without 4th argument - getter called from .value property observer
[ "handlers", "for", "different", "input", "types", "with", "4th", "argument", "-", "setter", "without", "4th", "argument", "-", "getter", "called", "from", ".", "value", "property", "observer" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/form/dist/index.js#L795-L822
22,041
Mevrael/bunny
examples/form/dist/index.js
download
function download(URL) { var convert_to_blob = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var request = new XMLHttpRequest(); var p = new Promise(function (success, fail) { request.onload = function () { if (request.status === 200) { var blob = request.response; success(blob); } else { fail(request); } }; }); request.open('GET', URL, true); if (convert_to_blob) { request.responseType = 'blob'; } request.send(); return p; }
javascript
function download(URL) { var convert_to_blob = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var request = new XMLHttpRequest(); var p = new Promise(function (success, fail) { request.onload = function () { if (request.status === 200) { var blob = request.response; success(blob); } else { fail(request); } }; }); request.open('GET', URL, true); if (convert_to_blob) { request.responseType = 'blob'; } request.send(); return p; }
[ "function", "download", "(", "URL", ")", "{", "var", "convert_to_blob", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "true", ";", "var", "request", "=", "new", "XMLHttpRequest", "(", ")", ";", "var", "p", "=", "new", "Promise", "(", "function", "(", "success", ",", "fail", ")", "{", "request", ".", "onload", "=", "function", "(", ")", "{", "if", "(", "request", ".", "status", "===", "200", ")", "{", "var", "blob", "=", "request", ".", "response", ";", "success", "(", "blob", ")", ";", "}", "else", "{", "fail", "(", "request", ")", ";", "}", "}", ";", "}", ")", ";", "request", ".", "open", "(", "'GET'", ",", "URL", ",", "true", ")", ";", "if", "(", "convert_to_blob", ")", "{", "request", ".", "responseType", "=", "'blob'", ";", "}", "request", ".", "send", "(", ")", ";", "return", "p", ";", "}" ]
Download file from URL via AJAX and make Blob object or return base64 string if 2nd argument is false Only files from CORS-enabled domains can be downloaded or AJAX will get security error @param {String} URL @param {Boolean} convert_to_blob = true @returns {Promise}: success(Blob object | base64 string), fail(response XHR object)
[ "Download", "file", "from", "URL", "via", "AJAX", "and", "make", "Blob", "object", "or", "return", "base64", "string", "if", "2nd", "argument", "is", "false", "Only", "files", "from", "CORS", "-", "enabled", "domains", "can", "be", "downloaded", "or", "AJAX", "will", "get", "security", "error" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/form/dist/index.js#L1343-L1365
22,042
Mevrael/bunny
examples/form/dist/index.js
base64ToBlob
function base64ToBlob(base64) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(base64.split(',')[1]); // separate out the mime component var mimeString = base64.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // write the ArrayBuffer to a blob, and you're done return new Blob([ab], { type: mimeString }); }
javascript
function base64ToBlob(base64) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(base64.split(',')[1]); // separate out the mime component var mimeString = base64.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // write the ArrayBuffer to a blob, and you're done return new Blob([ab], { type: mimeString }); }
[ "function", "base64ToBlob", "(", "base64", ")", "{", "// convert base64 to raw binary data held in a string", "// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this", "var", "byteString", "=", "atob", "(", "base64", ".", "split", "(", "','", ")", "[", "1", "]", ")", ";", "// separate out the mime component", "var", "mimeString", "=", "base64", ".", "split", "(", "','", ")", "[", "0", "]", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "split", "(", "';'", ")", "[", "0", "]", ";", "// write the bytes of the string to an ArrayBuffer", "var", "ab", "=", "new", "ArrayBuffer", "(", "byteString", ".", "length", ")", ";", "var", "ia", "=", "new", "Uint8Array", "(", "ab", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "byteString", ".", "length", ";", "i", "++", ")", "{", "ia", "[", "i", "]", "=", "byteString", ".", "charCodeAt", "(", "i", ")", ";", "}", "// write the ArrayBuffer to a blob, and you're done", "return", "new", "Blob", "(", "[", "ab", "]", ",", "{", "type", ":", "mimeString", "}", ")", ";", "}" ]
Convert base64 string to Blob object @param {String} base64 @returns {Blob}
[ "Convert", "base64", "string", "to", "Blob", "object" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/form/dist/index.js#L1415-L1432
22,043
Mevrael/bunny
examples/form/dist/index.js
blobToBase64
function blobToBase64(blob) { var reader = new FileReader(); var p = new Promise(function (success, fail) { reader.onloadend = function () { var base64 = reader.result; success(base64); }; reader.onerror = function (e) { fail(e); }; }); reader.readAsDataURL(blob); return p; }
javascript
function blobToBase64(blob) { var reader = new FileReader(); var p = new Promise(function (success, fail) { reader.onloadend = function () { var base64 = reader.result; success(base64); }; reader.onerror = function (e) { fail(e); }; }); reader.readAsDataURL(blob); return p; }
[ "function", "blobToBase64", "(", "blob", ")", "{", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "var", "p", "=", "new", "Promise", "(", "function", "(", "success", ",", "fail", ")", "{", "reader", ".", "onloadend", "=", "function", "(", ")", "{", "var", "base64", "=", "reader", ".", "result", ";", "success", "(", "base64", ")", ";", "}", ";", "reader", ".", "onerror", "=", "function", "(", "e", ")", "{", "fail", "(", "e", ")", ";", "}", ";", "}", ")", ";", "reader", ".", "readAsDataURL", "(", "blob", ")", ";", "return", "p", ";", "}" ]
Convert Blob object to base64string @param {Blob} blob @returns {Promise} success(base64 string), fail(error)
[ "Convert", "Blob", "object", "to", "base64string" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/form/dist/index.js#L1440-L1455
22,044
Mevrael/bunny
examples/form/dist/index.js
getBlobLocalURL
function getBlobLocalURL(blob) { if (!(blob instanceof Blob || blob instanceof File)) { throw new TypeError('Argument in BunnyFile.getBlobLocalURL() is not a Blob or File object'); } return URL.createObjectURL(blob); }
javascript
function getBlobLocalURL(blob) { if (!(blob instanceof Blob || blob instanceof File)) { throw new TypeError('Argument in BunnyFile.getBlobLocalURL() is not a Blob or File object'); } return URL.createObjectURL(blob); }
[ "function", "getBlobLocalURL", "(", "blob", ")", "{", "if", "(", "!", "(", "blob", "instanceof", "Blob", "||", "blob", "instanceof", "File", ")", ")", "{", "throw", "new", "TypeError", "(", "'Argument in BunnyFile.getBlobLocalURL() is not a Blob or File object'", ")", ";", "}", "return", "URL", ".", "createObjectURL", "(", "blob", ")", ";", "}" ]
Get local browser object URL which can be used in img.src for example @param {Blob} blob @returns {String}
[ "Get", "local", "browser", "object", "URL", "which", "can", "be", "used", "in", "img", ".", "src", "for", "example" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/form/dist/index.js#L1463-L1468
22,045
Mevrael/bunny
examples/validation/dist/index.js
scrollTo
function scrollTo(target) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500; var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var rootElement = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : window; return new Promise(function (onAnimationEnd) { var element = void 0; if (typeof target === 'string') { element = document.querySelector(target); } else if ((typeof target === 'undefined' ? 'undefined' : babelHelpers.typeof(target)) === 'object') { element = target; } else { // number element = null; } if (element !== null && element.offsetParent === null) { // element is not visible, scroll to top of parent element element = element.parentNode; } var start = rootElement === window ? window.pageYOffset : rootElement.scrollTop; var distance = 0; if (element !== null) { distance = element.getBoundingClientRect().top; } else { // number distance = target; } distance = distance + offset; if (typeof duration === 'function') { duration = duration(distance); } var timeStart = 0; var timeElapsed = 0; requestAnimationFrame(function (time) { timeStart = time; loop(time); }); function setScrollYPosition(el, y) { if (el === window) { window.scrollTo(0, y); } else { el.scrollTop = y; } } function loop(time) { timeElapsed = time - timeStart; setScrollYPosition(rootElement, easeInOutQuad(timeElapsed, start, distance, duration)); if (timeElapsed < duration) { requestAnimationFrame(loop); } else { end(); } } function end() { setScrollYPosition(rootElement, start + distance); onAnimationEnd(); } // Robert Penner's easeInOutQuad - http://robertpenner.com/easing/ function easeInOutQuad(t, b, c, d) { t /= d / 2; if (t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; } }); }
javascript
function scrollTo(target) { var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500; var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var rootElement = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : window; return new Promise(function (onAnimationEnd) { var element = void 0; if (typeof target === 'string') { element = document.querySelector(target); } else if ((typeof target === 'undefined' ? 'undefined' : babelHelpers.typeof(target)) === 'object') { element = target; } else { // number element = null; } if (element !== null && element.offsetParent === null) { // element is not visible, scroll to top of parent element element = element.parentNode; } var start = rootElement === window ? window.pageYOffset : rootElement.scrollTop; var distance = 0; if (element !== null) { distance = element.getBoundingClientRect().top; } else { // number distance = target; } distance = distance + offset; if (typeof duration === 'function') { duration = duration(distance); } var timeStart = 0; var timeElapsed = 0; requestAnimationFrame(function (time) { timeStart = time; loop(time); }); function setScrollYPosition(el, y) { if (el === window) { window.scrollTo(0, y); } else { el.scrollTop = y; } } function loop(time) { timeElapsed = time - timeStart; setScrollYPosition(rootElement, easeInOutQuad(timeElapsed, start, distance, duration)); if (timeElapsed < duration) { requestAnimationFrame(loop); } else { end(); } } function end() { setScrollYPosition(rootElement, start + distance); onAnimationEnd(); } // Robert Penner's easeInOutQuad - http://robertpenner.com/easing/ function easeInOutQuad(t, b, c, d) { t /= d / 2; if (t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; } }); }
[ "function", "scrollTo", "(", "target", ")", "{", "var", "duration", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "500", ";", "var", "offset", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "0", ";", "var", "rootElement", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "window", ";", "return", "new", "Promise", "(", "function", "(", "onAnimationEnd", ")", "{", "var", "element", "=", "void", "0", ";", "if", "(", "typeof", "target", "===", "'string'", ")", "{", "element", "=", "document", ".", "querySelector", "(", "target", ")", ";", "}", "else", "if", "(", "(", "typeof", "target", "===", "'undefined'", "?", "'undefined'", ":", "babelHelpers", ".", "typeof", "(", "target", ")", ")", "===", "'object'", ")", "{", "element", "=", "target", ";", "}", "else", "{", "// number", "element", "=", "null", ";", "}", "if", "(", "element", "!==", "null", "&&", "element", ".", "offsetParent", "===", "null", ")", "{", "// element is not visible, scroll to top of parent element", "element", "=", "element", ".", "parentNode", ";", "}", "var", "start", "=", "rootElement", "===", "window", "?", "window", ".", "pageYOffset", ":", "rootElement", ".", "scrollTop", ";", "var", "distance", "=", "0", ";", "if", "(", "element", "!==", "null", ")", "{", "distance", "=", "element", ".", "getBoundingClientRect", "(", ")", ".", "top", ";", "}", "else", "{", "// number", "distance", "=", "target", ";", "}", "distance", "=", "distance", "+", "offset", ";", "if", "(", "typeof", "duration", "===", "'function'", ")", "{", "duration", "=", "duration", "(", "distance", ")", ";", "}", "var", "timeStart", "=", "0", ";", "var", "timeElapsed", "=", "0", ";", "requestAnimationFrame", "(", "function", "(", "time", ")", "{", "timeStart", "=", "time", ";", "loop", "(", "time", ")", ";", "}", ")", ";", "function", "setScrollYPosition", "(", "el", ",", "y", ")", "{", "if", "(", "el", "===", "window", ")", "{", "window", ".", "scrollTo", "(", "0", ",", "y", ")", ";", "}", "else", "{", "el", ".", "scrollTop", "=", "y", ";", "}", "}", "function", "loop", "(", "time", ")", "{", "timeElapsed", "=", "time", "-", "timeStart", ";", "setScrollYPosition", "(", "rootElement", ",", "easeInOutQuad", "(", "timeElapsed", ",", "start", ",", "distance", ",", "duration", ")", ")", ";", "if", "(", "timeElapsed", "<", "duration", ")", "{", "requestAnimationFrame", "(", "loop", ")", ";", "}", "else", "{", "end", "(", ")", ";", "}", "}", "function", "end", "(", ")", "{", "setScrollYPosition", "(", "rootElement", ",", "start", "+", "distance", ")", ";", "onAnimationEnd", "(", ")", ";", "}", "// Robert Penner's easeInOutQuad - http://robertpenner.com/easing/", "function", "easeInOutQuad", "(", "t", ",", "b", ",", "c", ",", "d", ")", "{", "t", "/=", "d", "/", "2", ";", "if", "(", "t", "<", "1", ")", "return", "c", "/", "2", "*", "t", "*", "t", "+", "b", ";", "t", "--", ";", "return", "-", "c", "/", "2", "*", "(", "t", "*", "(", "t", "-", "2", ")", "-", "1", ")", "+", "b", ";", "}", "}", ")", ";", "}" ]
Smooth scrolling to DOM element or to relative window position If target is string it should be CSS selector If target is object it should be DOM element If target is number - it is used to relatively scroll X pixels form current position Based on https://www.sitepoint.com/smooth-scrolling-vanilla-javascript/ @param {HTMLElement, string, number} target @param {Number|function} duration @param {Number} offset @param {HTMLElement} rootElement
[ "Smooth", "scrolling", "to", "DOM", "element", "or", "to", "relative", "window", "position", "If", "target", "is", "string", "it", "should", "be", "CSS", "selector", "If", "target", "is", "object", "it", "should", "be", "DOM", "element", "If", "target", "is", "number", "-", "it", "is", "used", "to", "relatively", "scroll", "X", "pixels", "form", "current", "position" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L849-L925
22,046
Mevrael/bunny
examples/validation/dist/index.js
_bn_getFile
function _bn_getFile(input) { // if there is custom file upload logic, for example, images are resized client-side // generated Blobs should be assigned to fileInput._file // and can be sent via ajax with FormData // if file was deleted, custom field can be set to an empty string // Bunny Validation detects if there is custom Blob assigned to file input // and uses this file for validation instead of original read-only input.files[] if (input._file !== undefined && input._file !== '') { if (input._file instanceof Blob === false) { console.error("Custom file for input " + input.name + " is not an instance of Blob"); return false; } return input._file; } return input.files[0] || false; }
javascript
function _bn_getFile(input) { // if there is custom file upload logic, for example, images are resized client-side // generated Blobs should be assigned to fileInput._file // and can be sent via ajax with FormData // if file was deleted, custom field can be set to an empty string // Bunny Validation detects if there is custom Blob assigned to file input // and uses this file for validation instead of original read-only input.files[] if (input._file !== undefined && input._file !== '') { if (input._file instanceof Blob === false) { console.error("Custom file for input " + input.name + " is not an instance of Blob"); return false; } return input._file; } return input.files[0] || false; }
[ "function", "_bn_getFile", "(", "input", ")", "{", "// if there is custom file upload logic, for example, images are resized client-side", "// generated Blobs should be assigned to fileInput._file", "// and can be sent via ajax with FormData", "// if file was deleted, custom field can be set to an empty string", "// Bunny Validation detects if there is custom Blob assigned to file input", "// and uses this file for validation instead of original read-only input.files[]", "if", "(", "input", ".", "_file", "!==", "undefined", "&&", "input", ".", "_file", "!==", "''", ")", "{", "if", "(", "input", ".", "_file", "instanceof", "Blob", "===", "false", ")", "{", "console", ".", "error", "(", "\"Custom file for input \"", "+", "input", ".", "name", "+", "\" is not an instance of Blob\"", ")", ";", "return", "false", ";", "}", "return", "input", ".", "_file", ";", "}", "return", "input", ".", "files", "[", "0", "]", "||", "false", ";", "}" ]
Bunny Validation helper - get file to validate @param {HTMLInputElement} input @returns {File|Blob|boolean} - If no file uploaded - returns false @private
[ "Bunny", "Validation", "helper", "-", "get", "file", "to", "validate" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1046-L1063
22,047
Mevrael/bunny
examples/validation/dist/index.js
image
function image(input) { return new Promise(function (valid, invalid) { if (input.getAttribute('type') === 'file' && input.getAttribute('accept').indexOf('image') > -1 && _bn_getFile(input) !== false) { BunnyFile.getSignature(_bn_getFile(input)).then(function (signature) { if (BunnyFile.isJpeg(signature) || BunnyFile.isPng(signature)) { valid(); } else { invalid({ signature: signature }); } }).catch(function (e) { invalid(e); }); } else { valid(); } }); }
javascript
function image(input) { return new Promise(function (valid, invalid) { if (input.getAttribute('type') === 'file' && input.getAttribute('accept').indexOf('image') > -1 && _bn_getFile(input) !== false) { BunnyFile.getSignature(_bn_getFile(input)).then(function (signature) { if (BunnyFile.isJpeg(signature) || BunnyFile.isPng(signature)) { valid(); } else { invalid({ signature: signature }); } }).catch(function (e) { invalid(e); }); } else { valid(); } }); }
[ "function", "image", "(", "input", ")", "{", "return", "new", "Promise", "(", "function", "(", "valid", ",", "invalid", ")", "{", "if", "(", "input", ".", "getAttribute", "(", "'type'", ")", "===", "'file'", "&&", "input", ".", "getAttribute", "(", "'accept'", ")", ".", "indexOf", "(", "'image'", ")", ">", "-", "1", "&&", "_bn_getFile", "(", "input", ")", "!==", "false", ")", "{", "BunnyFile", ".", "getSignature", "(", "_bn_getFile", "(", "input", ")", ")", ".", "then", "(", "function", "(", "signature", ")", "{", "if", "(", "BunnyFile", ".", "isJpeg", "(", "signature", ")", "||", "BunnyFile", ".", "isPng", "(", "signature", ")", ")", "{", "valid", "(", ")", ";", "}", "else", "{", "invalid", "(", "{", "signature", ":", "signature", "}", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "invalid", "(", "e", ")", ";", "}", ")", ";", "}", "else", "{", "valid", "(", ")", ";", "}", "}", ")", ";", "}" ]
if file input has "accept" attribute and it contains "image", then check if uploaded file is a JPG or PNG
[ "if", "file", "input", "has", "accept", "attribute", "and", "it", "contains", "image", "then", "check", "if", "uploaded", "file", "is", "a", "JPG", "or", "PNG" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1171-L1187
22,048
Mevrael/bunny
examples/validation/dist/index.js
createErrorNode
function createErrorNode() { var el = document.createElement(this.config.tagNameError); el.classList.add(this.config.classError); return el; }
javascript
function createErrorNode() { var el = document.createElement(this.config.tagNameError); el.classList.add(this.config.classError); return el; }
[ "function", "createErrorNode", "(", ")", "{", "var", "el", "=", "document", ".", "createElement", "(", "this", ".", "config", ".", "tagNameError", ")", ";", "el", ".", "classList", ".", "add", "(", "this", ".", "config", ".", "classError", ")", ";", "return", "el", ";", "}" ]
Create DOM element for error message @returns {HTMLElement}
[ "Create", "DOM", "element", "for", "error", "message" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1369-L1373
22,049
Mevrael/bunny
examples/validation/dist/index.js
removeErrorNode
function removeErrorNode(inputGroup) { var el = this.getErrorNode(inputGroup); if (el) { el.parentNode.removeChild(el); this.toggleErrorClass(inputGroup); } }
javascript
function removeErrorNode(inputGroup) { var el = this.getErrorNode(inputGroup); if (el) { el.parentNode.removeChild(el); this.toggleErrorClass(inputGroup); } }
[ "function", "removeErrorNode", "(", "inputGroup", ")", "{", "var", "el", "=", "this", ".", "getErrorNode", "(", "inputGroup", ")", ";", "if", "(", "el", ")", "{", "el", ".", "parentNode", ".", "removeChild", "(", "el", ")", ";", "this", ".", "toggleErrorClass", "(", "inputGroup", ")", ";", "}", "}" ]
Removes error node and class from input group if exists @param {HTMLElement} inputGroup
[ "Removes", "error", "node", "and", "class", "from", "input", "group", "if", "exists" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1393-L1399
22,050
Mevrael/bunny
examples/validation/dist/index.js
removeErrorNodesFromSection
function removeErrorNodesFromSection(section) { var _this = this; [].forEach.call(this.getInputGroupsInSection(section), function (inputGroup) { _this.removeErrorNode(inputGroup); }); }
javascript
function removeErrorNodesFromSection(section) { var _this = this; [].forEach.call(this.getInputGroupsInSection(section), function (inputGroup) { _this.removeErrorNode(inputGroup); }); }
[ "function", "removeErrorNodesFromSection", "(", "section", ")", "{", "var", "_this", "=", "this", ";", "[", "]", ".", "forEach", ".", "call", "(", "this", ".", "getInputGroupsInSection", "(", "section", ")", ",", "function", "(", "inputGroup", ")", "{", "_this", ".", "removeErrorNode", "(", "inputGroup", ")", ";", "}", ")", ";", "}" ]
Removes all error node and class from input group if exists within section @param {HTMLElement} section
[ "Removes", "all", "error", "node", "and", "class", "from", "input", "group", "if", "exists", "within", "section" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1407-L1413
22,051
Mevrael/bunny
examples/validation/dist/index.js
setErrorMessage
function setErrorMessage(inputGroup, message) { var errorNode = this.getErrorNode(inputGroup); if (errorNode === false) { // container for error message doesn't exists, create new errorNode = this.createErrorNode(); this.toggleErrorClass(inputGroup); this.insertErrorNode(inputGroup, errorNode); } // set or update error message errorNode.textContent = message; }
javascript
function setErrorMessage(inputGroup, message) { var errorNode = this.getErrorNode(inputGroup); if (errorNode === false) { // container for error message doesn't exists, create new errorNode = this.createErrorNode(); this.toggleErrorClass(inputGroup); this.insertErrorNode(inputGroup, errorNode); } // set or update error message errorNode.textContent = message; }
[ "function", "setErrorMessage", "(", "inputGroup", ",", "message", ")", "{", "var", "errorNode", "=", "this", ".", "getErrorNode", "(", "inputGroup", ")", ";", "if", "(", "errorNode", "===", "false", ")", "{", "// container for error message doesn't exists, create new", "errorNode", "=", "this", ".", "createErrorNode", "(", ")", ";", "this", ".", "toggleErrorClass", "(", "inputGroup", ")", ";", "this", ".", "insertErrorNode", "(", "inputGroup", ",", "errorNode", ")", ";", "}", "// set or update error message", "errorNode", ".", "textContent", "=", "message", ";", "}" ]
Creates and includes into DOM error node or updates error message @param {HTMLElement} inputGroup @param {String} message
[ "Creates", "and", "includes", "into", "DOM", "error", "node", "or", "updates", "error", "message" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1422-L1432
22,052
Mevrael/bunny
examples/validation/dist/index.js
getInputGroup
function getInputGroup(input) { var el = input; while ((el = el.parentNode) && !el.classList.contains(this.config.classInputGroup)) {} return el; }
javascript
function getInputGroup(input) { var el = input; while ((el = el.parentNode) && !el.classList.contains(this.config.classInputGroup)) {} return el; }
[ "function", "getInputGroup", "(", "input", ")", "{", "var", "el", "=", "input", ";", "while", "(", "(", "el", "=", "el", ".", "parentNode", ")", "&&", "!", "el", ".", "classList", ".", "contains", "(", "this", ".", "config", ".", "classInputGroup", ")", ")", "{", "}", "return", "el", ";", "}" ]
Find closest parent inputGroup element by Input element @param {HTMLElement} input @returns {HTMLElement}
[ "Find", "closest", "parent", "inputGroup", "element", "by", "Input", "element" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1468-L1472
22,053
Mevrael/bunny
examples/validation/dist/index.js
getInputsInSection
function getInputsInSection(node) { var resolving = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var inputGroups = this.getInputGroupsInSection(node); var inputs = void 0; if (resolving) { inputs = { inputs: {}, invalidInputs: {}, length: 0, unresolvedLength: 0, invalidLength: 0 }; } else { inputs = []; } for (var k = 0; k < inputGroups.length; k++) { var input = this.getInput(inputGroups[k]); if (input === false) { console.error(inputGroups[k]); throw new Error('Bunny Validation: Input group has no input'); } if (resolving) { inputs.inputs[k] = { input: input, isValid: null }; inputs.length++; inputs.unresolvedLength++; } else { inputs.push(input); } } return inputs; }
javascript
function getInputsInSection(node) { var resolving = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var inputGroups = this.getInputGroupsInSection(node); var inputs = void 0; if (resolving) { inputs = { inputs: {}, invalidInputs: {}, length: 0, unresolvedLength: 0, invalidLength: 0 }; } else { inputs = []; } for (var k = 0; k < inputGroups.length; k++) { var input = this.getInput(inputGroups[k]); if (input === false) { console.error(inputGroups[k]); throw new Error('Bunny Validation: Input group has no input'); } if (resolving) { inputs.inputs[k] = { input: input, isValid: null }; inputs.length++; inputs.unresolvedLength++; } else { inputs.push(input); } } return inputs; }
[ "function", "getInputsInSection", "(", "node", ")", "{", "var", "resolving", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "false", ";", "var", "inputGroups", "=", "this", ".", "getInputGroupsInSection", "(", "node", ")", ";", "var", "inputs", "=", "void", "0", ";", "if", "(", "resolving", ")", "{", "inputs", "=", "{", "inputs", ":", "{", "}", ",", "invalidInputs", ":", "{", "}", ",", "length", ":", "0", ",", "unresolvedLength", ":", "0", ",", "invalidLength", ":", "0", "}", ";", "}", "else", "{", "inputs", "=", "[", "]", ";", "}", "for", "(", "var", "k", "=", "0", ";", "k", "<", "inputGroups", ".", "length", ";", "k", "++", ")", "{", "var", "input", "=", "this", ".", "getInput", "(", "inputGroups", "[", "k", "]", ")", ";", "if", "(", "input", "===", "false", ")", "{", "console", ".", "error", "(", "inputGroups", "[", "k", "]", ")", ";", "throw", "new", "Error", "(", "'Bunny Validation: Input group has no input'", ")", ";", "}", "if", "(", "resolving", ")", "{", "inputs", ".", "inputs", "[", "k", "]", "=", "{", "input", ":", "input", ",", "isValid", ":", "null", "}", ";", "inputs", ".", "length", "++", ";", "inputs", ".", "unresolvedLength", "++", ";", "}", "else", "{", "inputs", ".", "push", "(", "input", ")", ";", "}", "}", "return", "inputs", ";", "}" ]
Find inputs in section @meta if second argument true - return object with meta information to use during promise resolving @param {HTMLElement} node @param {boolean} resolving = false @returns {Array|Object}
[ "Find", "inputs", "in", "section" ]
90bea09545288e0f050b5c2a5f72c0ed7252b98e
https://github.com/Mevrael/bunny/blob/90bea09545288e0f050b5c2a5f72c0ed7252b98e/examples/validation/dist/index.js#L1485-L1519
22,054
L33T-KR3W/push-dir
index.js
getCurrentBranch
function getCurrentBranch(verbose) { return Promise.resolve() .then(execCmd.bind(null, 'git', ['symbolic-ref', 'HEAD', '-q'], 'problem getting current branch', verbose )) .catch(function() { return ''; }) .then(function(result) { return result.replace(new RegExp('^refs\/heads\/'), ''); }); }
javascript
function getCurrentBranch(verbose) { return Promise.resolve() .then(execCmd.bind(null, 'git', ['symbolic-ref', 'HEAD', '-q'], 'problem getting current branch', verbose )) .catch(function() { return ''; }) .then(function(result) { return result.replace(new RegExp('^refs\/heads\/'), ''); }); }
[ "function", "getCurrentBranch", "(", "verbose", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "execCmd", ".", "bind", "(", "null", ",", "'git'", ",", "[", "'symbolic-ref'", ",", "'HEAD'", ",", "'-q'", "]", ",", "'problem getting current branch'", ",", "verbose", ")", ")", ".", "catch", "(", "function", "(", ")", "{", "return", "''", ";", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "return", "result", ".", "replace", "(", "new", "RegExp", "(", "'^refs\\/heads\\/'", ")", ",", "''", ")", ";", "}", ")", ";", "}" ]
Returns name of current branch or empty string if detached HEAD @return {string} - name of current branch
[ "Returns", "name", "of", "current", "branch", "or", "empty", "string", "if", "detached", "HEAD" ]
a708b3c95a4fd4698ee0a4dc91090ca2796ae174
https://github.com/L33T-KR3W/push-dir/blob/a708b3c95a4fd4698ee0a4dc91090ca2796ae174/index.js#L66-L80
22,055
Nhogs/popoto
src/graph/util/appendFittedText.js
computeTextRadius
function computeTextRadius(lines) { var textRadius = 0; for (var i = 0, n = lines.length; i < n; ++i) { var dx = lines[i].width / 2; var dy = (Math.abs(i - n / 2 + 0.5) + 0.5) * DEFAULT_CANVAS_LINE_HEIGHT; textRadius = Math.max(textRadius, Math.sqrt(dx * dx + dy * dy)); } return textRadius; }
javascript
function computeTextRadius(lines) { var textRadius = 0; for (var i = 0, n = lines.length; i < n; ++i) { var dx = lines[i].width / 2; var dy = (Math.abs(i - n / 2 + 0.5) + 0.5) * DEFAULT_CANVAS_LINE_HEIGHT; textRadius = Math.max(textRadius, Math.sqrt(dx * dx + dy * dy)); } return textRadius; }
[ "function", "computeTextRadius", "(", "lines", ")", "{", "var", "textRadius", "=", "0", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "lines", ".", "length", ";", "i", "<", "n", ";", "++", "i", ")", "{", "var", "dx", "=", "lines", "[", "i", "]", ".", "width", "/", "2", ";", "var", "dy", "=", "(", "Math", ".", "abs", "(", "i", "-", "n", "/", "2", "+", "0.5", ")", "+", "0.5", ")", "*", "DEFAULT_CANVAS_LINE_HEIGHT", ";", "textRadius", "=", "Math", ".", "max", "(", "textRadius", ",", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ")", ";", "}", "return", "textRadius", ";", "}" ]
Compute the radius of the circle wrapping all the lines. @param lines array of text lines @return {number}
[ "Compute", "the", "radius", "of", "the", "circle", "wrapping", "all", "the", "lines", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/graph/util/appendFittedText.js#L17-L27
22,056
Nhogs/popoto
src/graph/util/appendFittedText.js
computeWords
function computeWords(text) { var words = text.split(/\s+/g); // To hyphenate: /\s+|(?<=-)/ if (!words[words.length - 1]) words.pop(); if (!words[0]) words.shift(); return words; }
javascript
function computeWords(text) { var words = text.split(/\s+/g); // To hyphenate: /\s+|(?<=-)/ if (!words[words.length - 1]) words.pop(); if (!words[0]) words.shift(); return words; }
[ "function", "computeWords", "(", "text", ")", "{", "var", "words", "=", "text", ".", "split", "(", "/", "\\s+", "/", "g", ")", ";", "// To hyphenate: /\\s+|(?<=-)/", "if", "(", "!", "words", "[", "words", ".", "length", "-", "1", "]", ")", "words", ".", "pop", "(", ")", ";", "if", "(", "!", "words", "[", "0", "]", ")", "words", ".", "shift", "(", ")", ";", "return", "words", ";", "}" ]
Split text into words. @param text @return {*|string[]}
[ "Split", "text", "into", "words", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/graph/util/appendFittedText.js#L60-L65
22,057
Nhogs/popoto
src/popoto.js
checkHtmlComponents
function checkHtmlComponents() { var graphHTMLContainer = d3.select("#" + graph.containerId); var taxonomyHTMLContainer = d3.select("#" + taxonomy.containerId); var queryHTMLContainer = d3.select("#" + queryviewer.containerId); var cypherHTMLContainer = d3.select("#" + cypherviewer.containerId); var resultsHTMLContainer = d3.select("#" + result.containerId); if (graphHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + graph.containerId + "\" no graph area will be generated. This ID is defined in graph.containerId property."); graph.isActive = false; } else { graph.isActive = true; } if (taxonomyHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + taxonomy.containerId + "\" no taxonomy filter will be generated. This ID is defined in taxonomy.containerId property."); taxonomy.isActive = false; } else { taxonomy.isActive = true; } if (queryHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + queryviewer.containerId + "\" no query viewer will be generated. This ID is defined in queryviewer.containerId property."); queryviewer.isActive = false; } else { queryviewer.isActive = true; } if (cypherHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + cypherviewer.containerId + "\" no cypher query viewer will be generated. This ID is defined in cypherviewer.containerId property."); cypherviewer.isActive = false; } else { cypherviewer.isActive = true; } if (resultsHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + result.containerId + "\" no result area will be generated. This ID is defined in result.containerId property."); result.isActive = false; } else { result.isActive = true; } }
javascript
function checkHtmlComponents() { var graphHTMLContainer = d3.select("#" + graph.containerId); var taxonomyHTMLContainer = d3.select("#" + taxonomy.containerId); var queryHTMLContainer = d3.select("#" + queryviewer.containerId); var cypherHTMLContainer = d3.select("#" + cypherviewer.containerId); var resultsHTMLContainer = d3.select("#" + result.containerId); if (graphHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + graph.containerId + "\" no graph area will be generated. This ID is defined in graph.containerId property."); graph.isActive = false; } else { graph.isActive = true; } if (taxonomyHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + taxonomy.containerId + "\" no taxonomy filter will be generated. This ID is defined in taxonomy.containerId property."); taxonomy.isActive = false; } else { taxonomy.isActive = true; } if (queryHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + queryviewer.containerId + "\" no query viewer will be generated. This ID is defined in queryviewer.containerId property."); queryviewer.isActive = false; } else { queryviewer.isActive = true; } if (cypherHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + cypherviewer.containerId + "\" no cypher query viewer will be generated. This ID is defined in cypherviewer.containerId property."); cypherviewer.isActive = false; } else { cypherviewer.isActive = true; } if (resultsHTMLContainer.empty()) { logger.debug("The page doesn't contain a container with ID = \"" + result.containerId + "\" no result area will be generated. This ID is defined in result.containerId property."); result.isActive = false; } else { result.isActive = true; } }
[ "function", "checkHtmlComponents", "(", ")", "{", "var", "graphHTMLContainer", "=", "d3", ".", "select", "(", "\"#\"", "+", "graph", ".", "containerId", ")", ";", "var", "taxonomyHTMLContainer", "=", "d3", ".", "select", "(", "\"#\"", "+", "taxonomy", ".", "containerId", ")", ";", "var", "queryHTMLContainer", "=", "d3", ".", "select", "(", "\"#\"", "+", "queryviewer", ".", "containerId", ")", ";", "var", "cypherHTMLContainer", "=", "d3", ".", "select", "(", "\"#\"", "+", "cypherviewer", ".", "containerId", ")", ";", "var", "resultsHTMLContainer", "=", "d3", ".", "select", "(", "\"#\"", "+", "result", ".", "containerId", ")", ";", "if", "(", "graphHTMLContainer", ".", "empty", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"The page doesn't contain a container with ID = \\\"\"", "+", "graph", ".", "containerId", "+", "\"\\\" no graph area will be generated. This ID is defined in graph.containerId property.\"", ")", ";", "graph", ".", "isActive", "=", "false", ";", "}", "else", "{", "graph", ".", "isActive", "=", "true", ";", "}", "if", "(", "taxonomyHTMLContainer", ".", "empty", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"The page doesn't contain a container with ID = \\\"\"", "+", "taxonomy", ".", "containerId", "+", "\"\\\" no taxonomy filter will be generated. This ID is defined in taxonomy.containerId property.\"", ")", ";", "taxonomy", ".", "isActive", "=", "false", ";", "}", "else", "{", "taxonomy", ".", "isActive", "=", "true", ";", "}", "if", "(", "queryHTMLContainer", ".", "empty", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"The page doesn't contain a container with ID = \\\"\"", "+", "queryviewer", ".", "containerId", "+", "\"\\\" no query viewer will be generated. This ID is defined in queryviewer.containerId property.\"", ")", ";", "queryviewer", ".", "isActive", "=", "false", ";", "}", "else", "{", "queryviewer", ".", "isActive", "=", "true", ";", "}", "if", "(", "cypherHTMLContainer", ".", "empty", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"The page doesn't contain a container with ID = \\\"\"", "+", "cypherviewer", ".", "containerId", "+", "\"\\\" no cypher query viewer will be generated. This ID is defined in cypherviewer.containerId property.\"", ")", ";", "cypherviewer", ".", "isActive", "=", "false", ";", "}", "else", "{", "cypherviewer", ".", "isActive", "=", "true", ";", "}", "if", "(", "resultsHTMLContainer", ".", "empty", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"The page doesn't contain a container with ID = \\\"\"", "+", "result", ".", "containerId", "+", "\"\\\" no result area will be generated. This ID is defined in result.containerId property.\"", ")", ";", "result", ".", "isActive", "=", "false", ";", "}", "else", "{", "result", ".", "isActive", "=", "true", ";", "}", "}" ]
Check in the HTML page the components to generate.
[ "Check", "in", "the", "HTML", "page", "the", "components", "to", "generate", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/popoto.js#L70-L111
22,058
Nhogs/popoto
src/provider/provider.js
function (link) { if (link.type === graph.link.LinkTypes.VALUE) { // Links between node and list of values. if (provider.node.isTextDisplayed(link.target)) { // Don't display text on link if text is displayed on target node. return ""; } else { // No text is displayed on target node then the text is displayed on link. return provider.node.getTextValue(link.target); } } else { var targetName = ""; if (link.type === graph.link.LinkTypes.SEGMENT) { targetName = " " + provider.node.getTextValue(link.target); } return link.label + targetName; } }
javascript
function (link) { if (link.type === graph.link.LinkTypes.VALUE) { // Links between node and list of values. if (provider.node.isTextDisplayed(link.target)) { // Don't display text on link if text is displayed on target node. return ""; } else { // No text is displayed on target node then the text is displayed on link. return provider.node.getTextValue(link.target); } } else { var targetName = ""; if (link.type === graph.link.LinkTypes.SEGMENT) { targetName = " " + provider.node.getTextValue(link.target); } return link.label + targetName; } }
[ "function", "(", "link", ")", "{", "if", "(", "link", ".", "type", "===", "graph", ".", "link", ".", "LinkTypes", ".", "VALUE", ")", "{", "// Links between node and list of values.", "if", "(", "provider", ".", "node", ".", "isTextDisplayed", "(", "link", ".", "target", ")", ")", "{", "// Don't display text on link if text is displayed on target node.", "return", "\"\"", ";", "}", "else", "{", "// No text is displayed on target node then the text is displayed on link.", "return", "provider", ".", "node", ".", "getTextValue", "(", "link", ".", "target", ")", ";", "}", "}", "else", "{", "var", "targetName", "=", "\"\"", ";", "if", "(", "link", ".", "type", "===", "graph", ".", "link", ".", "LinkTypes", ".", "SEGMENT", ")", "{", "targetName", "=", "\" \"", "+", "provider", ".", "node", ".", "getTextValue", "(", "link", ".", "target", ")", ";", "}", "return", "link", ".", "label", "+", "targetName", ";", "}", "}" ]
Function used to return the text representation of a link. The default behavior is to return the internal relation name as text for relation links. And return the target node text value for links between a node and its expanded values but only if text is not displayed on value node. @param link the link to represent as text. @returns {string} the text representation of the link.
[ "Function", "used", "to", "return", "the", "text", "representation", "of", "a", "link", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/provider/provider.js#L130-L149
22,059
Nhogs/popoto
src/provider/provider.js
function (link, element, attribute) { if (link.type === graph.link.LinkTypes.VALUE) { return "#525863"; } else { var colorId = link.source.label + link.label + link.target.label; var color = provider.colorScale(colorId); if (attribute === "stroke") { return provider.colorLuminance(color, -0.2); } return color; } }
javascript
function (link, element, attribute) { if (link.type === graph.link.LinkTypes.VALUE) { return "#525863"; } else { var colorId = link.source.label + link.label + link.target.label; var color = provider.colorScale(colorId); if (attribute === "stroke") { return provider.colorLuminance(color, -0.2); } return color; } }
[ "function", "(", "link", ",", "element", ",", "attribute", ")", "{", "if", "(", "link", ".", "type", "===", "graph", ".", "link", ".", "LinkTypes", ".", "VALUE", ")", "{", "return", "\"#525863\"", ";", "}", "else", "{", "var", "colorId", "=", "link", ".", "source", ".", "label", "+", "link", ".", "label", "+", "link", ".", "target", ".", "label", ";", "var", "color", "=", "provider", ".", "colorScale", "(", "colorId", ")", ";", "if", "(", "attribute", "===", "\"stroke\"", ")", "{", "return", "provider", ".", "colorLuminance", "(", "color", ",", "-", "0.2", ")", ";", "}", "return", "color", ";", "}", "}" ]
Return the color to use on links and relation donut segments. Return null or undefined @param link @param element @param attribute @return {*}
[ "Return", "the", "color", "to", "use", "on", "links", "and", "relation", "donut", "segments", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/provider/provider.js#L174-L186
22,060
Nhogs/popoto
src/provider/provider.js
function (node) { if (node.type === graph.node.NodeTypes.VALUE) { return provider.node.getColor(node.parent); } else { var parentLabel = ""; if (node.hasOwnProperty("parent")) { parentLabel = node.parent.label } var incomingRelation = node.parentRel || ""; var colorId = parentLabel + incomingRelation + node.label; return provider.colorScale(colorId); } }
javascript
function (node) { if (node.type === graph.node.NodeTypes.VALUE) { return provider.node.getColor(node.parent); } else { var parentLabel = ""; if (node.hasOwnProperty("parent")) { parentLabel = node.parent.label } var incomingRelation = node.parentRel || ""; var colorId = parentLabel + incomingRelation + node.label; return provider.colorScale(colorId); } }
[ "function", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "graph", ".", "node", ".", "NodeTypes", ".", "VALUE", ")", "{", "return", "provider", ".", "node", ".", "getColor", "(", "node", ".", "parent", ")", ";", "}", "else", "{", "var", "parentLabel", "=", "\"\"", ";", "if", "(", "node", ".", "hasOwnProperty", "(", "\"parent\"", ")", ")", "{", "parentLabel", "=", "node", ".", "parent", ".", "label", "}", "var", "incomingRelation", "=", "node", ".", "parentRel", "||", "\"\"", ";", "var", "colorId", "=", "parentLabel", "+", "incomingRelation", "+", "node", ".", "label", ";", "return", "provider", ".", "colorScale", "(", "colorId", ")", ";", "}", "}" ]
Return a color for the node. @param node @returns {*}
[ "Return", "a", "color", "for", "the", "node", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/provider/provider.js#L927-L941
22,061
Nhogs/popoto
src/provider/provider.js
function (node, element) { var labelAsCSSName = node.label.replace(/[^0-9a-z\-_]/gi, ''); var cssClass = "ppt-node__" + element; if (node.type === graph.node.NodeTypes.ROOT) { cssClass = cssClass + "--root"; } if (node.type === graph.node.NodeTypes.CHOOSE) { cssClass = cssClass + "--choose"; } if (node.type === graph.node.NodeTypes.GROUP) { cssClass = cssClass + "--group"; } if (node.type === graph.node.NodeTypes.VALUE) { cssClass = cssClass + "--value"; } if (node.value !== undefined && node.value.length > 0) { cssClass = cssClass + "--value-selected"; } if (node.count === 0) { cssClass = cssClass + "--disabled"; } return cssClass + " " + labelAsCSSName; }
javascript
function (node, element) { var labelAsCSSName = node.label.replace(/[^0-9a-z\-_]/gi, ''); var cssClass = "ppt-node__" + element; if (node.type === graph.node.NodeTypes.ROOT) { cssClass = cssClass + "--root"; } if (node.type === graph.node.NodeTypes.CHOOSE) { cssClass = cssClass + "--choose"; } if (node.type === graph.node.NodeTypes.GROUP) { cssClass = cssClass + "--group"; } if (node.type === graph.node.NodeTypes.VALUE) { cssClass = cssClass + "--value"; } if (node.value !== undefined && node.value.length > 0) { cssClass = cssClass + "--value-selected"; } if (node.count === 0) { cssClass = cssClass + "--disabled"; } return cssClass + " " + labelAsCSSName; }
[ "function", "(", "node", ",", "element", ")", "{", "var", "labelAsCSSName", "=", "node", ".", "label", ".", "replace", "(", "/", "[^0-9a-z\\-_]", "/", "gi", ",", "''", ")", ";", "var", "cssClass", "=", "\"ppt-node__\"", "+", "element", ";", "if", "(", "node", ".", "type", "===", "graph", ".", "node", ".", "NodeTypes", ".", "ROOT", ")", "{", "cssClass", "=", "cssClass", "+", "\"--root\"", ";", "}", "if", "(", "node", ".", "type", "===", "graph", ".", "node", ".", "NodeTypes", ".", "CHOOSE", ")", "{", "cssClass", "=", "cssClass", "+", "\"--choose\"", ";", "}", "if", "(", "node", ".", "type", "===", "graph", ".", "node", ".", "NodeTypes", ".", "GROUP", ")", "{", "cssClass", "=", "cssClass", "+", "\"--group\"", ";", "}", "if", "(", "node", ".", "type", "===", "graph", ".", "node", ".", "NodeTypes", ".", "VALUE", ")", "{", "cssClass", "=", "cssClass", "+", "\"--value\"", ";", "}", "if", "(", "node", ".", "value", "!==", "undefined", "&&", "node", ".", "value", ".", "length", ">", "0", ")", "{", "cssClass", "=", "cssClass", "+", "\"--value-selected\"", ";", "}", "if", "(", "node", ".", "count", "===", "0", ")", "{", "cssClass", "=", "cssClass", "+", "\"--disabled\"", ";", "}", "return", "cssClass", "+", "\" \"", "+", "labelAsCSSName", ";", "}" ]
Generate a CSS class for the node depending on its type. @param node @param element @return {string}
[ "Generate", "a", "CSS", "class", "for", "the", "node", "depending", "on", "its", "type", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/provider/provider.js#L950-L975
22,062
Nhogs/popoto
src/provider/provider.js
function (node) { var text = ""; var displayAttr = provider.node.getDisplayAttribute(node.label); if (node.type === graph.node.NodeTypes.VALUE) { if (displayAttr === query.NEO4J_INTERNAL_ID) { text = "" + node.internalID; } else { text = "" + node.attributes[displayAttr]; } } else { if (node.value !== undefined && node.value.length > 0) { if (displayAttr === query.NEO4J_INTERNAL_ID) { var separator = ""; node.value.forEach(function (value) { text += separator + value.internalID; separator = " or "; }); } else { var separator = ""; node.value.forEach(function (value) { text += separator + value.attributes[displayAttr]; separator = " or "; }); } } else { text = node.label; } } return text; }
javascript
function (node) { var text = ""; var displayAttr = provider.node.getDisplayAttribute(node.label); if (node.type === graph.node.NodeTypes.VALUE) { if (displayAttr === query.NEO4J_INTERNAL_ID) { text = "" + node.internalID; } else { text = "" + node.attributes[displayAttr]; } } else { if (node.value !== undefined && node.value.length > 0) { if (displayAttr === query.NEO4J_INTERNAL_ID) { var separator = ""; node.value.forEach(function (value) { text += separator + value.internalID; separator = " or "; }); } else { var separator = ""; node.value.forEach(function (value) { text += separator + value.attributes[displayAttr]; separator = " or "; }); } } else { text = node.label; } } return text; }
[ "function", "(", "node", ")", "{", "var", "text", "=", "\"\"", ";", "var", "displayAttr", "=", "provider", ".", "node", ".", "getDisplayAttribute", "(", "node", ".", "label", ")", ";", "if", "(", "node", ".", "type", "===", "graph", ".", "node", ".", "NodeTypes", ".", "VALUE", ")", "{", "if", "(", "displayAttr", "===", "query", ".", "NEO4J_INTERNAL_ID", ")", "{", "text", "=", "\"\"", "+", "node", ".", "internalID", ";", "}", "else", "{", "text", "=", "\"\"", "+", "node", ".", "attributes", "[", "displayAttr", "]", ";", "}", "}", "else", "{", "if", "(", "node", ".", "value", "!==", "undefined", "&&", "node", ".", "value", ".", "length", ">", "0", ")", "{", "if", "(", "displayAttr", "===", "query", ".", "NEO4J_INTERNAL_ID", ")", "{", "var", "separator", "=", "\"\"", ";", "node", ".", "value", ".", "forEach", "(", "function", "(", "value", ")", "{", "text", "+=", "separator", "+", "value", ".", "internalID", ";", "separator", "=", "\" or \"", ";", "}", ")", ";", "}", "else", "{", "var", "separator", "=", "\"\"", ";", "node", ".", "value", ".", "forEach", "(", "function", "(", "value", ")", "{", "text", "+=", "separator", "+", "value", ".", "attributes", "[", "displayAttr", "]", ";", "separator", "=", "\" or \"", ";", "}", ")", ";", "}", "}", "else", "{", "text", "=", "node", ".", "label", ";", "}", "}", "return", "text", ";", "}" ]
Function used to return a descriptive text representation of a link. This representation should be more complete than getTextValue and can contain semantic data. This function is used for example to generate the label in the query viewer. The default behavior is to return the getTextValue not truncated. @param node the node to represent as text. @returns {string} the text semantic representation of the node.
[ "Function", "used", "to", "return", "a", "descriptive", "text", "representation", "of", "a", "link", ".", "This", "representation", "should", "be", "more", "complete", "than", "getTextValue", "and", "can", "contain", "semantic", "data", ".", "This", "function", "is", "used", "for", "example", "to", "generate", "the", "label", "in", "the", "query", "viewer", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/provider/provider.js#L1066-L1095
22,063
Nhogs/popoto
src/provider/provider.js
function (node) { var size = provider.node.getSize(node); return [ { "d": "M 0, 0 m -" + size + ", 0 a " + size + "," + size + " 0 1,0 " + 2 * size + ",0 a " + size + "," + size + " 0 1,0 -" + 2 * size + ",0", "fill": "transparent", "stroke": provider.node.getColor(node), "stroke-width": "2px" } ]; }
javascript
function (node) { var size = provider.node.getSize(node); return [ { "d": "M 0, 0 m -" + size + ", 0 a " + size + "," + size + " 0 1,0 " + 2 * size + ",0 a " + size + "," + size + " 0 1,0 -" + 2 * size + ",0", "fill": "transparent", "stroke": provider.node.getColor(node), "stroke-width": "2px" } ]; }
[ "function", "(", "node", ")", "{", "var", "size", "=", "provider", ".", "node", ".", "getSize", "(", "node", ")", ";", "return", "[", "{", "\"d\"", ":", "\"M 0, 0 m -\"", "+", "size", "+", "\", 0 a \"", "+", "size", "+", "\",\"", "+", "size", "+", "\" 0 1,0 \"", "+", "2", "*", "size", "+", "\",0 a \"", "+", "size", "+", "\",\"", "+", "size", "+", "\" 0 1,0 -\"", "+", "2", "*", "size", "+", "\",0\"", ",", "\"fill\"", ":", "\"transparent\"", ",", "\"stroke\"", ":", "provider", ".", "node", ".", "getColor", "(", "node", ")", ",", "\"stroke-width\"", ":", "\"2px\"", "}", "]", ";", "}" ]
Function returning a array of path objects to display in the node. @param node @returns {*[]}
[ "Function", "returning", "a", "array", "of", "path", "objects", "to", "display", "in", "the", "node", "." ]
1dbed2f0e0c999a75c786d4955f14e3fe2ace47b
https://github.com/Nhogs/popoto/blob/1dbed2f0e0c999a75c786d4955f14e3fe2ace47b/src/provider/provider.js#L1120-L1130
22,064
ampproject/animations
docs/demo/lightbox/index.js
getTransitionContainer
function getTransitionContainer(show) { if (document.body.scrollHeight <= window.innerHeight) { return lightboxTransitionContainer; } return document.body; }
javascript
function getTransitionContainer(show) { if (document.body.scrollHeight <= window.innerHeight) { return lightboxTransitionContainer; } return document.body; }
[ "function", "getTransitionContainer", "(", "show", ")", "{", "if", "(", "document", ".", "body", ".", "scrollHeight", "<=", "window", ".", "innerHeight", ")", "{", "return", "lightboxTransitionContainer", ";", "}", "return", "document", ".", "body", ";", "}" ]
Gets the container to do the transition in. This is either the body or a fixed position container, depending on if the body has overflow or not. This is needed as doing the transition with position absolute can cause overflow, causing the scrollbars to show up during the animation. Depending on the OS, this can cause layout as the scrollbar shows/hides. Normally, we want to do the transition in the body, so that if the user scrolls while the transition is in progress (while the lightbox is) closing, the transition ends up in the right place. Note: you will want to prevent scrolling when the lightbox is opening to prevent scrolling during the animation. This will make sure the animation ends in the right place (and that the user does not scroll the body when they do not intend to).
[ "Gets", "the", "container", "to", "do", "the", "transition", "in", ".", "This", "is", "either", "the", "body", "or", "a", "fixed", "position", "container", "depending", "on", "if", "the", "body", "has", "overflow", "or", "not", "." ]
03fd1132095e8e60234280d4adccf05366bab58f
https://github.com/ampproject/animations/blob/03fd1132095e8e60234280d4adccf05366bab58f/docs/demo/lightbox/index.js#L49-L55
22,065
ampproject/animations
docs/demo/gallery/index.js
loadLargerImgSrc
function loadLargerImgSrc(img, largerSize) { if (img._preloaded) { return; } const dummyImg = new Image(); dummyImg.srcset = img.srcset; dummyImg.sizes = largerSize; img._preloaded = true; }
javascript
function loadLargerImgSrc(img, largerSize) { if (img._preloaded) { return; } const dummyImg = new Image(); dummyImg.srcset = img.srcset; dummyImg.sizes = largerSize; img._preloaded = true; }
[ "function", "loadLargerImgSrc", "(", "img", ",", "largerSize", ")", "{", "if", "(", "img", ".", "_preloaded", ")", "{", "return", ";", "}", "const", "dummyImg", "=", "new", "Image", "(", ")", ";", "dummyImg", ".", "srcset", "=", "img", ".", "srcset", ";", "dummyImg", ".", "sizes", "=", "largerSize", ";", "img", ".", "_preloaded", "=", "true", ";", "}" ]
Loads an img using a srcset, with a larger `size` value. This does not actually set the `size` attribute on the img.
[ "Loads", "an", "img", "using", "a", "srcset", "with", "a", "larger", "size", "value", ".", "This", "does", "not", "actually", "set", "the", "size", "attribute", "on", "the", "img", "." ]
03fd1132095e8e60234280d4adccf05366bab58f
https://github.com/ampproject/animations/blob/03fd1132095e8e60234280d4adccf05366bab58f/docs/demo/gallery/index.js#L36-L46
22,066
mourner/flatbush
index.js
upperBound
function upperBound(value, arr) { let i = 0; let j = arr.length - 1; while (i < j) { const m = (i + j) >> 1; if (arr[m] > value) { j = m; } else { i = m + 1; } } return arr[i]; }
javascript
function upperBound(value, arr) { let i = 0; let j = arr.length - 1; while (i < j) { const m = (i + j) >> 1; if (arr[m] > value) { j = m; } else { i = m + 1; } } return arr[i]; }
[ "function", "upperBound", "(", "value", ",", "arr", ")", "{", "let", "i", "=", "0", ";", "let", "j", "=", "arr", ".", "length", "-", "1", ";", "while", "(", "i", "<", "j", ")", "{", "const", "m", "=", "(", "i", "+", "j", ")", ">>", "1", ";", "if", "(", "arr", "[", "m", "]", ">", "value", ")", "{", "j", "=", "m", ";", "}", "else", "{", "i", "=", "m", "+", "1", ";", "}", "}", "return", "arr", "[", "i", "]", ";", "}" ]
binary search for the first value in the array bigger than the given
[ "binary", "search", "for", "the", "first", "value", "in", "the", "array", "bigger", "than", "the", "given" ]
65a01d9fe60b643ae6b6728a839a07c845fc0cd9
https://github.com/mourner/flatbush/blob/65a01d9fe60b643ae6b6728a839a07c845fc0cd9/index.js#L263-L275
22,067
mourner/flatbush
index.js
sort
function sort(values, boxes, indices, left, right) { if (left >= right) return; const pivot = values[(left + right) >> 1]; let i = left - 1; let j = right + 1; while (true) { do i++; while (values[i] < pivot); do j--; while (values[j] > pivot); if (i >= j) break; swap(values, boxes, indices, i, j); } sort(values, boxes, indices, left, j); sort(values, boxes, indices, j + 1, right); }
javascript
function sort(values, boxes, indices, left, right) { if (left >= right) return; const pivot = values[(left + right) >> 1]; let i = left - 1; let j = right + 1; while (true) { do i++; while (values[i] < pivot); do j--; while (values[j] > pivot); if (i >= j) break; swap(values, boxes, indices, i, j); } sort(values, boxes, indices, left, j); sort(values, boxes, indices, j + 1, right); }
[ "function", "sort", "(", "values", ",", "boxes", ",", "indices", ",", "left", ",", "right", ")", "{", "if", "(", "left", ">=", "right", ")", "return", ";", "const", "pivot", "=", "values", "[", "(", "left", "+", "right", ")", ">>", "1", "]", ";", "let", "i", "=", "left", "-", "1", ";", "let", "j", "=", "right", "+", "1", ";", "while", "(", "true", ")", "{", "do", "i", "++", ";", "while", "(", "values", "[", "i", "]", "<", "pivot", ")", ";", "do", "j", "--", ";", "while", "(", "values", "[", "j", "]", ">", "pivot", ")", ";", "if", "(", "i", ">=", "j", ")", "break", ";", "swap", "(", "values", ",", "boxes", ",", "indices", ",", "i", ",", "j", ")", ";", "}", "sort", "(", "values", ",", "boxes", ",", "indices", ",", "left", ",", "j", ")", ";", "sort", "(", "values", ",", "boxes", ",", "indices", ",", "j", "+", "1", ",", "right", ")", ";", "}" ]
custom quicksort that sorts bbox data alongside the hilbert values
[ "custom", "quicksort", "that", "sorts", "bbox", "data", "alongside", "the", "hilbert", "values" ]
65a01d9fe60b643ae6b6728a839a07c845fc0cd9
https://github.com/mourner/flatbush/blob/65a01d9fe60b643ae6b6728a839a07c845fc0cd9/index.js#L278-L294
22,068
mourner/flatbush
index.js
swap
function swap(values, boxes, indices, i, j) { const temp = values[i]; values[i] = values[j]; values[j] = temp; const k = 4 * i; const m = 4 * j; const a = boxes[k]; const b = boxes[k + 1]; const c = boxes[k + 2]; const d = boxes[k + 3]; boxes[k] = boxes[m]; boxes[k + 1] = boxes[m + 1]; boxes[k + 2] = boxes[m + 2]; boxes[k + 3] = boxes[m + 3]; boxes[m] = a; boxes[m + 1] = b; boxes[m + 2] = c; boxes[m + 3] = d; const e = indices[i]; indices[i] = indices[j]; indices[j] = e; }
javascript
function swap(values, boxes, indices, i, j) { const temp = values[i]; values[i] = values[j]; values[j] = temp; const k = 4 * i; const m = 4 * j; const a = boxes[k]; const b = boxes[k + 1]; const c = boxes[k + 2]; const d = boxes[k + 3]; boxes[k] = boxes[m]; boxes[k + 1] = boxes[m + 1]; boxes[k + 2] = boxes[m + 2]; boxes[k + 3] = boxes[m + 3]; boxes[m] = a; boxes[m + 1] = b; boxes[m + 2] = c; boxes[m + 3] = d; const e = indices[i]; indices[i] = indices[j]; indices[j] = e; }
[ "function", "swap", "(", "values", ",", "boxes", ",", "indices", ",", "i", ",", "j", ")", "{", "const", "temp", "=", "values", "[", "i", "]", ";", "values", "[", "i", "]", "=", "values", "[", "j", "]", ";", "values", "[", "j", "]", "=", "temp", ";", "const", "k", "=", "4", "*", "i", ";", "const", "m", "=", "4", "*", "j", ";", "const", "a", "=", "boxes", "[", "k", "]", ";", "const", "b", "=", "boxes", "[", "k", "+", "1", "]", ";", "const", "c", "=", "boxes", "[", "k", "+", "2", "]", ";", "const", "d", "=", "boxes", "[", "k", "+", "3", "]", ";", "boxes", "[", "k", "]", "=", "boxes", "[", "m", "]", ";", "boxes", "[", "k", "+", "1", "]", "=", "boxes", "[", "m", "+", "1", "]", ";", "boxes", "[", "k", "+", "2", "]", "=", "boxes", "[", "m", "+", "2", "]", ";", "boxes", "[", "k", "+", "3", "]", "=", "boxes", "[", "m", "+", "3", "]", ";", "boxes", "[", "m", "]", "=", "a", ";", "boxes", "[", "m", "+", "1", "]", "=", "b", ";", "boxes", "[", "m", "+", "2", "]", "=", "c", ";", "boxes", "[", "m", "+", "3", "]", "=", "d", ";", "const", "e", "=", "indices", "[", "i", "]", ";", "indices", "[", "i", "]", "=", "indices", "[", "j", "]", ";", "indices", "[", "j", "]", "=", "e", ";", "}" ]
swap two values and two corresponding boxes
[ "swap", "two", "values", "and", "two", "corresponding", "boxes" ]
65a01d9fe60b643ae6b6728a839a07c845fc0cd9
https://github.com/mourner/flatbush/blob/65a01d9fe60b643ae6b6728a839a07c845fc0cd9/index.js#L297-L321
22,069
boilerplates/scaffold
index.js
Scaffold
function Scaffold(options) { if (!(this instanceof Scaffold)) { return new Scaffold(options); } Base.call(this); this.use(utils.plugins()); this.is('scaffold'); options = options || {}; this.options = options; this.targets = {}; if (Scaffold.isScaffold(options)) { this.options = {}; foward(this, options); this.addTargets(options); return this; } else { foward(this, options); } }
javascript
function Scaffold(options) { if (!(this instanceof Scaffold)) { return new Scaffold(options); } Base.call(this); this.use(utils.plugins()); this.is('scaffold'); options = options || {}; this.options = options; this.targets = {}; if (Scaffold.isScaffold(options)) { this.options = {}; foward(this, options); this.addTargets(options); return this; } else { foward(this, options); } }
[ "function", "Scaffold", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Scaffold", ")", ")", "{", "return", "new", "Scaffold", "(", "options", ")", ";", "}", "Base", ".", "call", "(", "this", ")", ";", "this", ".", "use", "(", "utils", ".", "plugins", "(", ")", ")", ";", "this", ".", "is", "(", "'scaffold'", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "options", "=", "options", ";", "this", ".", "targets", "=", "{", "}", ";", "if", "(", "Scaffold", ".", "isScaffold", "(", "options", ")", ")", "{", "this", ".", "options", "=", "{", "}", ";", "foward", "(", "this", ",", "options", ")", ";", "this", ".", "addTargets", "(", "options", ")", ";", "return", "this", ";", "}", "else", "{", "foward", "(", "this", ",", "options", ")", ";", "}", "}" ]
Create a new Scaffold with the given `options` ```js var scaffold = new Scaffold({cwd: 'src'}); scaffold.addTargets({ site: {src: ['*.hbs']}, blog: {src: ['*.md']} }); ``` @param {Object} `options` @api public
[ "Create", "a", "new", "Scaffold", "with", "the", "given", "options" ]
baa526928d0f7e0bcae266fbaa6174ddf4007a66
https://github.com/boilerplates/scaffold/blob/baa526928d0f7e0bcae266fbaa6174ddf4007a66/index.js#L28-L49
22,070
boilerplates/scaffold
index.js
foward
function foward(app, options) { if (typeof options.name === 'string') { app.name = options.name; delete options.name; } Scaffold.emit('scaffold', app); emit('target', app, Scaffold); emit('files', app, Scaffold); }
javascript
function foward(app, options) { if (typeof options.name === 'string') { app.name = options.name; delete options.name; } Scaffold.emit('scaffold', app); emit('target', app, Scaffold); emit('files', app, Scaffold); }
[ "function", "foward", "(", "app", ",", "options", ")", "{", "if", "(", "typeof", "options", ".", "name", "===", "'string'", ")", "{", "app", ".", "name", "=", "options", ".", "name", ";", "delete", "options", ".", "name", ";", "}", "Scaffold", ".", "emit", "(", "'scaffold'", ",", "app", ")", ";", "emit", "(", "'target'", ",", "app", ",", "Scaffold", ")", ";", "emit", "(", "'files'", ",", "app", ",", "Scaffold", ")", ";", "}" ]
Forward events from the scaffold instance to the `Scaffold` constructor
[ "Forward", "events", "from", "the", "scaffold", "instance", "to", "the", "Scaffold", "constructor" ]
baa526928d0f7e0bcae266fbaa6174ddf4007a66
https://github.com/boilerplates/scaffold/blob/baa526928d0f7e0bcae266fbaa6174ddf4007a66/index.js#L241-L249
22,071
boilerplates/scaffold
index.js
emit
function emit(name, a, b) { a.on(name, b.emit.bind(b, name)); }
javascript
function emit(name, a, b) { a.on(name, b.emit.bind(b, name)); }
[ "function", "emit", "(", "name", ",", "a", ",", "b", ")", "{", "a", ".", "on", "(", "name", ",", "b", ".", "emit", ".", "bind", "(", "b", ",", "name", ")", ")", ";", "}" ]
Forward events from emitter `a` to emitter `b`
[ "Forward", "events", "from", "emitter", "a", "to", "emitter", "b" ]
baa526928d0f7e0bcae266fbaa6174ddf4007a66
https://github.com/boilerplates/scaffold/blob/baa526928d0f7e0bcae266fbaa6174ddf4007a66/index.js#L255-L257
22,072
GoogleChrome/inert-polyfill
suite.js
sendTab
function sendTab(opt_shiftKey) { var ev = null; try { ev = new KeyboardEvent('keydown', { keyCode: 9, which: 9, key: 'Tab', code: 'Tab', keyIdentifier: 'U+0009', shiftKey: !!opt_shiftKey, bubbles: true }); } catch (e) { try { // Internet Explorer ev = document.createEvent('KeyboardEvent'); ev.initKeyboardEvent( 'keydown', true, true, window, 'Tab', 0, opt_shiftKey ? 'Shift' : '', false, 'en' ) } catch (e) {} } if (ev) { try { Object.defineProperty(ev, 'keyCode', { value: 9 }); } catch (e) {} document.dispatchEvent(ev); } }
javascript
function sendTab(opt_shiftKey) { var ev = null; try { ev = new KeyboardEvent('keydown', { keyCode: 9, which: 9, key: 'Tab', code: 'Tab', keyIdentifier: 'U+0009', shiftKey: !!opt_shiftKey, bubbles: true }); } catch (e) { try { // Internet Explorer ev = document.createEvent('KeyboardEvent'); ev.initKeyboardEvent( 'keydown', true, true, window, 'Tab', 0, opt_shiftKey ? 'Shift' : '', false, 'en' ) } catch (e) {} } if (ev) { try { Object.defineProperty(ev, 'keyCode', { value: 9 }); } catch (e) {} document.dispatchEvent(ev); } }
[ "function", "sendTab", "(", "opt_shiftKey", ")", "{", "var", "ev", "=", "null", ";", "try", "{", "ev", "=", "new", "KeyboardEvent", "(", "'keydown'", ",", "{", "keyCode", ":", "9", ",", "which", ":", "9", ",", "key", ":", "'Tab'", ",", "code", ":", "'Tab'", ",", "keyIdentifier", ":", "'U+0009'", ",", "shiftKey", ":", "!", "!", "opt_shiftKey", ",", "bubbles", ":", "true", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "try", "{", "// Internet Explorer", "ev", "=", "document", ".", "createEvent", "(", "'KeyboardEvent'", ")", ";", "ev", ".", "initKeyboardEvent", "(", "'keydown'", ",", "true", ",", "true", ",", "window", ",", "'Tab'", ",", "0", ",", "opt_shiftKey", "?", "'Shift'", ":", "''", ",", "false", ",", "'en'", ")", "}", "catch", "(", "e", ")", "{", "}", "}", "if", "(", "ev", ")", "{", "try", "{", "Object", ".", "defineProperty", "(", "ev", ",", "'keyCode'", ",", "{", "value", ":", "9", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "document", ".", "dispatchEvent", "(", "ev", ")", ";", "}", "}" ]
Sends a tab event on this document. Note that this is a copy of dispatchTabEvent from the polyfill source. @param {boolean=} opt_shiftKey whether to send this tab with shiftKey
[ "Sends", "a", "tab", "event", "on", "this", "document", ".", "Note", "that", "this", "is", "a", "copy", "of", "dispatchTabEvent", "from", "the", "polyfill", "source", "." ]
d307e9a64e3c8efaacf8fbe2efbdde8bbdf7a5e6
https://github.com/GoogleChrome/inert-polyfill/blob/d307e9a64e3c8efaacf8fbe2efbdde8bbdf7a5e6/suite.js#L26-L61
22,073
plepers/nanogl
program.js
function( vert, frag, prefix ){ this.ready = false; prefix = ( prefix === undefined ) ? '' : prefix+'\n'; var gl = this.gl; if( !( compileShader( gl, this.fShader, prefix + frag ) && compileShader( gl, this.vShader, prefix + vert ) ) ) { return false; } gl.linkProgram(this.program); if ( Program.debug && !gl.getProgramParameter(this.program, gl.LINK_STATUS)) { warn(gl.getProgramInfoLog(this.program)); return false; } // delete old accessors while (this.dyns.length>0) { delete this[this.dyns.pop()]; } this._cuid = (_UID++)|0; return true; }
javascript
function( vert, frag, prefix ){ this.ready = false; prefix = ( prefix === undefined ) ? '' : prefix+'\n'; var gl = this.gl; if( !( compileShader( gl, this.fShader, prefix + frag ) && compileShader( gl, this.vShader, prefix + vert ) ) ) { return false; } gl.linkProgram(this.program); if ( Program.debug && !gl.getProgramParameter(this.program, gl.LINK_STATUS)) { warn(gl.getProgramInfoLog(this.program)); return false; } // delete old accessors while (this.dyns.length>0) { delete this[this.dyns.pop()]; } this._cuid = (_UID++)|0; return true; }
[ "function", "(", "vert", ",", "frag", ",", "prefix", ")", "{", "this", ".", "ready", "=", "false", ";", "prefix", "=", "(", "prefix", "===", "undefined", ")", "?", "''", ":", "prefix", "+", "'\\n'", ";", "var", "gl", "=", "this", ".", "gl", ";", "if", "(", "!", "(", "compileShader", "(", "gl", ",", "this", ".", "fShader", ",", "prefix", "+", "frag", ")", "&&", "compileShader", "(", "gl", ",", "this", ".", "vShader", ",", "prefix", "+", "vert", ")", ")", ")", "{", "return", "false", ";", "}", "gl", ".", "linkProgram", "(", "this", ".", "program", ")", ";", "if", "(", "Program", ".", "debug", "&&", "!", "gl", ".", "getProgramParameter", "(", "this", ".", "program", ",", "gl", ".", "LINK_STATUS", ")", ")", "{", "warn", "(", "gl", ".", "getProgramInfoLog", "(", "this", ".", "program", ")", ")", ";", "return", "false", ";", "}", "// delete old accessors", "while", "(", "this", ".", "dyns", ".", "length", ">", "0", ")", "{", "delete", "this", "[", "this", ".", "dyns", ".", "pop", "(", ")", "]", ";", "}", "this", ".", "_cuid", "=", "(", "_UID", "++", ")", "|", "0", ";", "return", "true", ";", "}" ]
Compile vertex and fragment shader then link gl program This method can be safely called several times. @param {String} vert vertex shader code @param {String} frag fragment shader code @param {String} [prefix=''] an optional string append to both fragment and vertex code
[ "Compile", "vertex", "and", "fragment", "shader", "then", "link", "gl", "program", "This", "method", "can", "be", "safely", "called", "several", "times", "." ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/program.js#L69-L96
22,074
plepers/nanogl
program.js
function() { if( this.gl !== null ){ this.gl.deleteProgram( this.program ); this.gl.deleteShader( this.fShader ); this.gl.deleteShader( this.vShader ); this.gl = null; } }
javascript
function() { if( this.gl !== null ){ this.gl.deleteProgram( this.program ); this.gl.deleteShader( this.fShader ); this.gl.deleteShader( this.vShader ); this.gl = null; } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "gl", "!==", "null", ")", "{", "this", ".", "gl", ".", "deleteProgram", "(", "this", ".", "program", ")", ";", "this", ".", "gl", ".", "deleteShader", "(", "this", ".", "fShader", ")", ";", "this", ".", "gl", ".", "deleteShader", "(", "this", ".", "vShader", ")", ";", "this", ".", "gl", "=", "null", ";", "}", "}" ]
Delete program and shaders
[ "Delete", "program", "and", "shaders" ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/program.js#L101-L108
22,075
plepers/nanogl
texture.js
function( format, type, internal ){ this.format = format || this.gl.RGB; this.internal = internal || this.format; this.type = type || this.gl.UNSIGNED_BYTE; }
javascript
function( format, type, internal ){ this.format = format || this.gl.RGB; this.internal = internal || this.format; this.type = type || this.gl.UNSIGNED_BYTE; }
[ "function", "(", "format", ",", "type", ",", "internal", ")", "{", "this", ".", "format", "=", "format", "||", "this", ".", "gl", ".", "RGB", ";", "this", ".", "internal", "=", "internal", "||", "this", ".", "format", ";", "this", ".", "type", "=", "type", "||", "this", ".", "gl", ".", "UNSIGNED_BYTE", ";", "}" ]
define underlying format, internal format and data type of texture @param {GLenum} [format =GL_RGB] the pixel format, default to gl.RGB (can be gl.RGB, gl.RGBA, gl.LUMINANCE...) @param {GLenum} [type =GL_UNSIGNED_BYTE] the pixel data type, default to gl.UNSIGNED_BYTE @param {GLenum} [internal=format] the pixel internal format, default to the same value than 'format' parameter (which must be in webgl 1)
[ "define", "underlying", "format", "internal", "format", "and", "data", "type", "of", "texture" ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/texture.js#L50-L54
22,076
plepers/nanogl
texture.js
function( img ){ var gl = this.gl; this.width = img.width; this.height = img.height; gl.bindTexture( T2D, this.id ); gl.texImage2D( T2D, 0, this.internal, this.format, this.type, img ); }
javascript
function( img ){ var gl = this.gl; this.width = img.width; this.height = img.height; gl.bindTexture( T2D, this.id ); gl.texImage2D( T2D, 0, this.internal, this.format, this.type, img ); }
[ "function", "(", "img", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "this", ".", "width", "=", "img", ".", "width", ";", "this", ".", "height", "=", "img", ".", "height", ";", "gl", ".", "bindTexture", "(", "T2D", ",", "this", ".", "id", ")", ";", "gl", ".", "texImage2D", "(", "T2D", ",", "0", ",", "this", ".", "internal", ",", "this", ".", "format", ",", "this", ".", "type", ",", "img", ")", ";", "}" ]
set texture data from html source @param {TexImageSource} img the source. Can be ImageBitmap, ImageData, HTMLImageElement, HTMLCanvasElement, HTMLVideoElement
[ "set", "texture", "data", "from", "html", "source" ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/texture.js#L60-L68
22,077
plepers/nanogl
texture.js
function( unit ){ var gl = this.gl; if( unit !== undefined ){ gl.activeTexture( gl.TEXTURE0 + (0|unit) ); } gl.bindTexture( T2D, this.id ); }
javascript
function( unit ){ var gl = this.gl; if( unit !== undefined ){ gl.activeTexture( gl.TEXTURE0 + (0|unit) ); } gl.bindTexture( T2D, this.id ); }
[ "function", "(", "unit", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "if", "(", "unit", "!==", "undefined", ")", "{", "gl", ".", "activeTexture", "(", "gl", ".", "TEXTURE0", "+", "(", "0", "|", "unit", ")", ")", ";", "}", "gl", ".", "bindTexture", "(", "T2D", ",", "this", ".", "id", ")", ";", "}" ]
Bind the texture @param {uint} [unit=undefined] optional texture unit to make active before binding
[ "Bind", "the", "texture" ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/texture.js#L93-L99
22,078
plepers/nanogl
arraybuffer.js
function( array ){ var gl = this.gl; gl.bindBuffer( TGT, this.buffer ); gl.bufferData( TGT, array, this.usage ); gl.bindBuffer( TGT, null ); this.byteLength = ( array.byteLength === undefined ) ? array : array.byteLength; this._computeLength(); }
javascript
function( array ){ var gl = this.gl; gl.bindBuffer( TGT, this.buffer ); gl.bufferData( TGT, array, this.usage ); gl.bindBuffer( TGT, null ); this.byteLength = ( array.byteLength === undefined ) ? array : array.byteLength; this._computeLength(); }
[ "function", "(", "array", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "gl", ".", "bindBuffer", "(", "TGT", ",", "this", ".", "buffer", ")", ";", "gl", ".", "bufferData", "(", "TGT", ",", "array", ",", "this", ".", "usage", ")", ";", "gl", ".", "bindBuffer", "(", "TGT", ",", "null", ")", ";", "this", ".", "byteLength", "=", "(", "array", ".", "byteLength", "===", "undefined", ")", "?", "array", ":", "array", ".", "byteLength", ";", "this", ".", "_computeLength", "(", ")", ";", "}" ]
Fill webgl buffer with the given data. You can also pass a uint to allocate the buffer to the given size. @param {TypedArray|uint} array the data to send to the buffer, or a size.
[ "Fill", "webgl", "buffer", "with", "the", "given", "data", ".", "You", "can", "also", "pass", "a", "uint", "to", "allocate", "the", "buffer", "to", "the", "given", "size", "." ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/arraybuffer.js#L66-L74
22,079
plepers/nanogl
fbo.js
function( format, type, internal ){ var t = new Texture( this.gl, format, type, internal ); return this.attach( 0x8CE0, t ); }
javascript
function( format, type, internal ){ var t = new Texture( this.gl, format, type, internal ); return this.attach( 0x8CE0, t ); }
[ "function", "(", "format", ",", "type", ",", "internal", ")", "{", "var", "t", "=", "new", "Texture", "(", "this", ".", "gl", ",", "format", ",", "type", ",", "internal", ")", ";", "return", "this", ".", "attach", "(", "0x8CE0", ",", "t", ")", ";", "}" ]
Shortcut to attach texture to color attachment 0
[ "Shortcut", "to", "attach", "texture", "to", "color", "attachment", "0" ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/fbo.js#L149-L152
22,080
plepers/nanogl
fbo.js
function( w, h ){ if( this.width !== w || this.height !== h ) { this.width = w|0; this.height = h|0; this._allocate(); } }
javascript
function( w, h ){ if( this.width !== w || this.height !== h ) { this.width = w|0; this.height = h|0; this._allocate(); } }
[ "function", "(", "w", ",", "h", ")", "{", "if", "(", "this", ".", "width", "!==", "w", "||", "this", ".", "height", "!==", "h", ")", "{", "this", ".", "width", "=", "w", "|", "0", ";", "this", ".", "height", "=", "h", "|", "0", ";", "this", ".", "_allocate", "(", ")", ";", "}", "}" ]
Resize FBO attachments @param {uint} w new width @param {uint} h new height
[ "Resize", "FBO", "attachments" ]
7cdf82ffe7bbb3121d2a999e98373832cecd112c
https://github.com/plepers/nanogl/blob/7cdf82ffe7bbb3121d2a999e98373832cecd112c/fbo.js#L185-L191
22,081
goddyZhao/nproxy
lib/middlewares/respond.js
_watchRuleFile
function _watchRuleFile(file, callback){ fs.watchFile(file, function(curr, prev){ log.warn('The rule file has been modified!'); callback(); }); }
javascript
function _watchRuleFile(file, callback){ fs.watchFile(file, function(curr, prev){ log.warn('The rule file has been modified!'); callback(); }); }
[ "function", "_watchRuleFile", "(", "file", ",", "callback", ")", "{", "fs", ".", "watchFile", "(", "file", ",", "function", "(", "curr", ",", "prev", ")", "{", "log", ".", "warn", "(", "'The rule file has been modified!'", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Watch the rule file to support applying changed rules without restart the proxy @param {String} file the path of the file @param {Function} callback
[ "Watch", "the", "rule", "file", "to", "support", "applying", "changed", "rules", "without", "restart", "the", "proxy" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/middlewares/respond.js#L174-L179
22,082
goddyZhao/nproxy
lib/middlewares/respond.js
_loadResponderList
function _loadResponderList(responderListFilePath){ var filePath = responderListFilePath; if(typeof filePath !== 'string'){ return null; } if(!fs.existsSync(responderListFilePath)){ throw new Error('File doesn\'t exist!'); } if(!utils.isAbsolutePath(responderListFilePath)){ filePath = path.join(process.cwd(), filePath); } return _loadFile(filePath); }
javascript
function _loadResponderList(responderListFilePath){ var filePath = responderListFilePath; if(typeof filePath !== 'string'){ return null; } if(!fs.existsSync(responderListFilePath)){ throw new Error('File doesn\'t exist!'); } if(!utils.isAbsolutePath(responderListFilePath)){ filePath = path.join(process.cwd(), filePath); } return _loadFile(filePath); }
[ "function", "_loadResponderList", "(", "responderListFilePath", ")", "{", "var", "filePath", "=", "responderListFilePath", ";", "if", "(", "typeof", "filePath", "!==", "'string'", ")", "{", "return", "null", ";", "}", "if", "(", "!", "fs", ".", "existsSync", "(", "responderListFilePath", ")", ")", "{", "throw", "new", "Error", "(", "'File doesn\\'t exist!'", ")", ";", "}", "if", "(", "!", "utils", ".", "isAbsolutePath", "(", "responderListFilePath", ")", ")", "{", "filePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "filePath", ")", ";", "}", "return", "_loadFile", "(", "filePath", ")", ";", "}" ]
Load the list file and return the list object @param {String} responderListFilePath @return {Array} responder list @api private
[ "Load", "the", "list", "file", "and", "return", "the", "list", "object" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/middlewares/respond.js#L189-L205
22,083
goddyZhao/nproxy
lib/middlewares/respond.js
_loadFile
function _loadFile(filename){ var module = require(filename); delete require.cache[require.resolve(filename)]; return module; }
javascript
function _loadFile(filename){ var module = require(filename); delete require.cache[require.resolve(filename)]; return module; }
[ "function", "_loadFile", "(", "filename", ")", "{", "var", "module", "=", "require", "(", "filename", ")", ";", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "filename", ")", "]", ";", "return", "module", ";", "}" ]
Load file without cache @return {Array} load list from a file
[ "Load", "file", "without", "cache" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/middlewares/respond.js#L212-L216
22,084
goddyZhao/nproxy
lib/nproxy.js
nproxy
function nproxy(port, options){ var nm; if(typeof options.timeout === 'number'){ utils.reqTimeout = options.timeout; utils.resTimeout = options.timeout; } if(typeof options.debug === 'boolean'){ log.isDebug = options.debug; } nm = require('./middlewares'); //nproxy middles port = typeof port === 'number' ? port : DEFAULT_PORT; app = connect(); if(typeof options.responderListFilePath !== 'undefined'){ app.use(nm.respond(options.responderListFilePath)); } app.use(nm.forward()); httpServer = http.createServer(function(req, res){ req.type = 'http'; app(req, res); }).listen(port); proxyHttps(); log.info('NProxy started on ' + port + '!'); if (options.networks) { log.info('Network interfaces:'); var interfaces = require('os').networkInterfaces(); for (var key in interfaces) { log.info(key); interfaces[key].forEach(function (item) { log.info(' ' + item.address + '\t' + item.family); }); } } return { httpServer: httpServer }; }
javascript
function nproxy(port, options){ var nm; if(typeof options.timeout === 'number'){ utils.reqTimeout = options.timeout; utils.resTimeout = options.timeout; } if(typeof options.debug === 'boolean'){ log.isDebug = options.debug; } nm = require('./middlewares'); //nproxy middles port = typeof port === 'number' ? port : DEFAULT_PORT; app = connect(); if(typeof options.responderListFilePath !== 'undefined'){ app.use(nm.respond(options.responderListFilePath)); } app.use(nm.forward()); httpServer = http.createServer(function(req, res){ req.type = 'http'; app(req, res); }).listen(port); proxyHttps(); log.info('NProxy started on ' + port + '!'); if (options.networks) { log.info('Network interfaces:'); var interfaces = require('os').networkInterfaces(); for (var key in interfaces) { log.info(key); interfaces[key].forEach(function (item) { log.info(' ' + item.address + '\t' + item.family); }); } } return { httpServer: httpServer }; }
[ "function", "nproxy", "(", "port", ",", "options", ")", "{", "var", "nm", ";", "if", "(", "typeof", "options", ".", "timeout", "===", "'number'", ")", "{", "utils", ".", "reqTimeout", "=", "options", ".", "timeout", ";", "utils", ".", "resTimeout", "=", "options", ".", "timeout", ";", "}", "if", "(", "typeof", "options", ".", "debug", "===", "'boolean'", ")", "{", "log", ".", "isDebug", "=", "options", ".", "debug", ";", "}", "nm", "=", "require", "(", "'./middlewares'", ")", ";", "//nproxy middles", "port", "=", "typeof", "port", "===", "'number'", "?", "port", ":", "DEFAULT_PORT", ";", "app", "=", "connect", "(", ")", ";", "if", "(", "typeof", "options", ".", "responderListFilePath", "!==", "'undefined'", ")", "{", "app", ".", "use", "(", "nm", ".", "respond", "(", "options", ".", "responderListFilePath", ")", ")", ";", "}", "app", ".", "use", "(", "nm", ".", "forward", "(", ")", ")", ";", "httpServer", "=", "http", ".", "createServer", "(", "function", "(", "req", ",", "res", ")", "{", "req", ".", "type", "=", "'http'", ";", "app", "(", "req", ",", "res", ")", ";", "}", ")", ".", "listen", "(", "port", ")", ";", "proxyHttps", "(", ")", ";", "log", ".", "info", "(", "'NProxy started on '", "+", "port", "+", "'!'", ")", ";", "if", "(", "options", ".", "networks", ")", "{", "log", ".", "info", "(", "'Network interfaces:'", ")", ";", "var", "interfaces", "=", "require", "(", "'os'", ")", ".", "networkInterfaces", "(", ")", ";", "for", "(", "var", "key", "in", "interfaces", ")", "{", "log", ".", "info", "(", "key", ")", ";", "interfaces", "[", "key", "]", ".", "forEach", "(", "function", "(", "item", ")", "{", "log", ".", "info", "(", "' '", "+", "item", ".", "address", "+", "'\\t'", "+", "item", ".", "family", ")", ";", "}", ")", ";", "}", "}", "return", "{", "httpServer", ":", "httpServer", "}", ";", "}" ]
Start up nproxy server on the specified port and combine the processors defined as connect middlewares into it. @param {String} port the port proxy server will listen on @param {Object} options options for the middlewares
[ "Start", "up", "nproxy", "server", "on", "the", "specified", "port", "and", "combine", "the", "processors", "defined", "as", "connect", "middlewares", "into", "it", "." ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/nproxy.js#L30-L75
22,085
goddyZhao/nproxy
lib/nproxy.js
proxyHttps
function proxyHttps(){ httpServer.on('connect', function(req, socket, upgradeHead){ var hostname = req.url.split(':')[0]; log.debug('Create internal https server for ' + hostname); createInternalHttpsServer(hostname, function (err, httpsServerPort) { if (err) { log.error('Failed to create internal https proxy'); log.error(err); return; } // get proxy https server var netClient = net.createConnection(httpsServerPort); netClient.on('connect', function(){ log.info('connect to https server successfully!'); socket.write( "HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n"); }); socket.on('data', function(chunk){ netClient.write(chunk); }); socket.on('end', function(){ netClient.end(); }); socket.on('close', function(){ netClient.end(); }); socket.on('error', function(err){ log.error('socket error ' + err.message); netClient.end(); }); netClient.on('data', function(chunk){ socket.write(chunk); }); netClient.on('end', function(){ socket.end(); }); netClient.on('close', function(){ socket.end(); }); netClient.on('error', function(err){ log.error('netClient error ' + err.message); socket.end(); }); }); }); }
javascript
function proxyHttps(){ httpServer.on('connect', function(req, socket, upgradeHead){ var hostname = req.url.split(':')[0]; log.debug('Create internal https server for ' + hostname); createInternalHttpsServer(hostname, function (err, httpsServerPort) { if (err) { log.error('Failed to create internal https proxy'); log.error(err); return; } // get proxy https server var netClient = net.createConnection(httpsServerPort); netClient.on('connect', function(){ log.info('connect to https server successfully!'); socket.write( "HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n"); }); socket.on('data', function(chunk){ netClient.write(chunk); }); socket.on('end', function(){ netClient.end(); }); socket.on('close', function(){ netClient.end(); }); socket.on('error', function(err){ log.error('socket error ' + err.message); netClient.end(); }); netClient.on('data', function(chunk){ socket.write(chunk); }); netClient.on('end', function(){ socket.end(); }); netClient.on('close', function(){ socket.end(); }); netClient.on('error', function(err){ log.error('netClient error ' + err.message); socket.end(); }); }); }); }
[ "function", "proxyHttps", "(", ")", "{", "httpServer", ".", "on", "(", "'connect'", ",", "function", "(", "req", ",", "socket", ",", "upgradeHead", ")", "{", "var", "hostname", "=", "req", ".", "url", ".", "split", "(", "':'", ")", "[", "0", "]", ";", "log", ".", "debug", "(", "'Create internal https server for '", "+", "hostname", ")", ";", "createInternalHttpsServer", "(", "hostname", ",", "function", "(", "err", ",", "httpsServerPort", ")", "{", "if", "(", "err", ")", "{", "log", ".", "error", "(", "'Failed to create internal https proxy'", ")", ";", "log", ".", "error", "(", "err", ")", ";", "return", ";", "}", "// get proxy https server", "var", "netClient", "=", "net", ".", "createConnection", "(", "httpsServerPort", ")", ";", "netClient", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "log", ".", "info", "(", "'connect to https server successfully!'", ")", ";", "socket", ".", "write", "(", "\"HTTP/1.1 200 Connection established\\r\\nProxy-agent: Netscape-Proxy/1.1\\r\\n\\r\\n\"", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "netClient", ".", "write", "(", "chunk", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "netClient", ".", "end", "(", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "netClient", ".", "end", "(", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "log", ".", "error", "(", "'socket error '", "+", "err", ".", "message", ")", ";", "netClient", ".", "end", "(", ")", ";", "}", ")", ";", "netClient", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "socket", ".", "write", "(", "chunk", ")", ";", "}", ")", ";", "netClient", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "socket", ".", "end", "(", ")", ";", "}", ")", ";", "netClient", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "socket", ".", "end", "(", ")", ";", "}", ")", ";", "netClient", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "log", ".", "error", "(", "'netClient error '", "+", "err", ".", "message", ")", ";", "socket", ".", "end", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Listen the CONNECTION method and forward the https request to internal https server
[ "Listen", "the", "CONNECTION", "method", "and", "forward", "the", "https", "request", "to", "internal", "https", "server" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/nproxy.js#L120-L167
22,086
goddyZhao/nproxy
lib/agent.js
getAgentByUrl
function getAgentByUrl (requestUrl) { if (!requestUrl) { return null; } var parsedRequestUrl = url.parse(requestUrl); var proxyUrl = getSystemProxyByUrl(parsedRequestUrl); if (!proxyUrl) { log.debug('No system proxy'); return null; } log.debug('Detect system proxy Url: ' + proxyUrl); var parsedProxyUrl = url.parse(proxyUrl); var tunnelOptions = getTunnelOptionsByProxy(parsedProxyUrl, parsedRequestUrl); if (tunnelOptions) { var tunnelFnName = getTunnelFnName(parsedProxyUrl, parsedRequestUrl); log.debug('Tunnel name is ' + tunnelFnName); return tunnel[tunnelFnName](tunnelOptions); } }
javascript
function getAgentByUrl (requestUrl) { if (!requestUrl) { return null; } var parsedRequestUrl = url.parse(requestUrl); var proxyUrl = getSystemProxyByUrl(parsedRequestUrl); if (!proxyUrl) { log.debug('No system proxy'); return null; } log.debug('Detect system proxy Url: ' + proxyUrl); var parsedProxyUrl = url.parse(proxyUrl); var tunnelOptions = getTunnelOptionsByProxy(parsedProxyUrl, parsedRequestUrl); if (tunnelOptions) { var tunnelFnName = getTunnelFnName(parsedProxyUrl, parsedRequestUrl); log.debug('Tunnel name is ' + tunnelFnName); return tunnel[tunnelFnName](tunnelOptions); } }
[ "function", "getAgentByUrl", "(", "requestUrl", ")", "{", "if", "(", "!", "requestUrl", ")", "{", "return", "null", ";", "}", "var", "parsedRequestUrl", "=", "url", ".", "parse", "(", "requestUrl", ")", ";", "var", "proxyUrl", "=", "getSystemProxyByUrl", "(", "parsedRequestUrl", ")", ";", "if", "(", "!", "proxyUrl", ")", "{", "log", ".", "debug", "(", "'No system proxy'", ")", ";", "return", "null", ";", "}", "log", ".", "debug", "(", "'Detect system proxy Url: '", "+", "proxyUrl", ")", ";", "var", "parsedProxyUrl", "=", "url", ".", "parse", "(", "proxyUrl", ")", ";", "var", "tunnelOptions", "=", "getTunnelOptionsByProxy", "(", "parsedProxyUrl", ",", "parsedRequestUrl", ")", ";", "if", "(", "tunnelOptions", ")", "{", "var", "tunnelFnName", "=", "getTunnelFnName", "(", "parsedProxyUrl", ",", "parsedRequestUrl", ")", ";", "log", ".", "debug", "(", "'Tunnel name is '", "+", "tunnelFnName", ")", ";", "return", "tunnel", "[", "tunnelFnName", "]", "(", "tunnelOptions", ")", ";", "}", "}" ]
Get agent only if it has system proxy
[ "Get", "agent", "only", "if", "it", "has", "system", "proxy" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/agent.js#L40-L59
22,087
goddyZhao/nproxy
lib/cert.js
_checkRootCA
function _checkRootCA () { var caKeyFilePath = path.join(certDir, 'ca.key'); var caCrtFilePath = path.join(certDir, 'ca.crt'); var keysDir = path.join(__dirname, '..', 'keys'); if (!fs.existsSync(caKeyFilePath) || !fs.existsSync(caCrtFilePath)) { log.debug('CA files do not exist'); log.debug('Copy CA files'); fse.copySync(path.join(keysDir, 'ca.key'), caKeyFilePath); fse.copySync(path.join(keysDir, 'ca.crt'), caCrtFilePath); } }
javascript
function _checkRootCA () { var caKeyFilePath = path.join(certDir, 'ca.key'); var caCrtFilePath = path.join(certDir, 'ca.crt'); var keysDir = path.join(__dirname, '..', 'keys'); if (!fs.existsSync(caKeyFilePath) || !fs.existsSync(caCrtFilePath)) { log.debug('CA files do not exist'); log.debug('Copy CA files'); fse.copySync(path.join(keysDir, 'ca.key'), caKeyFilePath); fse.copySync(path.join(keysDir, 'ca.crt'), caCrtFilePath); } }
[ "function", "_checkRootCA", "(", ")", "{", "var", "caKeyFilePath", "=", "path", ".", "join", "(", "certDir", ",", "'ca.key'", ")", ";", "var", "caCrtFilePath", "=", "path", ".", "join", "(", "certDir", ",", "'ca.crt'", ")", ";", "var", "keysDir", "=", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'keys'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "caKeyFilePath", ")", "||", "!", "fs", ".", "existsSync", "(", "caCrtFilePath", ")", ")", "{", "log", ".", "debug", "(", "'CA files do not exist'", ")", ";", "log", ".", "debug", "(", "'Copy CA files'", ")", ";", "fse", ".", "copySync", "(", "path", ".", "join", "(", "keysDir", ",", "'ca.key'", ")", ",", "caKeyFilePath", ")", ";", "fse", ".", "copySync", "(", "path", ".", "join", "(", "keysDir", ",", "'ca.crt'", ")", ",", "caCrtFilePath", ")", ";", "}", "}" ]
Check the ca files Copy them if they does not exist
[ "Check", "the", "ca", "files" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/cert.js#L64-L76
22,088
goddyZhao/nproxy
lib/middlewares/forward.js
forward
function forward(){ return function forward(req, res, next){ var url = utils.processUrl(req); var options = { url: url, method: req.method, headers: req.headers } var buffers = []; log.debug('forward: ' + url); if(req.method === 'POST'){ req.on('data', function(chunk){ buffers.push(chunk); }); req.on('end', function(){ options.data = Buffer.concat(buffers); utils.request(options, function(err, data, proxyRes){ _forwardHandler(err, data, proxyRes, res); }); }); }else{ utils.request(options, function(err, data, proxyRes){ _forwardHandler(err, data, proxyRes, res) }); } }; }
javascript
function forward(){ return function forward(req, res, next){ var url = utils.processUrl(req); var options = { url: url, method: req.method, headers: req.headers } var buffers = []; log.debug('forward: ' + url); if(req.method === 'POST'){ req.on('data', function(chunk){ buffers.push(chunk); }); req.on('end', function(){ options.data = Buffer.concat(buffers); utils.request(options, function(err, data, proxyRes){ _forwardHandler(err, data, proxyRes, res); }); }); }else{ utils.request(options, function(err, data, proxyRes){ _forwardHandler(err, data, proxyRes, res) }); } }; }
[ "function", "forward", "(", ")", "{", "return", "function", "forward", "(", "req", ",", "res", ",", "next", ")", "{", "var", "url", "=", "utils", ".", "processUrl", "(", "req", ")", ";", "var", "options", "=", "{", "url", ":", "url", ",", "method", ":", "req", ".", "method", ",", "headers", ":", "req", ".", "headers", "}", "var", "buffers", "=", "[", "]", ";", "log", ".", "debug", "(", "'forward: '", "+", "url", ")", ";", "if", "(", "req", ".", "method", "===", "'POST'", ")", "{", "req", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "buffers", ".", "push", "(", "chunk", ")", ";", "}", ")", ";", "req", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "options", ".", "data", "=", "Buffer", ".", "concat", "(", "buffers", ")", ";", "utils", ".", "request", "(", "options", ",", "function", "(", "err", ",", "data", ",", "proxyRes", ")", "{", "_forwardHandler", "(", "err", ",", "data", ",", "proxyRes", ",", "res", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "utils", ".", "request", "(", "options", ",", "function", "(", "err", ",", "data", ",", "proxyRes", ")", "{", "_forwardHandler", "(", "err", ",", "data", ",", "proxyRes", ",", "res", ")", "}", ")", ";", "}", "}", ";", "}" ]
Forward the request directly
[ "Forward", "the", "request", "directly" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/middlewares/forward.js#L8-L37
22,089
goddyZhao/nproxy
lib/middlewares/responders/combo.js
respondFromCombo
function respondFromCombo(options, req, res, next){ var dir; var src; if(typeof options !== 'object' || typeof options === null){ log.warn('Options are invalid when responding from combo!'); next(); } dir = typeof options.dir === 'undefined' ? null : options.dir; src = Array.isArray(options.src) ? options.src : []; if(dir !== null){ try{ fs.statSync(dir); }catch(e){ throw e; } src = src.map(function(file){ return path.join(dir, file); }); } //Read the local files and concat together if(src.length > 0){ utils.concat(src, function(err, data){ if(err){ throw err; } res.statusCode = 200; res.setHeader('Content-Length', data.length); res.setHeader('Content-Type', mime.lookup(src[0])); res.setHeader('Server', 'nproxy'); res.write(data); res.end(); }); } }
javascript
function respondFromCombo(options, req, res, next){ var dir; var src; if(typeof options !== 'object' || typeof options === null){ log.warn('Options are invalid when responding from combo!'); next(); } dir = typeof options.dir === 'undefined' ? null : options.dir; src = Array.isArray(options.src) ? options.src : []; if(dir !== null){ try{ fs.statSync(dir); }catch(e){ throw e; } src = src.map(function(file){ return path.join(dir, file); }); } //Read the local files and concat together if(src.length > 0){ utils.concat(src, function(err, data){ if(err){ throw err; } res.statusCode = 200; res.setHeader('Content-Length', data.length); res.setHeader('Content-Type', mime.lookup(src[0])); res.setHeader('Server', 'nproxy'); res.write(data); res.end(); }); } }
[ "function", "respondFromCombo", "(", "options", ",", "req", ",", "res", ",", "next", ")", "{", "var", "dir", ";", "var", "src", ";", "if", "(", "typeof", "options", "!==", "'object'", "||", "typeof", "options", "===", "null", ")", "{", "log", ".", "warn", "(", "'Options are invalid when responding from combo!'", ")", ";", "next", "(", ")", ";", "}", "dir", "=", "typeof", "options", ".", "dir", "===", "'undefined'", "?", "null", ":", "options", ".", "dir", ";", "src", "=", "Array", ".", "isArray", "(", "options", ".", "src", ")", "?", "options", ".", "src", ":", "[", "]", ";", "if", "(", "dir", "!==", "null", ")", "{", "try", "{", "fs", ".", "statSync", "(", "dir", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "e", ";", "}", "src", "=", "src", ".", "map", "(", "function", "(", "file", ")", "{", "return", "path", ".", "join", "(", "dir", ",", "file", ")", ";", "}", ")", ";", "}", "//Read the local files and concat together", "if", "(", "src", ".", "length", ">", "0", ")", "{", "utils", ".", "concat", "(", "src", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "res", ".", "statusCode", "=", "200", ";", "res", ".", "setHeader", "(", "'Content-Length'", ",", "data", ".", "length", ")", ";", "res", ".", "setHeader", "(", "'Content-Type'", ",", "mime", ".", "lookup", "(", "src", "[", "0", "]", ")", ")", ";", "res", ".", "setHeader", "(", "'Server'", ",", "'nproxy'", ")", ";", "res", ".", "write", "(", "data", ")", ";", "res", ".", "end", "(", ")", ";", "}", ")", ";", "}", "}" ]
respond the request following the algorithm 1. Read the file content according to the configured src list 2. Concat them into a file 3. Respond the file to the request @param {Object} options dir and source file lists {dir: String, src: Array} @param {Object} req request @param {Object} res response @param {Object} next next
[ "respond", "the", "request", "following", "the", "algorithm" ]
e0af30c0edb7adc6e611ea90428d0f83d175d50d
https://github.com/goddyZhao/nproxy/blob/e0af30c0edb7adc6e611ea90428d0f83d175d50d/lib/middlewares/responders/combo.js#L20-L58
22,090
expressjs/response-time
index.js
responseTime
function responseTime (options) { var opts = options || {} if (typeof options === 'number') { // back-compat single number argument deprecate('number argument: use {digits: ' + JSON.stringify(options) + '} instead') opts = { digits: options } } // get the function to invoke var fn = typeof opts !== 'function' ? createSetHeader(opts) : opts return function responseTime (req, res, next) { var startAt = process.hrtime() onHeaders(res, function onHeaders () { var diff = process.hrtime(startAt) var time = diff[0] * 1e3 + diff[1] * 1e-6 fn(req, res, time) }) next() } }
javascript
function responseTime (options) { var opts = options || {} if (typeof options === 'number') { // back-compat single number argument deprecate('number argument: use {digits: ' + JSON.stringify(options) + '} instead') opts = { digits: options } } // get the function to invoke var fn = typeof opts !== 'function' ? createSetHeader(opts) : opts return function responseTime (req, res, next) { var startAt = process.hrtime() onHeaders(res, function onHeaders () { var diff = process.hrtime(startAt) var time = diff[0] * 1e3 + diff[1] * 1e-6 fn(req, res, time) }) next() } }
[ "function", "responseTime", "(", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", "if", "(", "typeof", "options", "===", "'number'", ")", "{", "// back-compat single number argument", "deprecate", "(", "'number argument: use {digits: '", "+", "JSON", ".", "stringify", "(", "options", ")", "+", "'} instead'", ")", "opts", "=", "{", "digits", ":", "options", "}", "}", "// get the function to invoke", "var", "fn", "=", "typeof", "opts", "!==", "'function'", "?", "createSetHeader", "(", "opts", ")", ":", "opts", "return", "function", "responseTime", "(", "req", ",", "res", ",", "next", ")", "{", "var", "startAt", "=", "process", ".", "hrtime", "(", ")", "onHeaders", "(", "res", ",", "function", "onHeaders", "(", ")", "{", "var", "diff", "=", "process", ".", "hrtime", "(", "startAt", ")", "var", "time", "=", "diff", "[", "0", "]", "*", "1e3", "+", "diff", "[", "1", "]", "*", "1e-6", "fn", "(", "req", ",", "res", ",", "time", ")", "}", ")", "next", "(", ")", "}", "}" ]
Create a middleware to add a `X-Response-Time` header displaying the response duration in milliseconds. @param {object|function} [options] @param {number} [options.digits=3] @param {string} [options.header=X-Response-Time] @param {boolean} [options.suffix=true] @return {function} @public
[ "Create", "a", "middleware", "to", "add", "a", "X", "-", "Response", "-", "Time", "header", "displaying", "the", "response", "duration", "in", "milliseconds", "." ]
5b396e3c87420bdc5a1bd283495de54d4ded4abf
https://github.com/expressjs/response-time/blob/5b396e3c87420bdc5a1bd283495de54d4ded4abf/index.js#L38-L64
22,091
expressjs/response-time
index.js
createSetHeader
function createSetHeader (options) { // response time digits var digits = options.digits !== undefined ? options.digits : 3 // header name var header = options.header || 'X-Response-Time' // display suffix var suffix = options.suffix !== undefined ? Boolean(options.suffix) : true return function setResponseHeader (req, res, time) { if (res.getHeader(header)) { return } var val = time.toFixed(digits) if (suffix) { val += 'ms' } res.setHeader(header, val) } }
javascript
function createSetHeader (options) { // response time digits var digits = options.digits !== undefined ? options.digits : 3 // header name var header = options.header || 'X-Response-Time' // display suffix var suffix = options.suffix !== undefined ? Boolean(options.suffix) : true return function setResponseHeader (req, res, time) { if (res.getHeader(header)) { return } var val = time.toFixed(digits) if (suffix) { val += 'ms' } res.setHeader(header, val) } }
[ "function", "createSetHeader", "(", "options", ")", "{", "// response time digits", "var", "digits", "=", "options", ".", "digits", "!==", "undefined", "?", "options", ".", "digits", ":", "3", "// header name", "var", "header", "=", "options", ".", "header", "||", "'X-Response-Time'", "// display suffix", "var", "suffix", "=", "options", ".", "suffix", "!==", "undefined", "?", "Boolean", "(", "options", ".", "suffix", ")", ":", "true", "return", "function", "setResponseHeader", "(", "req", ",", "res", ",", "time", ")", "{", "if", "(", "res", ".", "getHeader", "(", "header", ")", ")", "{", "return", "}", "var", "val", "=", "time", ".", "toFixed", "(", "digits", ")", "if", "(", "suffix", ")", "{", "val", "+=", "'ms'", "}", "res", ".", "setHeader", "(", "header", ",", "val", ")", "}", "}" ]
Create function to set respoonse time header. @private
[ "Create", "function", "to", "set", "respoonse", "time", "header", "." ]
5b396e3c87420bdc5a1bd283495de54d4ded4abf
https://github.com/expressjs/response-time/blob/5b396e3c87420bdc5a1bd283495de54d4ded4abf/index.js#L71-L98
22,092
gerhardberger/electron-pdf-window
pdfjs/web/l10n.js
translateElement
function translateElement(element) { var l10n = getL10nAttributes(element); if (!l10n.id) return; // get the related l10n object var data = getL10nData(l10n.id, l10n.args); if (!data) { console.warn('#' + l10n.id + ' is undefined.'); return; } // translate element (TODO: security checks?) if (data[gTextProp]) { // XXX if (getChildElementCount(element) === 0) { element[gTextProp] = data[gTextProp]; } else { // this element has element children: replace the content of the first // (non-empty) child textNode and clear other child textNodes var children = element.childNodes; var found = false; for (var i = 0, l = children.length; i < l; i++) { if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) { if (found) { children[i].nodeValue = ''; } else { children[i].nodeValue = data[gTextProp]; found = true; } } } // if no (non-empty) textNode is found, insert a textNode before the // first element child. if (!found) { var textNode = document.createTextNode(data[gTextProp]); element.insertBefore(textNode, element.firstChild); } } delete data[gTextProp]; } for (var k in data) { element[k] = data[k]; } }
javascript
function translateElement(element) { var l10n = getL10nAttributes(element); if (!l10n.id) return; // get the related l10n object var data = getL10nData(l10n.id, l10n.args); if (!data) { console.warn('#' + l10n.id + ' is undefined.'); return; } // translate element (TODO: security checks?) if (data[gTextProp]) { // XXX if (getChildElementCount(element) === 0) { element[gTextProp] = data[gTextProp]; } else { // this element has element children: replace the content of the first // (non-empty) child textNode and clear other child textNodes var children = element.childNodes; var found = false; for (var i = 0, l = children.length; i < l; i++) { if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) { if (found) { children[i].nodeValue = ''; } else { children[i].nodeValue = data[gTextProp]; found = true; } } } // if no (non-empty) textNode is found, insert a textNode before the // first element child. if (!found) { var textNode = document.createTextNode(data[gTextProp]); element.insertBefore(textNode, element.firstChild); } } delete data[gTextProp]; } for (var k in data) { element[k] = data[k]; } }
[ "function", "translateElement", "(", "element", ")", "{", "var", "l10n", "=", "getL10nAttributes", "(", "element", ")", ";", "if", "(", "!", "l10n", ".", "id", ")", "return", ";", "// get the related l10n object", "var", "data", "=", "getL10nData", "(", "l10n", ".", "id", ",", "l10n", ".", "args", ")", ";", "if", "(", "!", "data", ")", "{", "console", ".", "warn", "(", "'#'", "+", "l10n", ".", "id", "+", "' is undefined.'", ")", ";", "return", ";", "}", "// translate element (TODO: security checks?)", "if", "(", "data", "[", "gTextProp", "]", ")", "{", "// XXX", "if", "(", "getChildElementCount", "(", "element", ")", "===", "0", ")", "{", "element", "[", "gTextProp", "]", "=", "data", "[", "gTextProp", "]", ";", "}", "else", "{", "// this element has element children: replace the content of the first", "// (non-empty) child textNode and clear other child textNodes", "var", "children", "=", "element", ".", "childNodes", ";", "var", "found", "=", "false", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "children", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "children", "[", "i", "]", ".", "nodeType", "===", "3", "&&", "/", "\\S", "/", ".", "test", "(", "children", "[", "i", "]", ".", "nodeValue", ")", ")", "{", "if", "(", "found", ")", "{", "children", "[", "i", "]", ".", "nodeValue", "=", "''", ";", "}", "else", "{", "children", "[", "i", "]", ".", "nodeValue", "=", "data", "[", "gTextProp", "]", ";", "found", "=", "true", ";", "}", "}", "}", "// if no (non-empty) textNode is found, insert a textNode before the", "// first element child.", "if", "(", "!", "found", ")", "{", "var", "textNode", "=", "document", ".", "createTextNode", "(", "data", "[", "gTextProp", "]", ")", ";", "element", ".", "insertBefore", "(", "textNode", ",", "element", ".", "firstChild", ")", ";", "}", "}", "delete", "data", "[", "gTextProp", "]", ";", "}", "for", "(", "var", "k", "in", "data", ")", "{", "element", "[", "k", "]", "=", "data", "[", "k", "]", ";", "}", "}" ]
translate an HTML element
[ "translate", "an", "HTML", "element" ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/l10n.js#L893-L937
22,093
gerhardberger/electron-pdf-window
pdfjs/web/l10n.js
getChildElementCount
function getChildElementCount(element) { if (element.children) { return element.children.length; } if (typeof element.childElementCount !== 'undefined') { return element.childElementCount; } var count = 0; for (var i = 0; i < element.childNodes.length; i++) { count += element.nodeType === 1 ? 1 : 0; } return count; }
javascript
function getChildElementCount(element) { if (element.children) { return element.children.length; } if (typeof element.childElementCount !== 'undefined') { return element.childElementCount; } var count = 0; for (var i = 0; i < element.childNodes.length; i++) { count += element.nodeType === 1 ? 1 : 0; } return count; }
[ "function", "getChildElementCount", "(", "element", ")", "{", "if", "(", "element", ".", "children", ")", "{", "return", "element", ".", "children", ".", "length", ";", "}", "if", "(", "typeof", "element", ".", "childElementCount", "!==", "'undefined'", ")", "{", "return", "element", ".", "childElementCount", ";", "}", "var", "count", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "element", ".", "childNodes", ".", "length", ";", "i", "++", ")", "{", "count", "+=", "element", ".", "nodeType", "===", "1", "?", "1", ":", "0", ";", "}", "return", "count", ";", "}" ]
webkit browsers don't currently support 'children' on SVG elements...
[ "webkit", "browsers", "don", "t", "currently", "support", "children", "on", "SVG", "elements", "..." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/l10n.js#L940-L952
22,094
gerhardberger/electron-pdf-window
pdfjs/web/l10n.js
translateFragment
function translateFragment(element) { element = element || document.documentElement; // check all translatable children (= w/ a `data-l10n-id' attribute) var children = getTranslatableChildren(element); var elementCount = children.length; for (var i = 0; i < elementCount; i++) { translateElement(children[i]); } // translate element itself if necessary translateElement(element); }
javascript
function translateFragment(element) { element = element || document.documentElement; // check all translatable children (= w/ a `data-l10n-id' attribute) var children = getTranslatableChildren(element); var elementCount = children.length; for (var i = 0; i < elementCount; i++) { translateElement(children[i]); } // translate element itself if necessary translateElement(element); }
[ "function", "translateFragment", "(", "element", ")", "{", "element", "=", "element", "||", "document", ".", "documentElement", ";", "// check all translatable children (= w/ a `data-l10n-id' attribute)", "var", "children", "=", "getTranslatableChildren", "(", "element", ")", ";", "var", "elementCount", "=", "children", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elementCount", ";", "i", "++", ")", "{", "translateElement", "(", "children", "[", "i", "]", ")", ";", "}", "// translate element itself if necessary", "translateElement", "(", "element", ")", ";", "}" ]
translate an HTML subtree
[ "translate", "an", "HTML", "subtree" ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/l10n.js#L955-L967
22,095
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
preferencesSet
function preferencesSet(name, value) { return this.initializedPromise.then(function () { if (this.defaults[name] === undefined) { throw new Error('preferencesSet: \'' + name + '\' is undefined.'); } else if (value === undefined) { throw new Error('preferencesSet: no value is specified.'); } var valueType = typeof value; var defaultType = typeof this.defaults[name]; if (valueType !== defaultType) { if (valueType === 'number' && defaultType === 'string') { value = value.toString(); } else { throw new Error('Preferences_set: \'' + value + '\' is a \"' + valueType + '\", expected \"' + defaultType + '\".'); } } else { if (valueType === 'number' && (value | 0) !== value) { throw new Error('Preferences_set: \'' + value + '\' must be an \"integer\".'); } } this.prefs[name] = value; return this._writeToStorage(this.prefs); }.bind(this)); }
javascript
function preferencesSet(name, value) { return this.initializedPromise.then(function () { if (this.defaults[name] === undefined) { throw new Error('preferencesSet: \'' + name + '\' is undefined.'); } else if (value === undefined) { throw new Error('preferencesSet: no value is specified.'); } var valueType = typeof value; var defaultType = typeof this.defaults[name]; if (valueType !== defaultType) { if (valueType === 'number' && defaultType === 'string') { value = value.toString(); } else { throw new Error('Preferences_set: \'' + value + '\' is a \"' + valueType + '\", expected \"' + defaultType + '\".'); } } else { if (valueType === 'number' && (value | 0) !== value) { throw new Error('Preferences_set: \'' + value + '\' must be an \"integer\".'); } } this.prefs[name] = value; return this._writeToStorage(this.prefs); }.bind(this)); }
[ "function", "preferencesSet", "(", "name", ",", "value", ")", "{", "return", "this", ".", "initializedPromise", ".", "then", "(", "function", "(", ")", "{", "if", "(", "this", ".", "defaults", "[", "name", "]", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'preferencesSet: \\''", "+", "name", "+", "'\\' is undefined.'", ")", ";", "}", "else", "if", "(", "value", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'preferencesSet: no value is specified.'", ")", ";", "}", "var", "valueType", "=", "typeof", "value", ";", "var", "defaultType", "=", "typeof", "this", ".", "defaults", "[", "name", "]", ";", "if", "(", "valueType", "!==", "defaultType", ")", "{", "if", "(", "valueType", "===", "'number'", "&&", "defaultType", "===", "'string'", ")", "{", "value", "=", "value", ".", "toString", "(", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Preferences_set: \\''", "+", "value", "+", "'\\' is a \\\"'", "+", "valueType", "+", "'\\\", expected \\\"'", "+", "defaultType", "+", "'\\\".'", ")", ";", "}", "}", "else", "{", "if", "(", "valueType", "===", "'number'", "&&", "(", "value", "|", "0", ")", "!==", "value", ")", "{", "throw", "new", "Error", "(", "'Preferences_set: \\''", "+", "value", "+", "'\\' must be an \\\"integer\\\".'", ")", ";", "}", "}", "this", ".", "prefs", "[", "name", "]", "=", "value", ";", "return", "this", ".", "_writeToStorage", "(", "this", ".", "prefs", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Set the value of a preference. @param {string} name The name of the preference that should be changed. @param {boolean|number|string} value The new value of the preference. @return {Promise} A promise that is resolved when the value has been set, provided that the preference exists and the types match.
[ "Set", "the", "value", "of", "a", "preference", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L606-L629
22,096
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
PDFOutlineViewer_addToggleButton
function PDFOutlineViewer_addToggleButton(div) { var toggler = document.createElement('div'); toggler.className = 'outlineItemToggler'; toggler.onclick = function (event) { event.stopPropagation(); toggler.classList.toggle('outlineItemsHidden'); if (event.shiftKey) { var shouldShowAll = !toggler.classList.contains('outlineItemsHidden'); this._toggleOutlineItem(div, shouldShowAll); } }.bind(this); div.insertBefore(toggler, div.firstChild); }
javascript
function PDFOutlineViewer_addToggleButton(div) { var toggler = document.createElement('div'); toggler.className = 'outlineItemToggler'; toggler.onclick = function (event) { event.stopPropagation(); toggler.classList.toggle('outlineItemsHidden'); if (event.shiftKey) { var shouldShowAll = !toggler.classList.contains('outlineItemsHidden'); this._toggleOutlineItem(div, shouldShowAll); } }.bind(this); div.insertBefore(toggler, div.firstChild); }
[ "function", "PDFOutlineViewer_addToggleButton", "(", "div", ")", "{", "var", "toggler", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "toggler", ".", "className", "=", "'outlineItemToggler'", ";", "toggler", ".", "onclick", "=", "function", "(", "event", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "toggler", ".", "classList", ".", "toggle", "(", "'outlineItemsHidden'", ")", ";", "if", "(", "event", ".", "shiftKey", ")", "{", "var", "shouldShowAll", "=", "!", "toggler", ".", "classList", ".", "contains", "(", "'outlineItemsHidden'", ")", ";", "this", ".", "_toggleOutlineItem", "(", "div", ",", "shouldShowAll", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "div", ".", "insertBefore", "(", "toggler", ",", "div", ".", "firstChild", ")", ";", "}" ]
Prepend a button before an outline item which allows the user to toggle the visibility of all outline items at that level. @private
[ "Prepend", "a", "button", "before", "an", "outline", "item", "which", "allows", "the", "user", "to", "toggle", "the", "visibility", "of", "all", "outline", "items", "at", "that", "level", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L1072-L1084
22,097
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
PDFOutlineViewer_toggleOutlineItem
function PDFOutlineViewer_toggleOutlineItem(root, show) { this.lastToggleIsShow = show; var togglers = root.querySelectorAll('.outlineItemToggler'); for (var i = 0, ii = togglers.length; i < ii; ++i) { togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden'); } }
javascript
function PDFOutlineViewer_toggleOutlineItem(root, show) { this.lastToggleIsShow = show; var togglers = root.querySelectorAll('.outlineItemToggler'); for (var i = 0, ii = togglers.length; i < ii; ++i) { togglers[i].classList[show ? 'remove' : 'add']('outlineItemsHidden'); } }
[ "function", "PDFOutlineViewer_toggleOutlineItem", "(", "root", ",", "show", ")", "{", "this", ".", "lastToggleIsShow", "=", "show", ";", "var", "togglers", "=", "root", ".", "querySelectorAll", "(", "'.outlineItemToggler'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "togglers", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "togglers", "[", "i", "]", ".", "classList", "[", "show", "?", "'remove'", ":", "'add'", "]", "(", "'outlineItemsHidden'", ")", ";", "}", "}" ]
Toggle the visibility of the subtree of an outline item. @param {Element} root - the root of the outline (sub)tree. @param {boolean} show - whether to show the outline (sub)tree. If false, the outline subtree rooted at |root| will be collapsed. @private
[ "Toggle", "the", "visibility", "of", "the", "subtree", "of", "an", "outline", "item", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L1094-L1100
22,098
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
PDFDocumentProperties_open
function PDFDocumentProperties_open() { Promise.all([ OverlayManager.open(this.overlayName), this.dataAvailablePromise ]).then(function () { this._getProperties(); }.bind(this)); }
javascript
function PDFDocumentProperties_open() { Promise.all([ OverlayManager.open(this.overlayName), this.dataAvailablePromise ]).then(function () { this._getProperties(); }.bind(this)); }
[ "function", "PDFDocumentProperties_open", "(", ")", "{", "Promise", ".", "all", "(", "[", "OverlayManager", ".", "open", "(", "this", ".", "overlayName", ")", ",", "this", ".", "dataAvailablePromise", "]", ")", ".", "then", "(", "function", "(", ")", "{", "this", ".", "_getProperties", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Open the document properties overlay.
[ "Open", "the", "document", "properties", "overlay", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L2189-L2196
22,099
gerhardberger/electron-pdf-window
pdfjs/web/viewer.js
PDFFindController_updateMatchPosition
function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) { if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) { var spot = { top: FIND_SCROLL_OFFSET_TOP, left: FIND_SCROLL_OFFSET_LEFT }; scrollIntoView(elements[beginIdx], spot, /* skipOverflowHiddenElements = */ true); } }
javascript
function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) { if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) { var spot = { top: FIND_SCROLL_OFFSET_TOP, left: FIND_SCROLL_OFFSET_LEFT }; scrollIntoView(elements[beginIdx], spot, /* skipOverflowHiddenElements = */ true); } }
[ "function", "PDFFindController_updateMatchPosition", "(", "pageIndex", ",", "index", ",", "elements", ",", "beginIdx", ")", "{", "if", "(", "this", ".", "selected", ".", "matchIdx", "===", "index", "&&", "this", ".", "selected", ".", "pageIdx", "===", "pageIndex", ")", "{", "var", "spot", "=", "{", "top", ":", "FIND_SCROLL_OFFSET_TOP", ",", "left", ":", "FIND_SCROLL_OFFSET_LEFT", "}", ";", "scrollIntoView", "(", "elements", "[", "beginIdx", "]", ",", "spot", ",", "/* skipOverflowHiddenElements = */", "true", ")", ";", "}", "}" ]
The method is called back from the text layer when match presentation is updated. @param {number} pageIndex - page index. @param {number} index - match index. @param {Array} elements - text layer div elements array. @param {number} beginIdx - start index of the div array for the match.
[ "The", "method", "is", "called", "back", "from", "the", "text", "layer", "when", "match", "presentation", "is", "updated", "." ]
61fc00ab545ee5170f9832aaa37dedb542d3b3e8
https://github.com/gerhardberger/electron-pdf-window/blob/61fc00ab545ee5170f9832aaa37dedb542d3b3e8/pdfjs/web/viewer.js#L2708-L2717