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
18,600
zendeskgarden/css-components
scripts/new.js
linkCss
function linkCss(component) { const destination = path.join(demo, component); process.chdir(destination); const dist = path.join(packages, component, 'dist'); const source = path.relative(destination, dist); fs.readdirSync(source).forEach(file => { fs.symlinkSync(path.join(source, file), file); }); console.log(chalk.green('success'), 'Linked demo CSS'); }
javascript
function linkCss(component) { const destination = path.join(demo, component); process.chdir(destination); const dist = path.join(packages, component, 'dist'); const source = path.relative(destination, dist); fs.readdirSync(source).forEach(file => { fs.symlinkSync(path.join(source, file), file); }); console.log(chalk.green('success'), 'Linked demo CSS'); }
[ "function", "linkCss", "(", "component", ")", "{", "const", "destination", "=", "path", ".", "join", "(", "demo", ",", "component", ")", ";", "process", ".", "chdir", "(", "destination", ")", ";", "const", "dist", "=", "path", ".", "join", "(", "packages", ",", "component", ",", "'dist'", ")", ";", "const", "source", "=", "path", ".", "relative", "(", "destination", ",", "dist", ")", ";", "fs", ".", "readdirSync", "(", "source", ")", ".", "forEach", "(", "file", "=>", "{", "fs", ".", "symlinkSync", "(", "path", ".", "join", "(", "source", ",", "file", ")", ",", "file", ")", ";", "}", ")", ";", "console", ".", "log", "(", "chalk", ".", "green", "(", "'success'", ")", ",", "'Linked demo CSS'", ")", ";", "}" ]
Link demo CSS to the package dist for the given component. @param {String} component The name of the component to link.
[ "Link", "demo", "CSS", "to", "the", "package", "dist", "for", "the", "given", "component", "." ]
51007418bf70b9a3c8e6ff12f24e09e0ef3d2403
https://github.com/zendeskgarden/css-components/blob/51007418bf70b9a3c8e6ff12f24e09e0ef3d2403/scripts/new.js#L32-L45
18,601
zendeskgarden/css-components
scripts/new.js
updateDemo
function updateDemo(component) { const source = path.join(packages, component, 'demo'); const destination = path.join(demo, component); ncp(source, destination, error => { if (error) { console.log(chalk.red('error'), error); } else { rimraf(source, () => { console.log(chalk.green('success'), 'Updated component demo'); execSync(`yarn build --scope @zendeskgarden/css-${component}`); linkCss(component); execSync(`yarn start --open=${component}`); }); } }); }
javascript
function updateDemo(component) { const source = path.join(packages, component, 'demo'); const destination = path.join(demo, component); ncp(source, destination, error => { if (error) { console.log(chalk.red('error'), error); } else { rimraf(source, () => { console.log(chalk.green('success'), 'Updated component demo'); execSync(`yarn build --scope @zendeskgarden/css-${component}`); linkCss(component); execSync(`yarn start --open=${component}`); }); } }); }
[ "function", "updateDemo", "(", "component", ")", "{", "const", "source", "=", "path", ".", "join", "(", "packages", ",", "component", ",", "'demo'", ")", ";", "const", "destination", "=", "path", ".", "join", "(", "demo", ",", "component", ")", ";", "ncp", "(", "source", ",", "destination", ",", "error", "=>", "{", "if", "(", "error", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "'error'", ")", ",", "error", ")", ";", "}", "else", "{", "rimraf", "(", "source", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "chalk", ".", "green", "(", "'success'", ")", ",", "'Updated component demo'", ")", ";", "execSync", "(", "`", "${", "component", "}", "`", ")", ";", "linkCss", "(", "component", ")", ";", "execSync", "(", "`", "${", "component", "}", "`", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Update the HTML page demo for the given component. @param {String} component The name of the component to update.
[ "Update", "the", "HTML", "page", "demo", "for", "the", "given", "component", "." ]
51007418bf70b9a3c8e6ff12f24e09e0ef3d2403
https://github.com/zendeskgarden/css-components/blob/51007418bf70b9a3c8e6ff12f24e09e0ef3d2403/scripts/new.js#L52-L68
18,602
zendeskgarden/css-components
scripts/new.js
addComponent
function addComponent(name) { const source = path.join(packages, '.template'); const destination = path.join(packages, name); if (fs.existsSync(destination)) { console.log(chalk.red('error'), 'Component package exists'); } else { ncp(source, destination, error => { if (error) { console.log(chalk.red('error'), error); } else { const items = walk(destination, { nodir: true }); items.forEach(item => { const string = fs.readFileSync(item.path, 'utf8'); const template = Handlebars.compile(string); const data = template({ component: name }); fs.writeFileSync(item.path, data, 'utf8'); }); console.log(chalk.green('success'), 'Added new component'); execSync('yarn postinstall'); updateDemo(name); } }); } }
javascript
function addComponent(name) { const source = path.join(packages, '.template'); const destination = path.join(packages, name); if (fs.existsSync(destination)) { console.log(chalk.red('error'), 'Component package exists'); } else { ncp(source, destination, error => { if (error) { console.log(chalk.red('error'), error); } else { const items = walk(destination, { nodir: true }); items.forEach(item => { const string = fs.readFileSync(item.path, 'utf8'); const template = Handlebars.compile(string); const data = template({ component: name }); fs.writeFileSync(item.path, data, 'utf8'); }); console.log(chalk.green('success'), 'Added new component'); execSync('yarn postinstall'); updateDemo(name); } }); } }
[ "function", "addComponent", "(", "name", ")", "{", "const", "source", "=", "path", ".", "join", "(", "packages", ",", "'.template'", ")", ";", "const", "destination", "=", "path", ".", "join", "(", "packages", ",", "name", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "destination", ")", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "'error'", ")", ",", "'Component package exists'", ")", ";", "}", "else", "{", "ncp", "(", "source", ",", "destination", ",", "error", "=>", "{", "if", "(", "error", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "'error'", ")", ",", "error", ")", ";", "}", "else", "{", "const", "items", "=", "walk", "(", "destination", ",", "{", "nodir", ":", "true", "}", ")", ";", "items", ".", "forEach", "(", "item", "=>", "{", "const", "string", "=", "fs", ".", "readFileSync", "(", "item", ".", "path", ",", "'utf8'", ")", ";", "const", "template", "=", "Handlebars", ".", "compile", "(", "string", ")", ";", "const", "data", "=", "template", "(", "{", "component", ":", "name", "}", ")", ";", "fs", ".", "writeFileSync", "(", "item", ".", "path", ",", "data", ",", "'utf8'", ")", ";", "}", ")", ";", "console", ".", "log", "(", "chalk", ".", "green", "(", "'success'", ")", ",", "'Added new component'", ")", ";", "execSync", "(", "'yarn postinstall'", ")", ";", "updateDemo", "(", "name", ")", ";", "}", "}", ")", ";", "}", "}" ]
Add a new component package with the given name. @param {String} name The name of the component to add.
[ "Add", "a", "new", "component", "package", "with", "the", "given", "name", "." ]
51007418bf70b9a3c8e6ff12f24e09e0ef3d2403
https://github.com/zendeskgarden/css-components/blob/51007418bf70b9a3c8e6ff12f24e09e0ef3d2403/scripts/new.js#L75-L102
18,603
zendeskgarden/css-components
packages/variables/scripts/build.js
toProperties
function toProperties(variables) { const categories = Object.keys(variables); const valueOf = (category, value) => { let retVal; if (category === 'color') { retVal = `rgb(${value.r}, ${value.g}, ${value.b})`; } else if (category === 'font-family') { retVal = value .map(font => { return font.indexOf(' ') === -1 ? font : `'${font}'`; }) .join(', '); } else { retVal = value; } return retVal; }; return categories.reduce((retVal, category) => { const keys = Object.keys(variables[category]); keys.forEach(key => { const value = valueOf(category, variables[category][key]); const _key = key.length > 0 ? `${category}-${key}` : `${category}`; retVal.push(`--zd-${_key}: ${value};`); }); return retVal; }, []); }
javascript
function toProperties(variables) { const categories = Object.keys(variables); const valueOf = (category, value) => { let retVal; if (category === 'color') { retVal = `rgb(${value.r}, ${value.g}, ${value.b})`; } else if (category === 'font-family') { retVal = value .map(font => { return font.indexOf(' ') === -1 ? font : `'${font}'`; }) .join(', '); } else { retVal = value; } return retVal; }; return categories.reduce((retVal, category) => { const keys = Object.keys(variables[category]); keys.forEach(key => { const value = valueOf(category, variables[category][key]); const _key = key.length > 0 ? `${category}-${key}` : `${category}`; retVal.push(`--zd-${_key}: ${value};`); }); return retVal; }, []); }
[ "function", "toProperties", "(", "variables", ")", "{", "const", "categories", "=", "Object", ".", "keys", "(", "variables", ")", ";", "const", "valueOf", "=", "(", "category", ",", "value", ")", "=>", "{", "let", "retVal", ";", "if", "(", "category", "===", "'color'", ")", "{", "retVal", "=", "`", "${", "value", ".", "r", "}", "${", "value", ".", "g", "}", "${", "value", ".", "b", "}", "`", ";", "}", "else", "if", "(", "category", "===", "'font-family'", ")", "{", "retVal", "=", "value", ".", "map", "(", "font", "=>", "{", "return", "font", ".", "indexOf", "(", "' '", ")", "===", "-", "1", "?", "font", ":", "`", "${", "font", "}", "`", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "}", "else", "{", "retVal", "=", "value", ";", "}", "return", "retVal", ";", "}", ";", "return", "categories", ".", "reduce", "(", "(", "retVal", ",", "category", ")", "=>", "{", "const", "keys", "=", "Object", ".", "keys", "(", "variables", "[", "category", "]", ")", ";", "keys", ".", "forEach", "(", "key", "=>", "{", "const", "value", "=", "valueOf", "(", "category", ",", "variables", "[", "category", "]", "[", "key", "]", ")", ";", "const", "_key", "=", "key", ".", "length", ">", "0", "?", "`", "${", "category", "}", "${", "key", "}", "`", ":", "`", "${", "category", "}", "`", ";", "retVal", ".", "push", "(", "`", "${", "_key", "}", "${", "value", "}", "`", ")", ";", "}", ")", ";", "return", "retVal", ";", "}", ",", "[", "]", ")", ";", "}" ]
Convert the given variables object to an array of CSS properties. @param {Object} variables The object to convert. @returns {Array} CSS properties.
[ "Convert", "the", "given", "variables", "object", "to", "an", "array", "of", "CSS", "properties", "." ]
51007418bf70b9a3c8e6ff12f24e09e0ef3d2403
https://github.com/zendeskgarden/css-components/blob/51007418bf70b9a3c8e6ff12f24e09e0ef3d2403/packages/variables/scripts/build.js#L26-L58
18,604
noolsjs/nools
examples/requirejs/scripts/nools.js
function (/*Date*/date, /*String*/interval, /*int*/amount) { var res = addTransform(interval, date, amount || 0); amount = res[0]; var property = res[1]; var sum = new Date(+date); var fixOvershoot = res[2]; if (property) { sum["set" + property](sum["get" + property]() + amount); } if (fixOvershoot && (sum.getDate() < date.getDate())) { sum.setDate(0); } return sum; // Date }
javascript
function (/*Date*/date, /*String*/interval, /*int*/amount) { var res = addTransform(interval, date, amount || 0); amount = res[0]; var property = res[1]; var sum = new Date(+date); var fixOvershoot = res[2]; if (property) { sum["set" + property](sum["get" + property]() + amount); } if (fixOvershoot && (sum.getDate() < date.getDate())) { sum.setDate(0); } return sum; // Date }
[ "function", "(", "/*Date*/", "date", ",", "/*String*/", "interval", ",", "/*int*/", "amount", ")", "{", "var", "res", "=", "addTransform", "(", "interval", ",", "date", ",", "amount", "||", "0", ")", ";", "amount", "=", "res", "[", "0", "]", ";", "var", "property", "=", "res", "[", "1", "]", ";", "var", "sum", "=", "new", "Date", "(", "+", "date", ")", ";", "var", "fixOvershoot", "=", "res", "[", "2", "]", ";", "if", "(", "property", ")", "{", "sum", "[", "\"set\"", "+", "property", "]", "(", "sum", "[", "\"get\"", "+", "property", "]", "(", ")", "+", "amount", ")", ";", "}", "if", "(", "fixOvershoot", "&&", "(", "sum", ".", "getDate", "(", ")", "<", "date", ".", "getDate", "(", ")", ")", ")", "{", "sum", ".", "setDate", "(", "0", ")", ";", "}", "return", "sum", ";", "// Date", "}" ]
Adds a specified interval and amount to a date @example var dtA = new Date(2005, 11, 27); dateExtender.add(dtA, "year", 1); //new Date(2006, 11, 27); dateExtender.add(dtA, "years", 1); //new Date(2006, 11, 27); dtA = new Date(2000, 0, 1); dateExtender.add(dtA, "quarter", 1); //new Date(2000, 3, 1); dateExtender.add(dtA, "quarters", 1); //new Date(2000, 3, 1); dtA = new Date(2000, 0, 1); dateExtender.add(dtA, "month", 1); //new Date(2000, 1, 1); dateExtender.add(dtA, "months", 1); //new Date(2000, 1, 1); dtA = new Date(2000, 0, 31); dateExtender.add(dtA, "month", 1); //new Date(2000, 1, 29); dateExtender.add(dtA, "months", 1); //new Date(2000, 1, 29); dtA = new Date(2000, 0, 1); dateExtender.add(dtA, "week", 1); //new Date(2000, 0, 8); dateExtender.add(dtA, "weeks", 1); //new Date(2000, 0, 8); dtA = new Date(2000, 0, 1); dateExtender.add(dtA, "day", 1); //new Date(2000, 0, 2); dtA = new Date(2000, 0, 1); dateExtender.add(dtA, "weekday", 1); //new Date(2000, 0, 3); dtA = new Date(2000, 0, 1, 11); dateExtender.add(dtA, "hour", 1); //new Date(2000, 0, 1, 12); dtA = new Date(2000, 11, 31, 23, 59); dateExtender.add(dtA, "minute", 1); //new Date(2001, 0, 1, 0, 0); dtA = new Date(2000, 11, 31, 23, 59, 59); dateExtender.add(dtA, "second", 1); //new Date(2001, 0, 1, 0, 0, 0); dtA = new Date(2000, 11, 31, 23, 59, 59, 999); dateExtender.add(dtA, "millisecond", 1); //new Date(2001, 0, 1, 0, 0, 0, 0); @param {Date} date @param {String} interval the interval to add <ul> <li>day | days</li> <li>weekday | weekdays</li> <li>year | years</li> <li>week | weeks</li> <li>quarter | quarters</li> <li>months | months</li> <li>hour | hours</li> <li>minute | minutes</li> <li>second | seconds</li> <li>millisecond | milliseconds</li> </ul> @param {Number} [amount=0] the amount to add
[ "Adds", "a", "specified", "interval", "and", "amount", "to", "a", "date" ]
56e977d4e44cedf1c87142a6a94f7ebd9c00693a
https://github.com/noolsjs/nools/blob/56e977d4e44cedf1c87142a6a94f7ebd9c00693a/examples/requirejs/scripts/nools.js#L4591-L4606
18,605
noolsjs/nools
examples/requirejs/scripts/nools.js
function (/*Date*/date1, /*Date?*/date2, /*String*/interval, utc) { date2 = date2 || new Date(); interval = interval || "day"; return differenceTransform(interval, date1, date2, utc); }
javascript
function (/*Date*/date1, /*Date?*/date2, /*String*/interval, utc) { date2 = date2 || new Date(); interval = interval || "day"; return differenceTransform(interval, date1, date2, utc); }
[ "function", "(", "/*Date*/", "date1", ",", "/*Date?*/", "date2", ",", "/*String*/", "interval", ",", "utc", ")", "{", "date2", "=", "date2", "||", "new", "Date", "(", ")", ";", "interval", "=", "interval", "||", "\"day\"", ";", "return", "differenceTransform", "(", "interval", ",", "date1", ",", "date2", ",", "utc", ")", ";", "}" ]
Finds the difference between two dates based on the specified interval @example var dtA, dtB; dtA = new Date(2005, 11, 27); dtB = new Date(2006, 11, 27); dateExtender.difference(dtA, dtB, "year"); //1 dtA = new Date(2000, 1, 29); dtB = new Date(2001, 2, 1); dateExtender.difference(dtA, dtB, "quarter"); //4 dateExtender.difference(dtA, dtB, "month"); //13 dtA = new Date(2000, 1, 1); dtB = new Date(2000, 1, 8); dateExtender.difference(dtA, dtB, "week"); //1 dtA = new Date(2000, 1, 29); dtB = new Date(2000, 2, 1); dateExtender.difference(dtA, dtB, "day"); //1 dtA = new Date(2006, 7, 3); dtB = new Date(2006, 7, 11); dateExtender.difference(dtA, dtB, "weekday"); //6 dtA = new Date(2000, 11, 31, 23); dtB = new Date(2001, 0, 1, 0); dateExtender.difference(dtA, dtB, "hour"); //1 dtA = new Date(2000, 11, 31, 23, 59); dtB = new Date(2001, 0, 1, 0, 0); dateExtender.difference(dtA, dtB, "minute"); //1 dtA = new Date(2000, 11, 31, 23, 59, 59); dtB = new Date(2001, 0, 1, 0, 0, 0); dateExtender.difference(dtA, dtB, "second"); //1 dtA = new Date(2000, 11, 31, 23, 59, 59, 999); dtB = new Date(2001, 0, 1, 0, 0, 0, 0); dateExtender.difference(dtA, dtB, "millisecond"); //1 @param {Date} date1 @param {Date} [date2 = new Date()] @param {String} [interval = "day"] the intercal to find the difference of. <ul> <li>day | days</li> <li>weekday | weekdays</li> <li>year | years</li> <li>week | weeks</li> <li>quarter | quarters</li> <li>months | months</li> <li>hour | hours</li> <li>minute | minutes</li> <li>second | seconds</li> <li>millisecond | milliseconds</li> </ul>
[ "Finds", "the", "difference", "between", "two", "dates", "based", "on", "the", "specified", "interval" ]
56e977d4e44cedf1c87142a6a94f7ebd9c00693a
https://github.com/noolsjs/nools/blob/56e977d4e44cedf1c87142a6a94f7ebd9c00693a/examples/requirejs/scripts/nools.js#L4669-L4673
18,606
noolsjs/nools
examples/requirejs/scripts/nools.js
function (leftContext, rightContext) { var leftMatch = leftContext.match, fh = leftMatch.factHash, alias = this.__alias, rightFact = rightContext.fact; fh[alias] = rightFact.object; var ret = this.constraint.assert(fh); fh[alias] = null; return ret; }
javascript
function (leftContext, rightContext) { var leftMatch = leftContext.match, fh = leftMatch.factHash, alias = this.__alias, rightFact = rightContext.fact; fh[alias] = rightFact.object; var ret = this.constraint.assert(fh); fh[alias] = null; return ret; }
[ "function", "(", "leftContext", ",", "rightContext", ")", "{", "var", "leftMatch", "=", "leftContext", ".", "match", ",", "fh", "=", "leftMatch", ".", "factHash", ",", "alias", "=", "this", ".", "__alias", ",", "rightFact", "=", "rightContext", ".", "fact", ";", "fh", "[", "alias", "]", "=", "rightFact", ".", "object", ";", "var", "ret", "=", "this", ".", "constraint", ".", "assert", "(", "fh", ")", ";", "fh", "[", "alias", "]", "=", "null", ";", "return", "ret", ";", "}" ]
used by NotNode to avoid creating match Result for efficiency
[ "used", "by", "NotNode", "to", "avoid", "creating", "match", "Result", "for", "efficiency" ]
56e977d4e44cedf1c87142a6a94f7ebd9c00693a
https://github.com/noolsjs/nools/blob/56e977d4e44cedf1c87142a6a94f7ebd9c00693a/examples/requirejs/scripts/nools.js#L14898-L14908
18,607
mysticatea/eslint-plugin-eslint-comments
lib/utils/patch.js
getSeverity
function getSeverity(config, ruleId) { const rules = config && config.rules const ruleOptions = rules && rules[ruleId] const severity = Array.isArray(ruleOptions) ? ruleOptions[0] : ruleOptions switch (severity) { case 2: case "error": return 2 case 1: case "warn": return 1 default: return 0 } }
javascript
function getSeverity(config, ruleId) { const rules = config && config.rules const ruleOptions = rules && rules[ruleId] const severity = Array.isArray(ruleOptions) ? ruleOptions[0] : ruleOptions switch (severity) { case 2: case "error": return 2 case 1: case "warn": return 1 default: return 0 } }
[ "function", "getSeverity", "(", "config", ",", "ruleId", ")", "{", "const", "rules", "=", "config", "&&", "config", ".", "rules", "const", "ruleOptions", "=", "rules", "&&", "rules", "[", "ruleId", "]", "const", "severity", "=", "Array", ".", "isArray", "(", "ruleOptions", ")", "?", "ruleOptions", "[", "0", "]", ":", "ruleOptions", "switch", "(", "severity", ")", "{", "case", "2", ":", "case", "\"error\"", ":", "return", "2", "case", "1", ":", "case", "\"warn\"", ":", "return", "1", "default", ":", "return", "0", "}", "}" ]
Get the severity of a given rule. @param {object} config The config object to check. @param {string} ruleId The rule ID to check. @returns {number} The severity of the rule.
[ "Get", "the", "severity", "of", "a", "given", "rule", "." ]
cc1a193af03d552fedcd338e455e5f957d491df1
https://github.com/mysticatea/eslint-plugin-eslint-comments/blob/cc1a193af03d552fedcd338e455e5f957d491df1/lib/utils/patch.js#L17-L34
18,608
mysticatea/eslint-plugin-eslint-comments
lib/utils/patch.js
getCommentAt
function getCommentAt(message, sourceCode) { if (sourceCode != null) { const loc = { line: message.line, column: message.column - 1 } const index = sourceCode.getIndexFromLoc(loc) const options = { includeComments: true } const comment = sourceCode.getTokenByRangeStart(index, options) if ( comment != null && (comment.type === "Line" || comment.type === "Block") ) { return comment } } return undefined }
javascript
function getCommentAt(message, sourceCode) { if (sourceCode != null) { const loc = { line: message.line, column: message.column - 1 } const index = sourceCode.getIndexFromLoc(loc) const options = { includeComments: true } const comment = sourceCode.getTokenByRangeStart(index, options) if ( comment != null && (comment.type === "Line" || comment.type === "Block") ) { return comment } } return undefined }
[ "function", "getCommentAt", "(", "message", ",", "sourceCode", ")", "{", "if", "(", "sourceCode", "!=", "null", ")", "{", "const", "loc", "=", "{", "line", ":", "message", ".", "line", ",", "column", ":", "message", ".", "column", "-", "1", "}", "const", "index", "=", "sourceCode", ".", "getIndexFromLoc", "(", "loc", ")", "const", "options", "=", "{", "includeComments", ":", "true", "}", "const", "comment", "=", "sourceCode", ".", "getTokenByRangeStart", "(", "index", ",", "options", ")", "if", "(", "comment", "!=", "null", "&&", "(", "comment", ".", "type", "===", "\"Line\"", "||", "comment", ".", "type", "===", "\"Block\"", ")", ")", "{", "return", "comment", "}", "}", "return", "undefined", "}" ]
Get the comment which is at a given message location. @param {Message} message The message to get. @param {SourceCode|undefined} sourceCode The source code object to get. @returns {Comment|undefined} The gotten comment.
[ "Get", "the", "comment", "which", "is", "at", "a", "given", "message", "location", "." ]
cc1a193af03d552fedcd338e455e5f957d491df1
https://github.com/mysticatea/eslint-plugin-eslint-comments/blob/cc1a193af03d552fedcd338e455e5f957d491df1/lib/utils/patch.js#L42-L56
18,609
mysticatea/eslint-plugin-eslint-comments
scripts/lib/utils.js
format
function format(text) { const lintResult = linter.executeOnText(text) return lintResult.results[0].output || text }
javascript
function format(text) { const lintResult = linter.executeOnText(text) return lintResult.results[0].output || text }
[ "function", "format", "(", "text", ")", "{", "const", "lintResult", "=", "linter", ".", "executeOnText", "(", "text", ")", "return", "lintResult", ".", "results", "[", "0", "]", ".", "output", "||", "text", "}" ]
Format a given text. @param {string} text The text to format. @returns {string} The formatted text.
[ "Format", "a", "given", "text", "." ]
cc1a193af03d552fedcd338e455e5f957d491df1
https://github.com/mysticatea/eslint-plugin-eslint-comments/blob/cc1a193af03d552fedcd338e455e5f957d491df1/scripts/lib/utils.js#L17-L20
18,610
mysticatea/eslint-plugin-eslint-comments
scripts/lib/utils.js
createIndex
function createIndex(dirPath) { const dirName = path.basename(dirPath) return format(`/** DON'T EDIT THIS FILE; was created by scripts. */ "use strict" module.exports = { ${fs .readdirSync(dirPath) .map(file => path.basename(file, ".js")) .map(id => `"${id}": require("./${dirName}/${id}"),`) .join("\n ")} } `) }
javascript
function createIndex(dirPath) { const dirName = path.basename(dirPath) return format(`/** DON'T EDIT THIS FILE; was created by scripts. */ "use strict" module.exports = { ${fs .readdirSync(dirPath) .map(file => path.basename(file, ".js")) .map(id => `"${id}": require("./${dirName}/${id}"),`) .join("\n ")} } `) }
[ "function", "createIndex", "(", "dirPath", ")", "{", "const", "dirName", "=", "path", ".", "basename", "(", "dirPath", ")", "return", "format", "(", "`", "${", "fs", ".", "readdirSync", "(", "dirPath", ")", ".", "map", "(", "file", "=>", "path", ".", "basename", "(", "file", ",", "\".js\"", ")", ")", ".", "map", "(", "id", "=>", "`", "${", "id", "}", "${", "dirName", "}", "${", "id", "}", "`", ")", ".", "join", "(", "\"\\n \"", ")", "}", "`", ")", "}" ]
Create the index file content of a given directory. @param {string} dirPath The path to the directory to create index. @returns {string} The index file content.
[ "Create", "the", "index", "file", "content", "of", "a", "given", "directory", "." ]
cc1a193af03d552fedcd338e455e5f957d491df1
https://github.com/mysticatea/eslint-plugin-eslint-comments/blob/cc1a193af03d552fedcd338e455e5f957d491df1/scripts/lib/utils.js#L27-L40
18,611
padolsey/operative
dist/operative.js
operative
function operative(module, dependencies) { var getBase = operative.getBaseURL; var getSelf = operative.getSelfURL; var OperativeContext = operative.hasWorkerSupport ? operative.Operative.BrowserWorker : operative.Operative.Iframe; if (typeof module == 'function') { // Allow a single function to be passed. var o = new OperativeContext({ main: module }, dependencies, getBase, getSelf); var singularOperative = function() { return o.api.main.apply(o, arguments); }; singularOperative.transfer = function() { return o.api.main.transfer.apply(o, arguments); }; // Copy across exposable API to the returned function: for (var i in o.api) { if (hasOwn.call(o.api, i)) { singularOperative[i] = o.api[i]; } } return singularOperative; } return new OperativeContext(module, dependencies, getBase, getSelf).api; }
javascript
function operative(module, dependencies) { var getBase = operative.getBaseURL; var getSelf = operative.getSelfURL; var OperativeContext = operative.hasWorkerSupport ? operative.Operative.BrowserWorker : operative.Operative.Iframe; if (typeof module == 'function') { // Allow a single function to be passed. var o = new OperativeContext({ main: module }, dependencies, getBase, getSelf); var singularOperative = function() { return o.api.main.apply(o, arguments); }; singularOperative.transfer = function() { return o.api.main.transfer.apply(o, arguments); }; // Copy across exposable API to the returned function: for (var i in o.api) { if (hasOwn.call(o.api, i)) { singularOperative[i] = o.api[i]; } } return singularOperative; } return new OperativeContext(module, dependencies, getBase, getSelf).api; }
[ "function", "operative", "(", "module", ",", "dependencies", ")", "{", "var", "getBase", "=", "operative", ".", "getBaseURL", ";", "var", "getSelf", "=", "operative", ".", "getSelfURL", ";", "var", "OperativeContext", "=", "operative", ".", "hasWorkerSupport", "?", "operative", ".", "Operative", ".", "BrowserWorker", ":", "operative", ".", "Operative", ".", "Iframe", ";", "if", "(", "typeof", "module", "==", "'function'", ")", "{", "// Allow a single function to be passed.", "var", "o", "=", "new", "OperativeContext", "(", "{", "main", ":", "module", "}", ",", "dependencies", ",", "getBase", ",", "getSelf", ")", ";", "var", "singularOperative", "=", "function", "(", ")", "{", "return", "o", ".", "api", ".", "main", ".", "apply", "(", "o", ",", "arguments", ")", ";", "}", ";", "singularOperative", ".", "transfer", "=", "function", "(", ")", "{", "return", "o", ".", "api", ".", "main", ".", "transfer", ".", "apply", "(", "o", ",", "arguments", ")", ";", "}", ";", "// Copy across exposable API to the returned function:", "for", "(", "var", "i", "in", "o", ".", "api", ")", "{", "if", "(", "hasOwn", ".", "call", "(", "o", ".", "api", ",", "i", ")", ")", "{", "singularOperative", "[", "i", "]", "=", "o", ".", "api", "[", "i", "]", ";", "}", "}", "return", "singularOperative", ";", "}", "return", "new", "OperativeContext", "(", "module", ",", "dependencies", ",", "getBase", ",", "getSelf", ")", ".", "api", ";", "}" ]
Exposed operative factory
[ "Exposed", "operative", "factory" ]
b1353cb6961d8bc4f410149401e950d111e6e9b3
https://github.com/padolsey/operative/blob/b1353cb6961d8bc4f410149401e950d111e6e9b3/dist/operative.js#L51-L78
18,612
rafeca/prettyjson
lib/prettyjson.js
function(input, onlyPrimitives, options) { if ( typeof input === 'boolean' || typeof input === 'number' || typeof input === 'function' || input === null || input instanceof Date ) { return true; } if (typeof input === 'string' && input.indexOf('\n') === -1) { return true; } if (options.inlineArrays && !onlyPrimitives) { if (Array.isArray(input) && isSerializable(input[0], true, options)) { return true; } } return false; }
javascript
function(input, onlyPrimitives, options) { if ( typeof input === 'boolean' || typeof input === 'number' || typeof input === 'function' || input === null || input instanceof Date ) { return true; } if (typeof input === 'string' && input.indexOf('\n') === -1) { return true; } if (options.inlineArrays && !onlyPrimitives) { if (Array.isArray(input) && isSerializable(input[0], true, options)) { return true; } } return false; }
[ "function", "(", "input", ",", "onlyPrimitives", ",", "options", ")", "{", "if", "(", "typeof", "input", "===", "'boolean'", "||", "typeof", "input", "===", "'number'", "||", "typeof", "input", "===", "'function'", "||", "input", "===", "null", "||", "input", "instanceof", "Date", ")", "{", "return", "true", ";", "}", "if", "(", "typeof", "input", "===", "'string'", "&&", "input", ".", "indexOf", "(", "'\\n'", ")", "===", "-", "1", ")", "{", "return", "true", ";", "}", "if", "(", "options", ".", "inlineArrays", "&&", "!", "onlyPrimitives", ")", "{", "if", "(", "Array", ".", "isArray", "(", "input", ")", "&&", "isSerializable", "(", "input", "[", "0", "]", ",", "true", ",", "options", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Helper function to detect if an object can be directly serializable
[ "Helper", "function", "to", "detect", "if", "an", "object", "can", "be", "directly", "serializable" ]
7fa29b10985a0b816be649c9c6ddf9fb289c66fe
https://github.com/rafeca/prettyjson/blob/7fa29b10985a0b816be649c9c6ddf9fb289c66fe/lib/prettyjson.js#L10-L31
18,613
joeferraro/MavensMate
app/lib/commands/index.js
_handleCommandResult
function _handleCommandResult(result) { // if we're running via the cli, we can print human-friendly responses // otherwise we return proper JSON logger.info('handling command result'); if (result.result) { logger.debug(result.result); } else if (result.error) { logger.error(result.error); } if (result.error) { if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.reject(result.error); } else { console.error(JSON.stringify({ error:result.error.message })); process.exit(1); } } else { if (_.isString(result.result)) { var response = { message: result.result }; if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.resolve(response); } else { console.log(JSON.stringify(response)); process.exit(0); } } else { if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.resolve(result.result); } else { console.log(JSON.stringify(result.result)); process.exit(0); } } } }
javascript
function _handleCommandResult(result) { // if we're running via the cli, we can print human-friendly responses // otherwise we return proper JSON logger.info('handling command result'); if (result.result) { logger.debug(result.result); } else if (result.error) { logger.error(result.error); } if (result.error) { if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.reject(result.error); } else { console.error(JSON.stringify({ error:result.error.message })); process.exit(1); } } else { if (_.isString(result.result)) { var response = { message: result.result }; if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.resolve(response); } else { console.log(JSON.stringify(response)); process.exit(0); } } else { if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.resolve(result.result); } else { console.log(JSON.stringify(result.result)); process.exit(0); } } } }
[ "function", "_handleCommandResult", "(", "result", ")", "{", "// if we're running via the cli, we can print human-friendly responses", "// otherwise we return proper JSON", "logger", ".", "info", "(", "'handling command result'", ")", ";", "if", "(", "result", ".", "result", ")", "{", "logger", ".", "debug", "(", "result", ".", "result", ")", ";", "}", "else", "if", "(", "result", ".", "error", ")", "{", "logger", ".", "error", "(", "result", ".", "error", ")", ";", "}", "if", "(", "result", ".", "error", ")", "{", "if", "(", "process", ".", "env", ".", "MAVENSMATE_CONTEXT", "!==", "'cli'", ")", "{", "result", ".", "reject", "(", "result", ".", "error", ")", ";", "}", "else", "{", "console", ".", "error", "(", "JSON", ".", "stringify", "(", "{", "error", ":", "result", ".", "error", ".", "message", "}", ")", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}", "else", "{", "if", "(", "_", ".", "isString", "(", "result", ".", "result", ")", ")", "{", "var", "response", "=", "{", "message", ":", "result", ".", "result", "}", ";", "if", "(", "process", ".", "env", ".", "MAVENSMATE_CONTEXT", "!==", "'cli'", ")", "{", "result", ".", "resolve", "(", "response", ")", ";", "}", "else", "{", "console", ".", "log", "(", "JSON", ".", "stringify", "(", "response", ")", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "}", "else", "{", "if", "(", "process", ".", "env", ".", "MAVENSMATE_CONTEXT", "!==", "'cli'", ")", "{", "result", ".", "resolve", "(", "result", ".", "result", ")", ";", "}", "else", "{", "console", ".", "log", "(", "JSON", ".", "stringify", "(", "result", ".", "result", ")", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "}", "}", "}" ]
Responses to the client that executed the command @param {Object|String} res - response from the command @param {Boolean} success - whether the command was successfull (TODO: do we need this?) @param {Error} error - error instance (for failed commands) @return {String|Object|STDOUT} - depends on the configuration of the client (more documentation needed here)
[ "Responses", "to", "the", "client", "that", "executed", "the", "command" ]
8804517bf8f8edf716405d959abc5f9468aa021f
https://github.com/joeferraro/MavensMate/blob/8804517bf8f8edf716405d959abc5f9468aa021f/app/lib/commands/index.js#L23-L62
18,614
joeferraro/MavensMate
app/lib/project.js
function(opts) { this.name = opts.name; this.path = opts.path; this.workspace = opts.workspace; this.subscription = opts.subscription; this.origin = opts.origin; this.username = opts.username; this.password = opts.password; this.accessToken = opts.accessToken; this.refreshToken = opts.refreshToken; this.instanceUrl = opts.instanceUrl; this.package = opts.package; this.orgType = opts.orgType; this.sfdcClient = opts.sfdcClient; this.requiresAuthentication = true; this.settings = {}; this.packageXml = null; this.orgMetadata = null; this.lightningIndex = null; this.metadataHelper = null; this.keychainService = new KeychainService(); this.logService = new LogService(this); this.symbolService = new SymbolService(this); this.lightningService = new LightningService(this); }
javascript
function(opts) { this.name = opts.name; this.path = opts.path; this.workspace = opts.workspace; this.subscription = opts.subscription; this.origin = opts.origin; this.username = opts.username; this.password = opts.password; this.accessToken = opts.accessToken; this.refreshToken = opts.refreshToken; this.instanceUrl = opts.instanceUrl; this.package = opts.package; this.orgType = opts.orgType; this.sfdcClient = opts.sfdcClient; this.requiresAuthentication = true; this.settings = {}; this.packageXml = null; this.orgMetadata = null; this.lightningIndex = null; this.metadataHelper = null; this.keychainService = new KeychainService(); this.logService = new LogService(this); this.symbolService = new SymbolService(this); this.lightningService = new LightningService(this); }
[ "function", "(", "opts", ")", "{", "this", ".", "name", "=", "opts", ".", "name", ";", "this", ".", "path", "=", "opts", ".", "path", ";", "this", ".", "workspace", "=", "opts", ".", "workspace", ";", "this", ".", "subscription", "=", "opts", ".", "subscription", ";", "this", ".", "origin", "=", "opts", ".", "origin", ";", "this", ".", "username", "=", "opts", ".", "username", ";", "this", ".", "password", "=", "opts", ".", "password", ";", "this", ".", "accessToken", "=", "opts", ".", "accessToken", ";", "this", ".", "refreshToken", "=", "opts", ".", "refreshToken", ";", "this", ".", "instanceUrl", "=", "opts", ".", "instanceUrl", ";", "this", ".", "package", "=", "opts", ".", "package", ";", "this", ".", "orgType", "=", "opts", ".", "orgType", ";", "this", ".", "sfdcClient", "=", "opts", ".", "sfdcClient", ";", "this", ".", "requiresAuthentication", "=", "true", ";", "this", ".", "settings", "=", "{", "}", ";", "this", ".", "packageXml", "=", "null", ";", "this", ".", "orgMetadata", "=", "null", ";", "this", ".", "lightningIndex", "=", "null", ";", "this", ".", "metadataHelper", "=", "null", ";", "this", ".", "keychainService", "=", "new", "KeychainService", "(", ")", ";", "this", ".", "logService", "=", "new", "LogService", "(", "this", ")", ";", "this", ".", "symbolService", "=", "new", "SymbolService", "(", "this", ")", ";", "this", ".", "lightningService", "=", "new", "LightningService", "(", "this", ")", ";", "}" ]
Represents a MavensMate project @constructor @param {Object} [opts] - Options used in deployment @param {String} [opts.name] - For new projects, sets the name of the project @param {String} [opts.subscription] - (optional) Specifies list of Metadata types that the project should subscribe to @param {String} [opts.workspace] - (optional) For new projects, sets the workspace @param {String} [opts.path] - (optional) Explicitly sets path of the project (defaults to current working directory) @param {String} [opts.origin] - (optional) When creating a MavensMate project from an existing directory, pass the existing path as "origin"
[ "Represents", "a", "MavensMate", "project" ]
8804517bf8f8edf716405d959abc5f9468aa021f
https://github.com/joeferraro/MavensMate/blob/8804517bf8f8edf716405d959abc5f9468aa021f/app/lib/project.js#L42-L66
18,615
joeferraro/MavensMate
app/lib/loader.js
_loadCmds
function _loadCmds(dirpath) { if (fs.existsSync(dirpath) && fs.statSync(dirpath).isDirectory()) { var commandFiles = util.walkSync(dirpath); _.each(commandFiles, function(cf) { _require(cf); }); } else { logger.debug('Directory not found '+dirpath); throw new Error('Command directory not found'); } }
javascript
function _loadCmds(dirpath) { if (fs.existsSync(dirpath) && fs.statSync(dirpath).isDirectory()) { var commandFiles = util.walkSync(dirpath); _.each(commandFiles, function(cf) { _require(cf); }); } else { logger.debug('Directory not found '+dirpath); throw new Error('Command directory not found'); } }
[ "function", "_loadCmds", "(", "dirpath", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "dirpath", ")", "&&", "fs", ".", "statSync", "(", "dirpath", ")", ".", "isDirectory", "(", ")", ")", "{", "var", "commandFiles", "=", "util", ".", "walkSync", "(", "dirpath", ")", ";", "_", ".", "each", "(", "commandFiles", ",", "function", "(", "cf", ")", "{", "_require", "(", "cf", ")", ";", "}", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "'Directory not found '", "+", "dirpath", ")", ";", "throw", "new", "Error", "(", "'Command directory not found'", ")", ";", "}", "}" ]
Load tasks in a given folder.
[ "Load", "tasks", "in", "a", "given", "folder", "." ]
8804517bf8f8edf716405d959abc5f9468aa021f
https://github.com/joeferraro/MavensMate/blob/8804517bf8f8edf716405d959abc5f9468aa021f/app/lib/loader.js#L34-L44
18,616
joeferraro/MavensMate
app/middleware/project.js
_findProjectPathById
function _findProjectPathById(id) { logger.debug('_findProjectPathById'); logger.debug(id); var projectPathToReturn; var workspaces = config.get('mm_workspace'); if (!_.isArray(workspaces)) { workspaces = [workspaces]; } logger.silly(workspaces); _.each(workspaces, function(workspacePath) { // /foo/bar/project // /foo/bar/project/config/.settings logger.silly(workspacePath); var projectPaths = util.listDirectories(workspacePath); logger.silly(projectPaths); _.each(projectPaths, function(projectPath) { var settingsPath = path.join(projectPath, 'config', '.settings'); if (fs.existsSync(settingsPath)) { var settings = util.getFileBody(settingsPath, true); if (settings.id === id) { projectPathToReturn = projectPath; return false; } } }); }); return projectPathToReturn; }
javascript
function _findProjectPathById(id) { logger.debug('_findProjectPathById'); logger.debug(id); var projectPathToReturn; var workspaces = config.get('mm_workspace'); if (!_.isArray(workspaces)) { workspaces = [workspaces]; } logger.silly(workspaces); _.each(workspaces, function(workspacePath) { // /foo/bar/project // /foo/bar/project/config/.settings logger.silly(workspacePath); var projectPaths = util.listDirectories(workspacePath); logger.silly(projectPaths); _.each(projectPaths, function(projectPath) { var settingsPath = path.join(projectPath, 'config', '.settings'); if (fs.existsSync(settingsPath)) { var settings = util.getFileBody(settingsPath, true); if (settings.id === id) { projectPathToReturn = projectPath; return false; } } }); }); return projectPathToReturn; }
[ "function", "_findProjectPathById", "(", "id", ")", "{", "logger", ".", "debug", "(", "'_findProjectPathById'", ")", ";", "logger", ".", "debug", "(", "id", ")", ";", "var", "projectPathToReturn", ";", "var", "workspaces", "=", "config", ".", "get", "(", "'mm_workspace'", ")", ";", "if", "(", "!", "_", ".", "isArray", "(", "workspaces", ")", ")", "{", "workspaces", "=", "[", "workspaces", "]", ";", "}", "logger", ".", "silly", "(", "workspaces", ")", ";", "_", ".", "each", "(", "workspaces", ",", "function", "(", "workspacePath", ")", "{", "// /foo/bar/project", "// /foo/bar/project/config/.settings", "logger", ".", "silly", "(", "workspacePath", ")", ";", "var", "projectPaths", "=", "util", ".", "listDirectories", "(", "workspacePath", ")", ";", "logger", ".", "silly", "(", "projectPaths", ")", ";", "_", ".", "each", "(", "projectPaths", ",", "function", "(", "projectPath", ")", "{", "var", "settingsPath", "=", "path", ".", "join", "(", "projectPath", ",", "'config'", ",", "'.settings'", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "settingsPath", ")", ")", "{", "var", "settings", "=", "util", ".", "getFileBody", "(", "settingsPath", ",", "true", ")", ";", "if", "(", "settings", ".", "id", "===", "id", ")", "{", "projectPathToReturn", "=", "projectPath", ";", "return", "false", ";", "}", "}", "}", ")", ";", "}", ")", ";", "return", "projectPathToReturn", ";", "}" ]
Given a project id, search given workspaces to find it on the disk @param {String} id mavensmate project id @return {String} project path
[ "Given", "a", "project", "id", "search", "given", "workspaces", "to", "find", "it", "on", "the", "disk" ]
8804517bf8f8edf716405d959abc5f9468aa021f
https://github.com/joeferraro/MavensMate/blob/8804517bf8f8edf716405d959abc5f9468aa021f/app/middleware/project.js#L113-L140
18,617
joeferraro/MavensMate
app/lib/services/index.js
IndexService
function IndexService(opts) { util.applyProperties(this, opts); if (this.project) { this.metadataHelper = new MetadataHelper({ sfdcClient : this.project.sfdcClient }); this.sfdcClient = this.project.sfdcClient; } else if (this.sfdcClient) { this.metadataHelper = new MetadataHelper({ sfdcClient : this.sfdcClient }); } }
javascript
function IndexService(opts) { util.applyProperties(this, opts); if (this.project) { this.metadataHelper = new MetadataHelper({ sfdcClient : this.project.sfdcClient }); this.sfdcClient = this.project.sfdcClient; } else if (this.sfdcClient) { this.metadataHelper = new MetadataHelper({ sfdcClient : this.sfdcClient }); } }
[ "function", "IndexService", "(", "opts", ")", "{", "util", ".", "applyProperties", "(", "this", ",", "opts", ")", ";", "if", "(", "this", ".", "project", ")", "{", "this", ".", "metadataHelper", "=", "new", "MetadataHelper", "(", "{", "sfdcClient", ":", "this", ".", "project", ".", "sfdcClient", "}", ")", ";", "this", ".", "sfdcClient", "=", "this", ".", "project", ".", "sfdcClient", ";", "}", "else", "if", "(", "this", ".", "sfdcClient", ")", "{", "this", ".", "metadataHelper", "=", "new", "MetadataHelper", "(", "{", "sfdcClient", ":", "this", ".", "sfdcClient", "}", ")", ";", "}", "}" ]
Service to get an index of an org's metadata @param {Object} project - project instance (optional) @param {Object} sfdcClient - client instance (optional)
[ "Service", "to", "get", "an", "index", "of", "an", "org", "s", "metadata" ]
8804517bf8f8edf716405d959abc5f9468aa021f
https://github.com/joeferraro/MavensMate/blob/8804517bf8f8edf716405d959abc5f9468aa021f/app/lib/services/index.js#L25-L33
18,618
StreakYC/react-menu-list
example/Example.js
LI
function LI(props) { return ( <MenuItem style={{cursor: 'pointer', userSelect: 'none'}} highlightedStyle={{background: 'gray'}} onItemChosen={e => { console.log(`selected ${props.children}, byKeyboard: ${String(e.byKeyboard)}`); }} {...props} /> ); }
javascript
function LI(props) { return ( <MenuItem style={{cursor: 'pointer', userSelect: 'none'}} highlightedStyle={{background: 'gray'}} onItemChosen={e => { console.log(`selected ${props.children}, byKeyboard: ${String(e.byKeyboard)}`); }} {...props} /> ); }
[ "function", "LI", "(", "props", ")", "{", "return", "(", "<", "MenuItem", "style", "=", "{", "{", "cursor", ":", "'pointer'", ",", "userSelect", ":", "'none'", "}", "}", "highlightedStyle", "=", "{", "{", "background", ":", "'gray'", "}", "}", "onItemChosen", "=", "{", "e", "=>", "{", "console", ".", "log", "(", "`", "${", "props", ".", "children", "}", "${", "String", "(", "e", ".", "byKeyboard", ")", "}", "`", ")", ";", "}", "}", "{", "...", "props", "}", "/", ">", ")", ";", "}" ]
MenuItems don't come with any styling by default! You'll probably want to make your own component which wraps them and adds your own application's style to them like this.
[ "MenuItems", "don", "t", "come", "with", "any", "styling", "by", "default!", "You", "ll", "probably", "want", "to", "make", "your", "own", "component", "which", "wraps", "them", "and", "adds", "your", "own", "application", "s", "style", "to", "them", "like", "this", "." ]
73684426d8934ae7aaf85870bd55b94a1ee0cf9e
https://github.com/StreakYC/react-menu-list/blob/73684426d8934ae7aaf85870bd55b94a1ee0cf9e/example/Example.js#L11-L22
18,619
walmartlabs/little-loader
lib/little-loader.js
function (src, callback, context) { /*eslint max-statements: [2, 32]*/ var setup; if (callback && typeof callback !== "function") { context = callback.context || context; setup = callback.setup; callback = callback.callback; } var script = document.createElement("script"); var done = false; var err; var _cleanup; // _must_ be set below. /** * Final handler for error or completion. * * **Note**: Will only be called _once_. * * @returns {void} */ var _finish = function () { // Only call once. if (done) { return; } done = true; // Internal cleanup. _cleanup(); // Callback. if (callback) { callback.call(context, err); } }; /** * Error handler * * @returns {void} */ var _error = function () { err = new Error(src || "EMPTY"); _finish(); }; if (script.readyState && !("async" in script)) { /*eslint-disable consistent-return*/ // This section is only for IE<10. Some other old browsers may // satisfy the above condition and enter this branch, but we don't // support those browsers anyway. var id = scriptCounter++; var isReady = { loaded: true, complete: true }; var inserted = false; // Clear out listeners, state. _cleanup = function () { script.onreadystatechange = script.onerror = null; pendingScripts[id] = void 0; }; // Attach the handler before setting src, otherwise we might // miss events (consider that IE could fire them synchronously // upon setting src, for example). script.onreadystatechange = function () { var firstState = script.readyState; // Protect against any errors from state change randomness. if (err) { return; } if (!inserted && isReady[firstState]) { inserted = true; // Append to DOM. _addScript(script); } // -------------------------------------------------------------------- // GLORIOUS IE8 HACKAGE!!! // -------------------------------------------------------------------- // // Oh IE8, how you disappoint. IE8 won't call `script.onerror`, so // we have to resort to drastic measures. // See, e.g. http://www.quirksmode.org/dom/events/error.html#t02 // // As with all things development, there's a Stack Overflow comment that // asserts the following combinations of state changes in IE8 indicate a // script load error. And crazily, it seems to work! // // http://stackoverflow.com/a/18840568/741892 // // The `script.readyState` transitions we're interested are: // // * If state starts as `loaded` // * Call `script.children`, which _should_ change state to `complete` // * If state is now `loading`, then **we have a load error** // // For the reader's amusement, here is HeadJS's catalog of various // `readyState` transitions in normal operation for IE: // https://github.com/headjs/headjs/blob/master/src/2.0.0/load.js#L379-L419 if (firstState === "loaded") { // The act of accessing the property should change the script's // `readyState`. // // And, oh yeah, this hack is so hacky-ish we need the following // eslint disable... /*eslint-disable no-unused-expressions*/ script.children; /*eslint-enable no-unused-expressions*/ if (script.readyState === "loading") { // State transitions indicate we've hit the load error. // // **Note**: We are not intending to _return_ a value, just have // a shorter short-circuit code path here. return _error(); } } // It's possible for readyState to be "complete" immediately // after we insert (and execute) the script in the branch // above. So check readyState again here and react without // waiting for another onreadystatechange. if (script.readyState === "complete") { _finish(); } }; // Onerror handler _may_ work here. script.onerror = _error; // Since we're not appending the script to the DOM yet, the // reference to our script element might get garbage collected // when this function ends, without onreadystatechange ever being // fired. This has been witnessed to happen. Adding it to // `pendingScripts` ensures this can't happen. pendingScripts[id] = script; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script); } // This triggers a request for the script, but its contents won't // be executed until we append it to the DOM. script.src = src; // In some cases, the readyState is already "loaded" immediately // after setting src. It's a lie! Don't append to the DOM until // the onreadystatechange event says so. } else { // This section is for modern browsers, including IE10+. // Clear out listeners. _cleanup = function () { script.onload = script.onerror = null; }; script.onerror = _error; script.onload = _finish; script.async = true; script.charset = "utf-8"; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script); } script.src = src; // Append to DOM. _addScript(script); } }
javascript
function (src, callback, context) { /*eslint max-statements: [2, 32]*/ var setup; if (callback && typeof callback !== "function") { context = callback.context || context; setup = callback.setup; callback = callback.callback; } var script = document.createElement("script"); var done = false; var err; var _cleanup; // _must_ be set below. /** * Final handler for error or completion. * * **Note**: Will only be called _once_. * * @returns {void} */ var _finish = function () { // Only call once. if (done) { return; } done = true; // Internal cleanup. _cleanup(); // Callback. if (callback) { callback.call(context, err); } }; /** * Error handler * * @returns {void} */ var _error = function () { err = new Error(src || "EMPTY"); _finish(); }; if (script.readyState && !("async" in script)) { /*eslint-disable consistent-return*/ // This section is only for IE<10. Some other old browsers may // satisfy the above condition and enter this branch, but we don't // support those browsers anyway. var id = scriptCounter++; var isReady = { loaded: true, complete: true }; var inserted = false; // Clear out listeners, state. _cleanup = function () { script.onreadystatechange = script.onerror = null; pendingScripts[id] = void 0; }; // Attach the handler before setting src, otherwise we might // miss events (consider that IE could fire them synchronously // upon setting src, for example). script.onreadystatechange = function () { var firstState = script.readyState; // Protect against any errors from state change randomness. if (err) { return; } if (!inserted && isReady[firstState]) { inserted = true; // Append to DOM. _addScript(script); } // -------------------------------------------------------------------- // GLORIOUS IE8 HACKAGE!!! // -------------------------------------------------------------------- // // Oh IE8, how you disappoint. IE8 won't call `script.onerror`, so // we have to resort to drastic measures. // See, e.g. http://www.quirksmode.org/dom/events/error.html#t02 // // As with all things development, there's a Stack Overflow comment that // asserts the following combinations of state changes in IE8 indicate a // script load error. And crazily, it seems to work! // // http://stackoverflow.com/a/18840568/741892 // // The `script.readyState` transitions we're interested are: // // * If state starts as `loaded` // * Call `script.children`, which _should_ change state to `complete` // * If state is now `loading`, then **we have a load error** // // For the reader's amusement, here is HeadJS's catalog of various // `readyState` transitions in normal operation for IE: // https://github.com/headjs/headjs/blob/master/src/2.0.0/load.js#L379-L419 if (firstState === "loaded") { // The act of accessing the property should change the script's // `readyState`. // // And, oh yeah, this hack is so hacky-ish we need the following // eslint disable... /*eslint-disable no-unused-expressions*/ script.children; /*eslint-enable no-unused-expressions*/ if (script.readyState === "loading") { // State transitions indicate we've hit the load error. // // **Note**: We are not intending to _return_ a value, just have // a shorter short-circuit code path here. return _error(); } } // It's possible for readyState to be "complete" immediately // after we insert (and execute) the script in the branch // above. So check readyState again here and react without // waiting for another onreadystatechange. if (script.readyState === "complete") { _finish(); } }; // Onerror handler _may_ work here. script.onerror = _error; // Since we're not appending the script to the DOM yet, the // reference to our script element might get garbage collected // when this function ends, without onreadystatechange ever being // fired. This has been witnessed to happen. Adding it to // `pendingScripts` ensures this can't happen. pendingScripts[id] = script; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script); } // This triggers a request for the script, but its contents won't // be executed until we append it to the DOM. script.src = src; // In some cases, the readyState is already "loaded" immediately // after setting src. It's a lie! Don't append to the DOM until // the onreadystatechange event says so. } else { // This section is for modern browsers, including IE10+. // Clear out listeners. _cleanup = function () { script.onload = script.onerror = null; }; script.onerror = _error; script.onload = _finish; script.async = true; script.charset = "utf-8"; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script); } script.src = src; // Append to DOM. _addScript(script); } }
[ "function", "(", "src", ",", "callback", ",", "context", ")", "{", "/*eslint max-statements: [2, 32]*/", "var", "setup", ";", "if", "(", "callback", "&&", "typeof", "callback", "!==", "\"function\"", ")", "{", "context", "=", "callback", ".", "context", "||", "context", ";", "setup", "=", "callback", ".", "setup", ";", "callback", "=", "callback", ".", "callback", ";", "}", "var", "script", "=", "document", ".", "createElement", "(", "\"script\"", ")", ";", "var", "done", "=", "false", ";", "var", "err", ";", "var", "_cleanup", ";", "// _must_ be set below.", "/**\n * Final handler for error or completion.\n *\n * **Note**: Will only be called _once_.\n *\n * @returns {void}\n */", "var", "_finish", "=", "function", "(", ")", "{", "// Only call once.", "if", "(", "done", ")", "{", "return", ";", "}", "done", "=", "true", ";", "// Internal cleanup.", "_cleanup", "(", ")", ";", "// Callback.", "if", "(", "callback", ")", "{", "callback", ".", "call", "(", "context", ",", "err", ")", ";", "}", "}", ";", "/**\n * Error handler\n *\n * @returns {void}\n */", "var", "_error", "=", "function", "(", ")", "{", "err", "=", "new", "Error", "(", "src", "||", "\"EMPTY\"", ")", ";", "_finish", "(", ")", ";", "}", ";", "if", "(", "script", ".", "readyState", "&&", "!", "(", "\"async\"", "in", "script", ")", ")", "{", "/*eslint-disable consistent-return*/", "// This section is only for IE<10. Some other old browsers may", "// satisfy the above condition and enter this branch, but we don't", "// support those browsers anyway.", "var", "id", "=", "scriptCounter", "++", ";", "var", "isReady", "=", "{", "loaded", ":", "true", ",", "complete", ":", "true", "}", ";", "var", "inserted", "=", "false", ";", "// Clear out listeners, state.", "_cleanup", "=", "function", "(", ")", "{", "script", ".", "onreadystatechange", "=", "script", ".", "onerror", "=", "null", ";", "pendingScripts", "[", "id", "]", "=", "void", "0", ";", "}", ";", "// Attach the handler before setting src, otherwise we might", "// miss events (consider that IE could fire them synchronously", "// upon setting src, for example).", "script", ".", "onreadystatechange", "=", "function", "(", ")", "{", "var", "firstState", "=", "script", ".", "readyState", ";", "// Protect against any errors from state change randomness.", "if", "(", "err", ")", "{", "return", ";", "}", "if", "(", "!", "inserted", "&&", "isReady", "[", "firstState", "]", ")", "{", "inserted", "=", "true", ";", "// Append to DOM.", "_addScript", "(", "script", ")", ";", "}", "// --------------------------------------------------------------------", "// GLORIOUS IE8 HACKAGE!!!", "// --------------------------------------------------------------------", "//", "// Oh IE8, how you disappoint. IE8 won't call `script.onerror`, so", "// we have to resort to drastic measures.", "// See, e.g. http://www.quirksmode.org/dom/events/error.html#t02", "//", "// As with all things development, there's a Stack Overflow comment that", "// asserts the following combinations of state changes in IE8 indicate a", "// script load error. And crazily, it seems to work!", "//", "// http://stackoverflow.com/a/18840568/741892", "//", "// The `script.readyState` transitions we're interested are:", "//", "// * If state starts as `loaded`", "// * Call `script.children`, which _should_ change state to `complete`", "// * If state is now `loading`, then **we have a load error**", "//", "// For the reader's amusement, here is HeadJS's catalog of various", "// `readyState` transitions in normal operation for IE:", "// https://github.com/headjs/headjs/blob/master/src/2.0.0/load.js#L379-L419", "if", "(", "firstState", "===", "\"loaded\"", ")", "{", "// The act of accessing the property should change the script's", "// `readyState`.", "//", "// And, oh yeah, this hack is so hacky-ish we need the following", "// eslint disable...", "/*eslint-disable no-unused-expressions*/", "script", ".", "children", ";", "/*eslint-enable no-unused-expressions*/", "if", "(", "script", ".", "readyState", "===", "\"loading\"", ")", "{", "// State transitions indicate we've hit the load error.", "//", "// **Note**: We are not intending to _return_ a value, just have", "// a shorter short-circuit code path here.", "return", "_error", "(", ")", ";", "}", "}", "// It's possible for readyState to be \"complete\" immediately", "// after we insert (and execute) the script in the branch", "// above. So check readyState again here and react without", "// waiting for another onreadystatechange.", "if", "(", "script", ".", "readyState", "===", "\"complete\"", ")", "{", "_finish", "(", ")", ";", "}", "}", ";", "// Onerror handler _may_ work here.", "script", ".", "onerror", "=", "_error", ";", "// Since we're not appending the script to the DOM yet, the", "// reference to our script element might get garbage collected", "// when this function ends, without onreadystatechange ever being", "// fired. This has been witnessed to happen. Adding it to", "// `pendingScripts` ensures this can't happen.", "pendingScripts", "[", "id", "]", "=", "script", ";", "// call the setup callback to mutate the script tag", "if", "(", "setup", ")", "{", "setup", ".", "call", "(", "context", ",", "script", ")", ";", "}", "// This triggers a request for the script, but its contents won't", "// be executed until we append it to the DOM.", "script", ".", "src", "=", "src", ";", "// In some cases, the readyState is already \"loaded\" immediately", "// after setting src. It's a lie! Don't append to the DOM until", "// the onreadystatechange event says so.", "}", "else", "{", "// This section is for modern browsers, including IE10+.", "// Clear out listeners.", "_cleanup", "=", "function", "(", ")", "{", "script", ".", "onload", "=", "script", ".", "onerror", "=", "null", ";", "}", ";", "script", ".", "onerror", "=", "_error", ";", "script", ".", "onload", "=", "_finish", ";", "script", ".", "async", "=", "true", ";", "script", ".", "charset", "=", "\"utf-8\"", ";", "// call the setup callback to mutate the script tag", "if", "(", "setup", ")", "{", "setup", ".", "call", "(", "context", ",", "script", ")", ";", "}", "script", ".", "src", "=", "src", ";", "// Append to DOM.", "_addScript", "(", "script", ")", ";", "}", "}" ]
Load Script. @param {String} src URI of script @param {Function|Object} callback (Optional) Called on script load completion, or options object @param {Object} context (Optional) Callback context (`this`) @returns {void}
[ "Load", "Script", "." ]
42d233f360162bb01fce5a9664b6ef54751bd96e
https://github.com/walmartlabs/little-loader/blob/42d233f360162bb01fce5a9664b6ef54751bd96e/lib/little-loader.js#L55-L231
18,620
Donaldcwl/browser-image-compression
lib/index.js
imageCompression
async function imageCompression (file, options) { let compressedFile options.maxSizeMB = options.maxSizeMB || Number.POSITIVE_INFINITY options.useWebWorker = typeof options.useWebWorker === 'boolean' ? options.useWebWorker : true if (!(file instanceof Blob || file instanceof File)) { throw new Error('The file given is not an instance of Blob or File') } else if (!/^image/.test(file.type)) { throw new Error('The file given is not an image') } // try run in web worker, fall back to run in main thread const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope // if (inWebWorker) { // console.log('run compression in web worker') // } else { // console.log('run compression in main thread') // } if (options.useWebWorker && typeof Worker === 'function' && !inWebWorker) { try { // "compressOnWebWorker" is kind of like a recursion to call "imageCompression" again inside web worker compressedFile = await compressOnWebWorker(file, options) } catch (e) { // console.error('run compression in web worker failed', e) compressedFile = await compress(file, options) } } else { compressedFile = await compress(file, options) } try { compressedFile.name = file.name compressedFile.lastModified = file.lastModified } catch (e) {} return compressedFile }
javascript
async function imageCompression (file, options) { let compressedFile options.maxSizeMB = options.maxSizeMB || Number.POSITIVE_INFINITY options.useWebWorker = typeof options.useWebWorker === 'boolean' ? options.useWebWorker : true if (!(file instanceof Blob || file instanceof File)) { throw new Error('The file given is not an instance of Blob or File') } else if (!/^image/.test(file.type)) { throw new Error('The file given is not an image') } // try run in web worker, fall back to run in main thread const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope // if (inWebWorker) { // console.log('run compression in web worker') // } else { // console.log('run compression in main thread') // } if (options.useWebWorker && typeof Worker === 'function' && !inWebWorker) { try { // "compressOnWebWorker" is kind of like a recursion to call "imageCompression" again inside web worker compressedFile = await compressOnWebWorker(file, options) } catch (e) { // console.error('run compression in web worker failed', e) compressedFile = await compress(file, options) } } else { compressedFile = await compress(file, options) } try { compressedFile.name = file.name compressedFile.lastModified = file.lastModified } catch (e) {} return compressedFile }
[ "async", "function", "imageCompression", "(", "file", ",", "options", ")", "{", "let", "compressedFile", "options", ".", "maxSizeMB", "=", "options", ".", "maxSizeMB", "||", "Number", ".", "POSITIVE_INFINITY", "options", ".", "useWebWorker", "=", "typeof", "options", ".", "useWebWorker", "===", "'boolean'", "?", "options", ".", "useWebWorker", ":", "true", "if", "(", "!", "(", "file", "instanceof", "Blob", "||", "file", "instanceof", "File", ")", ")", "{", "throw", "new", "Error", "(", "'The file given is not an instance of Blob or File'", ")", "}", "else", "if", "(", "!", "/", "^image", "/", ".", "test", "(", "file", ".", "type", ")", ")", "{", "throw", "new", "Error", "(", "'The file given is not an image'", ")", "}", "// try run in web worker, fall back to run in main thread", "const", "inWebWorker", "=", "typeof", "WorkerGlobalScope", "!==", "'undefined'", "&&", "self", "instanceof", "WorkerGlobalScope", "// if (inWebWorker) {", "// console.log('run compression in web worker')", "// } else {", "// console.log('run compression in main thread')", "// }", "if", "(", "options", ".", "useWebWorker", "&&", "typeof", "Worker", "===", "'function'", "&&", "!", "inWebWorker", ")", "{", "try", "{", "// \"compressOnWebWorker\" is kind of like a recursion to call \"imageCompression\" again inside web worker", "compressedFile", "=", "await", "compressOnWebWorker", "(", "file", ",", "options", ")", "}", "catch", "(", "e", ")", "{", "// console.error('run compression in web worker failed', e)", "compressedFile", "=", "await", "compress", "(", "file", ",", "options", ")", "}", "}", "else", "{", "compressedFile", "=", "await", "compress", "(", "file", ",", "options", ")", "}", "try", "{", "compressedFile", ".", "name", "=", "file", ".", "name", "compressedFile", ".", "lastModified", "=", "file", ".", "lastModified", "}", "catch", "(", "e", ")", "{", "}", "return", "compressedFile", "}" ]
Compress an image file. @param {File} file @param {Object} options - { maxSizeMB=Number.POSITIVE_INFINITY, maxWidthOrHeight, useWebWorker=true, maxIteration = 10, exifOrientation } @param {number} [options.maxSizeMB=Number.POSITIVE_INFINITY] @param {number} [options.maxWidthOrHeight=undefined] * @param {number} [options.maxWidthOrHeight=undefined] @param {boolean} [options.useWebWorker=true] @param {number} [options.maxIteration=10] @param {number} [options.exifOrientation=] - default to be the exif orientation from the image file @returns {Promise<File | Blob>}
[ "Compress", "an", "image", "file", "." ]
9cd477460425e6a288dad325825ec4a336f6d8b8
https://github.com/Donaldcwl/browser-image-compression/blob/9cd477460425e6a288dad325825ec4a336f6d8b8/lib/index.js#L27-L67
18,621
thelonious/kld-intersections
dist/index-esm.js
sign
function sign(x) { // eslint-disable-next-line no-self-compare return typeof x === "number" ? x ? x < 0 ? -1 : 1 : x === x ? x : NaN : NaN; }
javascript
function sign(x) { // eslint-disable-next-line no-self-compare return typeof x === "number" ? x ? x < 0 ? -1 : 1 : x === x ? x : NaN : NaN; }
[ "function", "sign", "(", "x", ")", "{", "// eslint-disable-next-line no-self-compare", "return", "typeof", "x", "===", "\"number\"", "?", "x", "?", "x", "<", "0", "?", "-", "1", ":", "1", ":", "x", "===", "x", "?", "x", ":", "NaN", ":", "NaN", ";", "}" ]
Polynomial.js @module Polynomial @copyright 2002-2019 Kevin Lindsey<br> -<br> Contribution {@link http://github.com/Quazistax/kld-polynomial}<br> 2015 Robert Benko (Quazistax) <quazistax@gmail.com><br> MIT license Sign of a number (+1, -1, +0, -0). @param {number} x @returns {number}
[ "Polynomial", ".", "js" ]
12154d7200cb66c74ccd7200056e4455776042f5
https://github.com/thelonious/kld-intersections/blob/12154d7200cb66c74ccd7200056e4455776042f5/dist/index-esm.js#L1099-L1102
18,622
retextjs/retext-keywords
index.js
findPhraseInDirection
function findPhraseInDirection(node, index, parent, offset) { var children = parent.children var nodes = [] var stems = [] var words = [] var queue = [] var child while (children[(index += offset)]) { child = children[index] if (child.type === 'WhiteSpaceNode') { queue.push(child) } else if (isImportant(child)) { nodes = nodes.concat(queue, [child]) words.push(child) stems.push(stemNode(child)) queue = [] } else { break } } return { stems: stems, words: words, nodes: nodes } }
javascript
function findPhraseInDirection(node, index, parent, offset) { var children = parent.children var nodes = [] var stems = [] var words = [] var queue = [] var child while (children[(index += offset)]) { child = children[index] if (child.type === 'WhiteSpaceNode') { queue.push(child) } else if (isImportant(child)) { nodes = nodes.concat(queue, [child]) words.push(child) stems.push(stemNode(child)) queue = [] } else { break } } return { stems: stems, words: words, nodes: nodes } }
[ "function", "findPhraseInDirection", "(", "node", ",", "index", ",", "parent", ",", "offset", ")", "{", "var", "children", "=", "parent", ".", "children", "var", "nodes", "=", "[", "]", "var", "stems", "=", "[", "]", "var", "words", "=", "[", "]", "var", "queue", "=", "[", "]", "var", "child", "while", "(", "children", "[", "(", "index", "+=", "offset", ")", "]", ")", "{", "child", "=", "children", "[", "index", "]", "if", "(", "child", ".", "type", "===", "'WhiteSpaceNode'", ")", "{", "queue", ".", "push", "(", "child", ")", "}", "else", "if", "(", "isImportant", "(", "child", ")", ")", "{", "nodes", "=", "nodes", ".", "concat", "(", "queue", ",", "[", "child", "]", ")", "words", ".", "push", "(", "child", ")", "stems", ".", "push", "(", "stemNode", "(", "child", ")", ")", "queue", "=", "[", "]", "}", "else", "{", "break", "}", "}", "return", "{", "stems", ":", "stems", ",", "words", ":", "words", ",", "nodes", ":", "nodes", "}", "}" ]
Get following or preceding important words or white space.
[ "Get", "following", "or", "preceding", "important", "words", "or", "white", "space", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L30-L58
18,623
retextjs/retext-keywords
index.js
getKeyphrases
function getKeyphrases(results, maximum) { var stemmedPhrases = {} var initialWords = [] var stemmedPhrase var index var length var otherIndex var keyword var matches var phrase var stems var score var first var match // Iterate over all grouped important words... for (keyword in results) { matches = results[keyword].matches length = matches.length index = -1 // Iterate over every occurence of a certain keyword... while (++index < length) { phrase = findPhrase(matches[index]) stemmedPhrase = stemmedPhrases[phrase.value] first = phrase.nodes[0] match = { nodes: phrase.nodes, parent: matches[index].parent } // If we've detected the same stemmed phrase somewhere. if (own.call(stemmedPhrases, phrase.value)) { // Add weight per phrase to the score of the phrase. stemmedPhrase.score += stemmedPhrase.weight // If this is the first time we walk over the phrase (exact match but // containing another important word), add it to the list of matching // phrases. if (initialWords.indexOf(first) === -1) { initialWords.push(first) stemmedPhrase.matches.push(match) } } else { otherIndex = -1 score = -1 stems = phrase.stems initialWords.push(first) // For every stem in phrase, add its score to score. while (stems[++otherIndex]) { score += results[stems[otherIndex]].score } stemmedPhrases[phrase.value] = { score: score, weight: score, stems: stems, value: phrase.value, matches: [match] } } } } for (stemmedPhrase in stemmedPhrases) { phrase = stemmedPhrases[stemmedPhrase] // Modify its score to be the rounded result of multiplying it with the // number of occurances, and dividing it by the ammount of words in the // phrase. phrase.score = Math.round( (phrase.score * phrase.matches.length) / phrase.stems.length ) } return filterResults(stemmedPhrases, maximum) }
javascript
function getKeyphrases(results, maximum) { var stemmedPhrases = {} var initialWords = [] var stemmedPhrase var index var length var otherIndex var keyword var matches var phrase var stems var score var first var match // Iterate over all grouped important words... for (keyword in results) { matches = results[keyword].matches length = matches.length index = -1 // Iterate over every occurence of a certain keyword... while (++index < length) { phrase = findPhrase(matches[index]) stemmedPhrase = stemmedPhrases[phrase.value] first = phrase.nodes[0] match = { nodes: phrase.nodes, parent: matches[index].parent } // If we've detected the same stemmed phrase somewhere. if (own.call(stemmedPhrases, phrase.value)) { // Add weight per phrase to the score of the phrase. stemmedPhrase.score += stemmedPhrase.weight // If this is the first time we walk over the phrase (exact match but // containing another important word), add it to the list of matching // phrases. if (initialWords.indexOf(first) === -1) { initialWords.push(first) stemmedPhrase.matches.push(match) } } else { otherIndex = -1 score = -1 stems = phrase.stems initialWords.push(first) // For every stem in phrase, add its score to score. while (stems[++otherIndex]) { score += results[stems[otherIndex]].score } stemmedPhrases[phrase.value] = { score: score, weight: score, stems: stems, value: phrase.value, matches: [match] } } } } for (stemmedPhrase in stemmedPhrases) { phrase = stemmedPhrases[stemmedPhrase] // Modify its score to be the rounded result of multiplying it with the // number of occurances, and dividing it by the ammount of words in the // phrase. phrase.score = Math.round( (phrase.score * phrase.matches.length) / phrase.stems.length ) } return filterResults(stemmedPhrases, maximum) }
[ "function", "getKeyphrases", "(", "results", ",", "maximum", ")", "{", "var", "stemmedPhrases", "=", "{", "}", "var", "initialWords", "=", "[", "]", "var", "stemmedPhrase", "var", "index", "var", "length", "var", "otherIndex", "var", "keyword", "var", "matches", "var", "phrase", "var", "stems", "var", "score", "var", "first", "var", "match", "// Iterate over all grouped important words...", "for", "(", "keyword", "in", "results", ")", "{", "matches", "=", "results", "[", "keyword", "]", ".", "matches", "length", "=", "matches", ".", "length", "index", "=", "-", "1", "// Iterate over every occurence of a certain keyword...", "while", "(", "++", "index", "<", "length", ")", "{", "phrase", "=", "findPhrase", "(", "matches", "[", "index", "]", ")", "stemmedPhrase", "=", "stemmedPhrases", "[", "phrase", ".", "value", "]", "first", "=", "phrase", ".", "nodes", "[", "0", "]", "match", "=", "{", "nodes", ":", "phrase", ".", "nodes", ",", "parent", ":", "matches", "[", "index", "]", ".", "parent", "}", "// If we've detected the same stemmed phrase somewhere.", "if", "(", "own", ".", "call", "(", "stemmedPhrases", ",", "phrase", ".", "value", ")", ")", "{", "// Add weight per phrase to the score of the phrase.", "stemmedPhrase", ".", "score", "+=", "stemmedPhrase", ".", "weight", "// If this is the first time we walk over the phrase (exact match but", "// containing another important word), add it to the list of matching", "// phrases.", "if", "(", "initialWords", ".", "indexOf", "(", "first", ")", "===", "-", "1", ")", "{", "initialWords", ".", "push", "(", "first", ")", "stemmedPhrase", ".", "matches", ".", "push", "(", "match", ")", "}", "}", "else", "{", "otherIndex", "=", "-", "1", "score", "=", "-", "1", "stems", "=", "phrase", ".", "stems", "initialWords", ".", "push", "(", "first", ")", "// For every stem in phrase, add its score to score.", "while", "(", "stems", "[", "++", "otherIndex", "]", ")", "{", "score", "+=", "results", "[", "stems", "[", "otherIndex", "]", "]", ".", "score", "}", "stemmedPhrases", "[", "phrase", ".", "value", "]", "=", "{", "score", ":", "score", ",", "weight", ":", "score", ",", "stems", ":", "stems", ",", "value", ":", "phrase", ".", "value", ",", "matches", ":", "[", "match", "]", "}", "}", "}", "}", "for", "(", "stemmedPhrase", "in", "stemmedPhrases", ")", "{", "phrase", "=", "stemmedPhrases", "[", "stemmedPhrase", "]", "// Modify its score to be the rounded result of multiplying it with the", "// number of occurances, and dividing it by the ammount of words in the", "// phrase.", "phrase", ".", "score", "=", "Math", ".", "round", "(", "(", "phrase", ".", "score", "*", "phrase", ".", "matches", ".", "length", ")", "/", "phrase", ".", "stems", ".", "length", ")", "}", "return", "filterResults", "(", "stemmedPhrases", ",", "maximum", ")", "}" ]
Get the top important phrases in `self`.
[ "Get", "the", "top", "important", "phrases", "in", "self", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L61-L140
18,624
retextjs/retext-keywords
index.js
filterResults
function filterResults(results, maximum) { var filteredResults = [] var indices = [] var matrix = {} var column var key var score var interpolated var index var otherIndex var maxScore for (key in results) { score = results[key].score if (!matrix[score]) { matrix[score] = [] indices.push(score) } matrix[score].push(results[key]) } indices.sort(reverse) maxScore = indices[0] index = -1 while (indices[++index]) { score = indices[index] column = matrix[score] interpolated = score / maxScore otherIndex = -1 while (column[++otherIndex]) { column[otherIndex].score = interpolated } filteredResults = filteredResults.concat(column) if (filteredResults.length >= maximum) { break } } return filteredResults }
javascript
function filterResults(results, maximum) { var filteredResults = [] var indices = [] var matrix = {} var column var key var score var interpolated var index var otherIndex var maxScore for (key in results) { score = results[key].score if (!matrix[score]) { matrix[score] = [] indices.push(score) } matrix[score].push(results[key]) } indices.sort(reverse) maxScore = indices[0] index = -1 while (indices[++index]) { score = indices[index] column = matrix[score] interpolated = score / maxScore otherIndex = -1 while (column[++otherIndex]) { column[otherIndex].score = interpolated } filteredResults = filteredResults.concat(column) if (filteredResults.length >= maximum) { break } } return filteredResults }
[ "function", "filterResults", "(", "results", ",", "maximum", ")", "{", "var", "filteredResults", "=", "[", "]", "var", "indices", "=", "[", "]", "var", "matrix", "=", "{", "}", "var", "column", "var", "key", "var", "score", "var", "interpolated", "var", "index", "var", "otherIndex", "var", "maxScore", "for", "(", "key", "in", "results", ")", "{", "score", "=", "results", "[", "key", "]", ".", "score", "if", "(", "!", "matrix", "[", "score", "]", ")", "{", "matrix", "[", "score", "]", "=", "[", "]", "indices", ".", "push", "(", "score", ")", "}", "matrix", "[", "score", "]", ".", "push", "(", "results", "[", "key", "]", ")", "}", "indices", ".", "sort", "(", "reverse", ")", "maxScore", "=", "indices", "[", "0", "]", "index", "=", "-", "1", "while", "(", "indices", "[", "++", "index", "]", ")", "{", "score", "=", "indices", "[", "index", "]", "column", "=", "matrix", "[", "score", "]", "interpolated", "=", "score", "/", "maxScore", "otherIndex", "=", "-", "1", "while", "(", "column", "[", "++", "otherIndex", "]", ")", "{", "column", "[", "otherIndex", "]", ".", "score", "=", "interpolated", "}", "filteredResults", "=", "filteredResults", ".", "concat", "(", "column", ")", "if", "(", "filteredResults", ".", "length", ">=", "maximum", ")", "{", "break", "}", "}", "return", "filteredResults", "}" ]
Get the top results from an occurance map.
[ "Get", "the", "top", "results", "from", "an", "occurance", "map", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L143-L191
18,625
retextjs/retext-keywords
index.js
merge
function merge(prev, current, next) { return prev .concat() .reverse() .concat([current], next) }
javascript
function merge(prev, current, next) { return prev .concat() .reverse() .concat([current], next) }
[ "function", "merge", "(", "prev", ",", "current", ",", "next", ")", "{", "return", "prev", ".", "concat", "(", ")", ".", "reverse", "(", ")", ".", "concat", "(", "[", "current", "]", ",", "next", ")", "}" ]
Merge a previous array, with a current value, and a following array.
[ "Merge", "a", "previous", "array", "with", "a", "current", "value", "and", "a", "following", "array", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L194-L199
18,626
retextjs/retext-keywords
index.js
findPhrase
function findPhrase(match) { var node = match.node var prev = findPhraseInDirection(node, match.index, match.parent, -1) var next = findPhraseInDirection(node, match.index, match.parent, 1) var stems = merge(prev.stems, stemNode(node), next.stems) return { stems: stems, value: stems.join(' '), nodes: merge(prev.nodes, node, next.nodes) } }
javascript
function findPhrase(match) { var node = match.node var prev = findPhraseInDirection(node, match.index, match.parent, -1) var next = findPhraseInDirection(node, match.index, match.parent, 1) var stems = merge(prev.stems, stemNode(node), next.stems) return { stems: stems, value: stems.join(' '), nodes: merge(prev.nodes, node, next.nodes) } }
[ "function", "findPhrase", "(", "match", ")", "{", "var", "node", "=", "match", ".", "node", "var", "prev", "=", "findPhraseInDirection", "(", "node", ",", "match", ".", "index", ",", "match", ".", "parent", ",", "-", "1", ")", "var", "next", "=", "findPhraseInDirection", "(", "node", ",", "match", ".", "index", ",", "match", ".", "parent", ",", "1", ")", "var", "stems", "=", "merge", "(", "prev", ".", "stems", ",", "stemNode", "(", "node", ")", ",", "next", ".", "stems", ")", "return", "{", "stems", ":", "stems", ",", "value", ":", "stems", ".", "join", "(", "' '", ")", ",", "nodes", ":", "merge", "(", "prev", ".", "nodes", ",", "node", ",", "next", ".", "nodes", ")", "}", "}" ]
Find the phrase surrounding a node.
[ "Find", "the", "phrase", "surrounding", "a", "node", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L202-L213
18,627
retextjs/retext-keywords
index.js
getImportantWords
function getImportantWords(node) { var words = {} visit(node, 'WordNode', visitor) return words function visitor(word, index, parent) { var match var stem if (isImportant(word)) { stem = stemNode(word) match = { node: word, index: index, parent: parent } if (!own.call(words, stem)) { words[stem] = { matches: [match], stem: stem, score: 1 } } else { words[stem].matches.push(match) words[stem].score++ } } } }
javascript
function getImportantWords(node) { var words = {} visit(node, 'WordNode', visitor) return words function visitor(word, index, parent) { var match var stem if (isImportant(word)) { stem = stemNode(word) match = { node: word, index: index, parent: parent } if (!own.call(words, stem)) { words[stem] = { matches: [match], stem: stem, score: 1 } } else { words[stem].matches.push(match) words[stem].score++ } } } }
[ "function", "getImportantWords", "(", "node", ")", "{", "var", "words", "=", "{", "}", "visit", "(", "node", ",", "'WordNode'", ",", "visitor", ")", "return", "words", "function", "visitor", "(", "word", ",", "index", ",", "parent", ")", "{", "var", "match", "var", "stem", "if", "(", "isImportant", "(", "word", ")", ")", "{", "stem", "=", "stemNode", "(", "word", ")", "match", "=", "{", "node", ":", "word", ",", "index", ":", "index", ",", "parent", ":", "parent", "}", "if", "(", "!", "own", ".", "call", "(", "words", ",", "stem", ")", ")", "{", "words", "[", "stem", "]", "=", "{", "matches", ":", "[", "match", "]", ",", "stem", ":", "stem", ",", "score", ":", "1", "}", "}", "else", "{", "words", "[", "stem", "]", ".", "matches", ".", "push", "(", "match", ")", "words", "[", "stem", "]", ".", "score", "++", "}", "}", "}", "}" ]
Get most important words in `node`.
[ "Get", "most", "important", "words", "in", "node", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L216-L247
18,628
retextjs/retext-keywords
index.js
cloneMatches
function cloneMatches(words) { var result = {} var key var match for (key in words) { match = words[key] result[key] = { matches: match.matches, stem: match.stem, score: match.score } } return result }
javascript
function cloneMatches(words) { var result = {} var key var match for (key in words) { match = words[key] result[key] = { matches: match.matches, stem: match.stem, score: match.score } } return result }
[ "function", "cloneMatches", "(", "words", ")", "{", "var", "result", "=", "{", "}", "var", "key", "var", "match", "for", "(", "key", "in", "words", ")", "{", "match", "=", "words", "[", "key", "]", "result", "[", "key", "]", "=", "{", "matches", ":", "match", ".", "matches", ",", "stem", ":", "match", ".", "stem", ",", "score", ":", "match", ".", "score", "}", "}", "return", "result", "}" ]
Clone the given map of words. This is a two level-deep clone.
[ "Clone", "the", "given", "map", "of", "words", ".", "This", "is", "a", "two", "level", "-", "deep", "clone", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L250-L266
18,629
retextjs/retext-keywords
index.js
isImportant
function isImportant(node) { return ( node && node.data && node.data.partOfSpeech && (node.data.partOfSpeech.indexOf('N') === 0 || (node.data.partOfSpeech === 'JJ' && isUpperCase(nlcstToString(node).charAt(0)))) ) }
javascript
function isImportant(node) { return ( node && node.data && node.data.partOfSpeech && (node.data.partOfSpeech.indexOf('N') === 0 || (node.data.partOfSpeech === 'JJ' && isUpperCase(nlcstToString(node).charAt(0)))) ) }
[ "function", "isImportant", "(", "node", ")", "{", "return", "(", "node", "&&", "node", ".", "data", "&&", "node", ".", "data", ".", "partOfSpeech", "&&", "(", "node", ".", "data", ".", "partOfSpeech", ".", "indexOf", "(", "'N'", ")", "===", "0", "||", "(", "node", ".", "data", ".", "partOfSpeech", "===", "'JJ'", "&&", "isUpperCase", "(", "nlcstToString", "(", "node", ")", ".", "charAt", "(", "0", ")", ")", ")", ")", ")", "}" ]
Check if `node` is important.
[ "Check", "if", "node", "is", "important", "." ]
8edebafd93b6745522b369513b22c4dc220e3587
https://github.com/retextjs/retext-keywords/blob/8edebafd93b6745522b369513b22c4dc220e3587/index.js#L269-L278
18,630
brainly/nodejs-onesky-utils
lib/postScreenshot.js
postScreenshot
function postScreenshot (options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getUploadOptions(options), 'Unable to upload document'); }
javascript
function postScreenshot (options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getUploadOptions(options), 'Unable to upload document'); }
[ "function", "postScreenshot", "(", "options", ")", "{", "options", ".", "hash", "=", "_private", ".", "getDevHash", "(", "options", ".", "secret", ")", ";", "return", "_private", ".", "makeRequest", "(", "_getUploadOptions", "(", "options", ")", ",", "'Unable to upload document'", ")", ";", "}" ]
Post screenshot file form service OneSky Screenshot documentation @link https://github.com/onesky/api-documentation-platform/blob/master/reference/screenshot.md @param {Object} options @param {Number} options.projectId Project ID @param {String} options.name A unique name to identify where the image located at your website, apps, blogs, etc... (Hints: path of the webpage) @param {String} options.image Base64 encoded image data in Data URI scheme structure. Please reference to Data URI scheme and Base64 @param {Object[]} options.tags Translations bind to the screenshot @param {String} options.tags[].key Key of the translation @param {Number} options.tags[].x X-axis of the translation component @param {Number} options.tags[].y Y-axis of the translation component @param {Number} options.tags[].width Width of the translation component @param {Number} options.tags[].height Height of the translation component @param {String} options.tags[].file Name of the string file @param {String} options.secret Private key to OneSky API @param {String} options.apiKey Public key to OneSky API
[ "Post", "screenshot", "file", "form", "service" ]
373cc1f5e9339f05d02d08e39cc9a8864bd7c5dc
https://github.com/brainly/nodejs-onesky-utils/blob/373cc1f5e9339f05d02d08e39cc9a8864bd7c5dc/lib/postScreenshot.js#L30-L33
18,631
brainly/nodejs-onesky-utils
lib/postFile.js
postFile
function postFile (options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getUploadOptions(options), 'Unable to upload document'); }
javascript
function postFile (options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getUploadOptions(options), 'Unable to upload document'); }
[ "function", "postFile", "(", "options", ")", "{", "options", ".", "hash", "=", "_private", ".", "getDevHash", "(", "options", ".", "secret", ")", ";", "return", "_private", ".", "makeRequest", "(", "_getUploadOptions", "(", "options", ")", ",", "'Unable to upload document'", ")", ";", "}" ]
Post translations file form service @param {Object} options @param {Number} options.projectId Project ID @param {String} options.format File format (see documentation) @param {String} options.content File to upload @param {Boolean} options.keepStrings Keep previous, non present in this file strings @param {String} options.secret Private key to OneSky API @param {String} options.apiKey Public key to OneSky API @param {String} options.language Language of the uploaded file @param {String} options.fileName Name of the uploaded file
[ "Post", "translations", "file", "form", "service" ]
373cc1f5e9339f05d02d08e39cc9a8864bd7c5dc
https://github.com/brainly/nodejs-onesky-utils/blob/373cc1f5e9339f05d02d08e39cc9a8864bd7c5dc/lib/postFile.js#L23-L27
18,632
brainly/nodejs-onesky-utils
lib/getLanguages.js
getLanguages
function getLanguages(options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getLink(options), 'Unable to fetch project languages'); }
javascript
function getLanguages(options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getLink(options), 'Unable to fetch project languages'); }
[ "function", "getLanguages", "(", "options", ")", "{", "options", ".", "hash", "=", "_private", ".", "getDevHash", "(", "options", ".", "secret", ")", ";", "return", "_private", ".", "makeRequest", "(", "_getLink", "(", "options", ")", ",", "'Unable to fetch project languages'", ")", ";", "}" ]
Get list of project languages @param {Object} options @param {Number} options.projectId Project ID @param {String} options.secret Private key to OneSky API @param {String} options.apiKey Public key to OneSky API
[ "Get", "list", "of", "project", "languages" ]
373cc1f5e9339f05d02d08e39cc9a8864bd7c5dc
https://github.com/brainly/nodejs-onesky-utils/blob/373cc1f5e9339f05d02d08e39cc9a8864bd7c5dc/lib/getLanguages.js#L17-L20
18,633
timoxley/columnify
index.js
createRows
function createRows(items, columns, columnNames, paddingChr) { return items.map(item => { let row = [] let numLines = 0 columnNames.forEach(columnName => { numLines = Math.max(numLines, item[columnName].length) }) // combine matching lines of each rows for (let i = 0; i < numLines; i++) { row[i] = row[i] || [] columnNames.forEach(columnName => { let column = columns[columnName] let val = item[columnName][i] || '' // || '' ensures empty columns get padded if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr)) else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr)) else row[i].push(padRight(val, column.width, paddingChr)) }) } return row }) }
javascript
function createRows(items, columns, columnNames, paddingChr) { return items.map(item => { let row = [] let numLines = 0 columnNames.forEach(columnName => { numLines = Math.max(numLines, item[columnName].length) }) // combine matching lines of each rows for (let i = 0; i < numLines; i++) { row[i] = row[i] || [] columnNames.forEach(columnName => { let column = columns[columnName] let val = item[columnName][i] || '' // || '' ensures empty columns get padded if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr)) else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr)) else row[i].push(padRight(val, column.width, paddingChr)) }) } return row }) }
[ "function", "createRows", "(", "items", ",", "columns", ",", "columnNames", ",", "paddingChr", ")", "{", "return", "items", ".", "map", "(", "item", "=>", "{", "let", "row", "=", "[", "]", "let", "numLines", "=", "0", "columnNames", ".", "forEach", "(", "columnName", "=>", "{", "numLines", "=", "Math", ".", "max", "(", "numLines", ",", "item", "[", "columnName", "]", ".", "length", ")", "}", ")", "// combine matching lines of each rows", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numLines", ";", "i", "++", ")", "{", "row", "[", "i", "]", "=", "row", "[", "i", "]", "||", "[", "]", "columnNames", ".", "forEach", "(", "columnName", "=>", "{", "let", "column", "=", "columns", "[", "columnName", "]", "let", "val", "=", "item", "[", "columnName", "]", "[", "i", "]", "||", "''", "// || '' ensures empty columns get padded", "if", "(", "column", ".", "align", "===", "'right'", ")", "row", "[", "i", "]", ".", "push", "(", "padLeft", "(", "val", ",", "column", ".", "width", ",", "paddingChr", ")", ")", "else", "if", "(", "column", ".", "align", "===", "'center'", "||", "column", ".", "align", "===", "'centre'", ")", "row", "[", "i", "]", ".", "push", "(", "padCenter", "(", "val", ",", "column", ".", "width", ",", "paddingChr", ")", ")", "else", "row", "[", "i", "]", ".", "push", "(", "padRight", "(", "val", ",", "column", ".", "width", ",", "paddingChr", ")", ")", "}", ")", "}", "return", "row", "}", ")", "}" ]
Convert wrapped lines into rows with padded values. @param Array items data to process @param Array columns column width settings for wrapping @param Array columnNames column ordering @return Array items wrapped in arrays, corresponding to lines
[ "Convert", "wrapped", "lines", "into", "rows", "with", "padded", "values", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/index.js#L206-L226
18,634
timoxley/columnify
index.js
endsWith
function endsWith(target, searchString, position) { position = position || target.length; position = position - searchString.length; let lastIndex = target.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; }
javascript
function endsWith(target, searchString, position) { position = position || target.length; position = position - searchString.length; let lastIndex = target.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; }
[ "function", "endsWith", "(", "target", ",", "searchString", ",", "position", ")", "{", "position", "=", "position", "||", "target", ".", "length", ";", "position", "=", "position", "-", "searchString", ".", "length", ";", "let", "lastIndex", "=", "target", ".", "lastIndexOf", "(", "searchString", ")", ";", "return", "lastIndex", "!==", "-", "1", "&&", "lastIndex", "===", "position", ";", "}" ]
Adapted from String.prototype.endsWith polyfill.
[ "Adapted", "from", "String", ".", "prototype", ".", "endsWith", "polyfill", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/index.js#L279-L284
18,635
timoxley/columnify
utils.js
repeatString
function repeatString(str, len) { return Array.apply(null, {length: len + 1}).join(str).slice(0, len) }
javascript
function repeatString(str, len) { return Array.apply(null, {length: len + 1}).join(str).slice(0, len) }
[ "function", "repeatString", "(", "str", ",", "len", ")", "{", "return", "Array", ".", "apply", "(", "null", ",", "{", "length", ":", "len", "+", "1", "}", ")", ".", "join", "(", "str", ")", ".", "slice", "(", "0", ",", "len", ")", "}" ]
repeat string `str` up to total length of `len` @param String str string to repeat @param Number len total length of output string
[ "repeat", "string", "str", "up", "to", "total", "length", "of", "len" ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/utils.js#L12-L14
18,636
timoxley/columnify
utils.js
padRight
function padRight(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str) if (length <= 0) return str return str + repeatString(chr || ' ', length) }
javascript
function padRight(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str) if (length <= 0) return str return str + repeatString(chr || ' ', length) }
[ "function", "padRight", "(", "str", ",", "max", ",", "chr", ")", "{", "str", "=", "str", "!=", "null", "?", "str", ":", "''", "str", "=", "String", "(", "str", ")", "var", "length", "=", "max", "-", "wcwidth", "(", "str", ")", "if", "(", "length", "<=", "0", ")", "return", "str", "return", "str", "+", "repeatString", "(", "chr", "||", "' '", ",", "length", ")", "}" ]
Pad `str` up to total length `max` with `chr`. If `str` is longer than `max`, padRight will return `str` unaltered. @param String str string to pad @param Number max total length of output string @param String chr optional. Character to pad with. default: ' ' @return String padded str
[ "Pad", "str", "up", "to", "total", "length", "max", "with", "chr", ".", "If", "str", "is", "longer", "than", "max", "padRight", "will", "return", "str", "unaltered", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/utils.js#L26-L32
18,637
timoxley/columnify
utils.js
padCenter
function padCenter(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str) if (length <= 0) return str var lengthLeft = Math.floor(length/2) var lengthRight = length - lengthLeft return repeatString(chr || ' ', lengthLeft) + str + repeatString(chr || ' ', lengthRight) }
javascript
function padCenter(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str) if (length <= 0) return str var lengthLeft = Math.floor(length/2) var lengthRight = length - lengthLeft return repeatString(chr || ' ', lengthLeft) + str + repeatString(chr || ' ', lengthRight) }
[ "function", "padCenter", "(", "str", ",", "max", ",", "chr", ")", "{", "str", "=", "str", "!=", "null", "?", "str", ":", "''", "str", "=", "String", "(", "str", ")", "var", "length", "=", "max", "-", "wcwidth", "(", "str", ")", "if", "(", "length", "<=", "0", ")", "return", "str", "var", "lengthLeft", "=", "Math", ".", "floor", "(", "length", "/", "2", ")", "var", "lengthRight", "=", "length", "-", "lengthLeft", "return", "repeatString", "(", "chr", "||", "' '", ",", "lengthLeft", ")", "+", "str", "+", "repeatString", "(", "chr", "||", "' '", ",", "lengthRight", ")", "}" ]
Pad `str` up to total length `max` with `chr`. If `str` is longer than `max`, padCenter will return `str` unaltered. @param String str string to pad @param Number max total length of output string @param String chr optional. Character to pad with. default: ' ' @return String padded str
[ "Pad", "str", "up", "to", "total", "length", "max", "with", "chr", ".", "If", "str", "is", "longer", "than", "max", "padCenter", "will", "return", "str", "unaltered", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/utils.js#L44-L52
18,638
timoxley/columnify
utils.js
splitIntoLines
function splitIntoLines(str, max) { function _splitIntoLines(str, max) { return str.trim().split(' ').reduce(function(lines, word) { var line = lines[lines.length - 1] if (line && wcwidth(line.join(' ')) + wcwidth(word) < max) { lines[lines.length - 1].push(word) // add to line } else lines.push([word]) // new line return lines }, []).map(function(l) { return l.join(' ') }) } return str.split('\n').map(function(str) { return _splitIntoLines(str, max) }).reduce(function(lines, line) { return lines.concat(line) }, []) }
javascript
function splitIntoLines(str, max) { function _splitIntoLines(str, max) { return str.trim().split(' ').reduce(function(lines, word) { var line = lines[lines.length - 1] if (line && wcwidth(line.join(' ')) + wcwidth(word) < max) { lines[lines.length - 1].push(word) // add to line } else lines.push([word]) // new line return lines }, []).map(function(l) { return l.join(' ') }) } return str.split('\n').map(function(str) { return _splitIntoLines(str, max) }).reduce(function(lines, line) { return lines.concat(line) }, []) }
[ "function", "splitIntoLines", "(", "str", ",", "max", ")", "{", "function", "_splitIntoLines", "(", "str", ",", "max", ")", "{", "return", "str", ".", "trim", "(", ")", ".", "split", "(", "' '", ")", ".", "reduce", "(", "function", "(", "lines", ",", "word", ")", "{", "var", "line", "=", "lines", "[", "lines", ".", "length", "-", "1", "]", "if", "(", "line", "&&", "wcwidth", "(", "line", ".", "join", "(", "' '", ")", ")", "+", "wcwidth", "(", "word", ")", "<", "max", ")", "{", "lines", "[", "lines", ".", "length", "-", "1", "]", ".", "push", "(", "word", ")", "// add to line", "}", "else", "lines", ".", "push", "(", "[", "word", "]", ")", "// new line", "return", "lines", "}", ",", "[", "]", ")", ".", "map", "(", "function", "(", "l", ")", "{", "return", "l", ".", "join", "(", "' '", ")", "}", ")", "}", "return", "str", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "str", ")", "{", "return", "_splitIntoLines", "(", "str", ",", "max", ")", "}", ")", ".", "reduce", "(", "function", "(", "lines", ",", "line", ")", "{", "return", "lines", ".", "concat", "(", "line", ")", "}", ",", "[", "]", ")", "}" ]
Split a String `str` into lines of maxiumum length `max`. Splits on word boundaries. Preserves existing new lines. @param String str string to split @param Number max length of each line @return Array Array containing lines.
[ "Split", "a", "String", "str", "into", "lines", "of", "maxiumum", "length", "max", ".", "Splits", "on", "word", "boundaries", ".", "Preserves", "existing", "new", "lines", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/utils.js#L81-L99
18,639
timoxley/columnify
utils.js
splitLongWords
function splitLongWords(str, max, truncationChar) { str = str.trim() var result = [] var words = str.split(' ') var remainder = '' var truncationWidth = wcwidth(truncationChar) while (remainder || words.length) { if (remainder) { var word = remainder remainder = '' } else { var word = words.shift() } if (wcwidth(word) > max) { // slice is based on length no wcwidth var i = 0 var wwidth = 0 var limit = max - truncationWidth while (i < word.length) { var w = wcwidth(word.charAt(i)) if (w + wwidth > limit) { break } wwidth += w ++i } remainder = word.slice(i) // get remainder // save remainder for next loop word = word.slice(0, i) // grab truncated word word += truncationChar // add trailing … or whatever } result.push(word) } return result.join(' ') }
javascript
function splitLongWords(str, max, truncationChar) { str = str.trim() var result = [] var words = str.split(' ') var remainder = '' var truncationWidth = wcwidth(truncationChar) while (remainder || words.length) { if (remainder) { var word = remainder remainder = '' } else { var word = words.shift() } if (wcwidth(word) > max) { // slice is based on length no wcwidth var i = 0 var wwidth = 0 var limit = max - truncationWidth while (i < word.length) { var w = wcwidth(word.charAt(i)) if (w + wwidth > limit) { break } wwidth += w ++i } remainder = word.slice(i) // get remainder // save remainder for next loop word = word.slice(0, i) // grab truncated word word += truncationChar // add trailing … or whatever } result.push(word) } return result.join(' ') }
[ "function", "splitLongWords", "(", "str", ",", "max", ",", "truncationChar", ")", "{", "str", "=", "str", ".", "trim", "(", ")", "var", "result", "=", "[", "]", "var", "words", "=", "str", ".", "split", "(", "' '", ")", "var", "remainder", "=", "''", "var", "truncationWidth", "=", "wcwidth", "(", "truncationChar", ")", "while", "(", "remainder", "||", "words", ".", "length", ")", "{", "if", "(", "remainder", ")", "{", "var", "word", "=", "remainder", "remainder", "=", "''", "}", "else", "{", "var", "word", "=", "words", ".", "shift", "(", ")", "}", "if", "(", "wcwidth", "(", "word", ")", ">", "max", ")", "{", "// slice is based on length no wcwidth", "var", "i", "=", "0", "var", "wwidth", "=", "0", "var", "limit", "=", "max", "-", "truncationWidth", "while", "(", "i", "<", "word", ".", "length", ")", "{", "var", "w", "=", "wcwidth", "(", "word", ".", "charAt", "(", "i", ")", ")", "if", "(", "w", "+", "wwidth", ">", "limit", ")", "{", "break", "}", "wwidth", "+=", "w", "++", "i", "}", "remainder", "=", "word", ".", "slice", "(", "i", ")", "// get remainder", "// save remainder for next loop", "word", "=", "word", ".", "slice", "(", "0", ",", "i", ")", "// grab truncated word", "word", "+=", "truncationChar", "// add trailing … or whatever", "}", "result", ".", "push", "(", "word", ")", "}", "return", "result", ".", "join", "(", "' '", ")", "}" ]
Add spaces and `truncationChar` between words of `str` which are longer than `max`. @param String str string to split @param Number max length of each line @param Number truncationChar character to append to split words @return String
[ "Add", "spaces", "and", "truncationChar", "between", "words", "of", "str", "which", "are", "longer", "than", "max", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/utils.js#L111-L151
18,640
timoxley/columnify
utils.js
truncateString
function truncateString(str, max) { str = str != null ? str : '' str = String(str) if(max == Infinity) return str var i = 0 var wwidth = 0 while (i < str.length) { var w = wcwidth(str.charAt(i)) if(w + wwidth > max) break wwidth += w ++i } return str.slice(0, i) }
javascript
function truncateString(str, max) { str = str != null ? str : '' str = String(str) if(max == Infinity) return str var i = 0 var wwidth = 0 while (i < str.length) { var w = wcwidth(str.charAt(i)) if(w + wwidth > max) break wwidth += w ++i } return str.slice(0, i) }
[ "function", "truncateString", "(", "str", ",", "max", ")", "{", "str", "=", "str", "!=", "null", "?", "str", ":", "''", "str", "=", "String", "(", "str", ")", "if", "(", "max", "==", "Infinity", ")", "return", "str", "var", "i", "=", "0", "var", "wwidth", "=", "0", "while", "(", "i", "<", "str", ".", "length", ")", "{", "var", "w", "=", "wcwidth", "(", "str", ".", "charAt", "(", "i", ")", ")", "if", "(", "w", "+", "wwidth", ">", "max", ")", "break", "wwidth", "+=", "w", "++", "i", "}", "return", "str", ".", "slice", "(", "0", ",", "i", ")", "}" ]
Truncate `str` into total width `max` If `str` is shorter than `max`, will return `str` unaltered. @param String str string to truncated @param Number max total wcwidth of output string @return String truncated str
[ "Truncate", "str", "into", "total", "width", "max", "If", "str", "is", "shorter", "than", "max", "will", "return", "str", "unaltered", "." ]
101fc3856df38bb5f231cb62a40b8b407f8a871b
https://github.com/timoxley/columnify/blob/101fc3856df38bb5f231cb62a40b8b407f8a871b/utils.js#L163-L180
18,641
anseki/plain-draggable
src/plain-draggable.js
initTranslate
function initTranslate(props) { const element = props.element, elementStyle = props.elementStyle, curPosition = getBBox(element), // Get BBox before change style. RESTORE_PROPS = ['display', 'marginTop', 'marginBottom', 'width', 'height']; RESTORE_PROPS.unshift(cssPropTransform); // Reset `transition-property` every time because it might be changed frequently. const orgTransitionProperty = elementStyle[cssPropTransitionProperty]; elementStyle[cssPropTransitionProperty] = 'none'; // Disable animation const fixPosition = getBBox(element); if (!props.orgStyle) { props.orgStyle = RESTORE_PROPS.reduce((orgStyle, prop) => { orgStyle[prop] = elementStyle[prop] || ''; return orgStyle; }, {}); props.lastStyle = {}; } else { RESTORE_PROPS.forEach(prop => { // Skip this if it seems user changed it. (it can't check perfectly.) if (props.lastStyle[prop] == null || elementStyle[prop] === props.lastStyle[prop]) { elementStyle[prop] = props.orgStyle[prop]; } }); } const orgSize = getBBox(element), cmpStyle = window.getComputedStyle(element, ''); // https://www.w3.org/TR/css-transforms-1/#transformable-element if (cmpStyle.display === 'inline') { elementStyle.display = 'inline-block'; ['Top', 'Bottom'].forEach(dirProp => { const padding = parseFloat(cmpStyle[`padding${dirProp}`]); // paddingTop/Bottom make padding but don't make space -> negative margin in inline-block // marginTop/Bottom don't work in inline element -> `0` in inline-block elementStyle[`margin${dirProp}`] = padding ? `-${padding}px` : '0'; }); } elementStyle[cssPropTransform] = 'translate(0, 0)'; // Get document offset. let newBBox = getBBox(element); const offset = props.htmlOffset = {left: newBBox.left ? -newBBox.left : 0, top: newBBox.top ? -newBBox.top : 0}; // avoid `-0` // Restore position elementStyle[cssPropTransform] = `translate(${curPosition.left + offset.left}px, ${curPosition.top + offset.top}px)`; // Restore size ['width', 'height'].forEach(prop => { if (newBBox[prop] !== orgSize[prop]) { // Ignore `box-sizing` elementStyle[prop] = orgSize[prop] + 'px'; newBBox = getBBox(element); if (newBBox[prop] !== orgSize[prop]) { // Retry elementStyle[prop] = orgSize[prop] - (newBBox[prop] - orgSize[prop]) + 'px'; } } props.lastStyle[prop] = elementStyle[prop]; }); // Restore `transition-property` element.offsetWidth; /* force reflow */ // eslint-disable-line no-unused-expressions elementStyle[cssPropTransitionProperty] = orgTransitionProperty; if (fixPosition.left !== curPosition.left || fixPosition.top !== curPosition.top) { // It seems that it is moving. elementStyle[cssPropTransform] = `translate(${fixPosition.left + offset.left}px, ${fixPosition.top + offset.top}px)`; } return fixPosition; }
javascript
function initTranslate(props) { const element = props.element, elementStyle = props.elementStyle, curPosition = getBBox(element), // Get BBox before change style. RESTORE_PROPS = ['display', 'marginTop', 'marginBottom', 'width', 'height']; RESTORE_PROPS.unshift(cssPropTransform); // Reset `transition-property` every time because it might be changed frequently. const orgTransitionProperty = elementStyle[cssPropTransitionProperty]; elementStyle[cssPropTransitionProperty] = 'none'; // Disable animation const fixPosition = getBBox(element); if (!props.orgStyle) { props.orgStyle = RESTORE_PROPS.reduce((orgStyle, prop) => { orgStyle[prop] = elementStyle[prop] || ''; return orgStyle; }, {}); props.lastStyle = {}; } else { RESTORE_PROPS.forEach(prop => { // Skip this if it seems user changed it. (it can't check perfectly.) if (props.lastStyle[prop] == null || elementStyle[prop] === props.lastStyle[prop]) { elementStyle[prop] = props.orgStyle[prop]; } }); } const orgSize = getBBox(element), cmpStyle = window.getComputedStyle(element, ''); // https://www.w3.org/TR/css-transforms-1/#transformable-element if (cmpStyle.display === 'inline') { elementStyle.display = 'inline-block'; ['Top', 'Bottom'].forEach(dirProp => { const padding = parseFloat(cmpStyle[`padding${dirProp}`]); // paddingTop/Bottom make padding but don't make space -> negative margin in inline-block // marginTop/Bottom don't work in inline element -> `0` in inline-block elementStyle[`margin${dirProp}`] = padding ? `-${padding}px` : '0'; }); } elementStyle[cssPropTransform] = 'translate(0, 0)'; // Get document offset. let newBBox = getBBox(element); const offset = props.htmlOffset = {left: newBBox.left ? -newBBox.left : 0, top: newBBox.top ? -newBBox.top : 0}; // avoid `-0` // Restore position elementStyle[cssPropTransform] = `translate(${curPosition.left + offset.left}px, ${curPosition.top + offset.top}px)`; // Restore size ['width', 'height'].forEach(prop => { if (newBBox[prop] !== orgSize[prop]) { // Ignore `box-sizing` elementStyle[prop] = orgSize[prop] + 'px'; newBBox = getBBox(element); if (newBBox[prop] !== orgSize[prop]) { // Retry elementStyle[prop] = orgSize[prop] - (newBBox[prop] - orgSize[prop]) + 'px'; } } props.lastStyle[prop] = elementStyle[prop]; }); // Restore `transition-property` element.offsetWidth; /* force reflow */ // eslint-disable-line no-unused-expressions elementStyle[cssPropTransitionProperty] = orgTransitionProperty; if (fixPosition.left !== curPosition.left || fixPosition.top !== curPosition.top) { // It seems that it is moving. elementStyle[cssPropTransform] = `translate(${fixPosition.left + offset.left}px, ${fixPosition.top + offset.top}px)`; } return fixPosition; }
[ "function", "initTranslate", "(", "props", ")", "{", "const", "element", "=", "props", ".", "element", ",", "elementStyle", "=", "props", ".", "elementStyle", ",", "curPosition", "=", "getBBox", "(", "element", ")", ",", "// Get BBox before change style.", "RESTORE_PROPS", "=", "[", "'display'", ",", "'marginTop'", ",", "'marginBottom'", ",", "'width'", ",", "'height'", "]", ";", "RESTORE_PROPS", ".", "unshift", "(", "cssPropTransform", ")", ";", "// Reset `transition-property` every time because it might be changed frequently.", "const", "orgTransitionProperty", "=", "elementStyle", "[", "cssPropTransitionProperty", "]", ";", "elementStyle", "[", "cssPropTransitionProperty", "]", "=", "'none'", ";", "// Disable animation", "const", "fixPosition", "=", "getBBox", "(", "element", ")", ";", "if", "(", "!", "props", ".", "orgStyle", ")", "{", "props", ".", "orgStyle", "=", "RESTORE_PROPS", ".", "reduce", "(", "(", "orgStyle", ",", "prop", ")", "=>", "{", "orgStyle", "[", "prop", "]", "=", "elementStyle", "[", "prop", "]", "||", "''", ";", "return", "orgStyle", ";", "}", ",", "{", "}", ")", ";", "props", ".", "lastStyle", "=", "{", "}", ";", "}", "else", "{", "RESTORE_PROPS", ".", "forEach", "(", "prop", "=>", "{", "// Skip this if it seems user changed it. (it can't check perfectly.)", "if", "(", "props", ".", "lastStyle", "[", "prop", "]", "==", "null", "||", "elementStyle", "[", "prop", "]", "===", "props", ".", "lastStyle", "[", "prop", "]", ")", "{", "elementStyle", "[", "prop", "]", "=", "props", ".", "orgStyle", "[", "prop", "]", ";", "}", "}", ")", ";", "}", "const", "orgSize", "=", "getBBox", "(", "element", ")", ",", "cmpStyle", "=", "window", ".", "getComputedStyle", "(", "element", ",", "''", ")", ";", "// https://www.w3.org/TR/css-transforms-1/#transformable-element", "if", "(", "cmpStyle", ".", "display", "===", "'inline'", ")", "{", "elementStyle", ".", "display", "=", "'inline-block'", ";", "[", "'Top'", ",", "'Bottom'", "]", ".", "forEach", "(", "dirProp", "=>", "{", "const", "padding", "=", "parseFloat", "(", "cmpStyle", "[", "`", "${", "dirProp", "}", "`", "]", ")", ";", "// paddingTop/Bottom make padding but don't make space -> negative margin in inline-block", "// marginTop/Bottom don't work in inline element -> `0` in inline-block", "elementStyle", "[", "`", "${", "dirProp", "}", "`", "]", "=", "padding", "?", "`", "${", "padding", "}", "`", ":", "'0'", ";", "}", ")", ";", "}", "elementStyle", "[", "cssPropTransform", "]", "=", "'translate(0, 0)'", ";", "// Get document offset.", "let", "newBBox", "=", "getBBox", "(", "element", ")", ";", "const", "offset", "=", "props", ".", "htmlOffset", "=", "{", "left", ":", "newBBox", ".", "left", "?", "-", "newBBox", ".", "left", ":", "0", ",", "top", ":", "newBBox", ".", "top", "?", "-", "newBBox", ".", "top", ":", "0", "}", ";", "// avoid `-0`", "// Restore position", "elementStyle", "[", "cssPropTransform", "]", "=", "`", "${", "curPosition", ".", "left", "+", "offset", ".", "left", "}", "${", "curPosition", ".", "top", "+", "offset", ".", "top", "}", "`", ";", "// Restore size", "[", "'width'", ",", "'height'", "]", ".", "forEach", "(", "prop", "=>", "{", "if", "(", "newBBox", "[", "prop", "]", "!==", "orgSize", "[", "prop", "]", ")", "{", "// Ignore `box-sizing`", "elementStyle", "[", "prop", "]", "=", "orgSize", "[", "prop", "]", "+", "'px'", ";", "newBBox", "=", "getBBox", "(", "element", ")", ";", "if", "(", "newBBox", "[", "prop", "]", "!==", "orgSize", "[", "prop", "]", ")", "{", "// Retry", "elementStyle", "[", "prop", "]", "=", "orgSize", "[", "prop", "]", "-", "(", "newBBox", "[", "prop", "]", "-", "orgSize", "[", "prop", "]", ")", "+", "'px'", ";", "}", "}", "props", ".", "lastStyle", "[", "prop", "]", "=", "elementStyle", "[", "prop", "]", ";", "}", ")", ";", "// Restore `transition-property`", "element", ".", "offsetWidth", ";", "/* force reflow */", "// eslint-disable-line no-unused-expressions", "elementStyle", "[", "cssPropTransitionProperty", "]", "=", "orgTransitionProperty", ";", "if", "(", "fixPosition", ".", "left", "!==", "curPosition", ".", "left", "||", "fixPosition", ".", "top", "!==", "curPosition", ".", "top", ")", "{", "// It seems that it is moving.", "elementStyle", "[", "cssPropTransform", "]", "=", "`", "${", "fixPosition", ".", "left", "+", "offset", ".", "left", "}", "${", "fixPosition", ".", "top", "+", "offset", ".", "top", "}", "`", ";", "}", "return", "fixPosition", ";", "}" ]
Initialize HTMLElement for `translate`, and get `offset` that is used by `moveTranslate`. @param {props} props - `props` of instance. @returns {BBox} Current BBox without animation, i.e. left/top properties.
[ "Initialize", "HTMLElement", "for", "translate", "and", "get", "offset", "that", "is", "used", "by", "moveTranslate", "." ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/src/plain-draggable.js#L670-L741
18,642
anseki/plain-draggable
plain-draggable-limit.esm.js
validPPValue
function validPPValue(value) { // Get PPValue from string (all `/s` were already removed) function string2PPValue(inString) { var matches = /^(.+?)(%)?$/.exec(inString); var value = void 0, isRatio = void 0; return matches && isFinite(value = parseFloat(matches[1])) ? { value: (isRatio = !!(matches[2] && value)) ? value / 100 : value, isRatio: isRatio } : null; // 0% -> 0 } return isFinite(value) ? { value: value, isRatio: false } : typeof value === 'string' ? string2PPValue(value.replace(/\s/g, '')) : null; }
javascript
function validPPValue(value) { // Get PPValue from string (all `/s` were already removed) function string2PPValue(inString) { var matches = /^(.+?)(%)?$/.exec(inString); var value = void 0, isRatio = void 0; return matches && isFinite(value = parseFloat(matches[1])) ? { value: (isRatio = !!(matches[2] && value)) ? value / 100 : value, isRatio: isRatio } : null; // 0% -> 0 } return isFinite(value) ? { value: value, isRatio: false } : typeof value === 'string' ? string2PPValue(value.replace(/\s/g, '')) : null; }
[ "function", "validPPValue", "(", "value", ")", "{", "// Get PPValue from string (all `/s` were already removed)", "function", "string2PPValue", "(", "inString", ")", "{", "var", "matches", "=", "/", "^(.+?)(%)?$", "/", ".", "exec", "(", "inString", ")", ";", "var", "value", "=", "void", "0", ",", "isRatio", "=", "void", "0", ";", "return", "matches", "&&", "isFinite", "(", "value", "=", "parseFloat", "(", "matches", "[", "1", "]", ")", ")", "?", "{", "value", ":", "(", "isRatio", "=", "!", "!", "(", "matches", "[", "2", "]", "&&", "value", ")", ")", "?", "value", "/", "100", ":", "value", ",", "isRatio", ":", "isRatio", "}", ":", "null", ";", "// 0% -> 0", "}", "return", "isFinite", "(", "value", ")", "?", "{", "value", ":", "value", ",", "isRatio", ":", "false", "}", ":", "typeof", "value", "===", "'string'", "?", "string2PPValue", "(", "value", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ")", ":", "null", ";", "}" ]
A value that is Pixels or Ratio @typedef {{value: number, isRatio: boolean}} PPValue
[ "A", "value", "that", "is", "Pixels", "or", "Ratio" ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/plain-draggable-limit.esm.js#L159-L170
18,643
anseki/plain-draggable
plain-draggable-limit.esm.js
validPPBBox
function validPPBBox(bBox) { if (!isObject(bBox)) { return null; } var ppValue = void 0; if ((ppValue = validPPValue(bBox.left)) || (ppValue = validPPValue(bBox.x))) { bBox.left = bBox.x = ppValue; } else { return null; } if ((ppValue = validPPValue(bBox.top)) || (ppValue = validPPValue(bBox.y))) { bBox.top = bBox.y = ppValue; } else { return null; } if ((ppValue = validPPValue(bBox.width)) && ppValue.value >= 0) { bBox.width = ppValue; delete bBox.right; } else if (ppValue = validPPValue(bBox.right)) { bBox.right = ppValue; delete bBox.width; } else { return null; } if ((ppValue = validPPValue(bBox.height)) && ppValue.value >= 0) { bBox.height = ppValue; delete bBox.bottom; } else if (ppValue = validPPValue(bBox.bottom)) { bBox.bottom = ppValue; delete bBox.height; } else { return null; } return bBox; }
javascript
function validPPBBox(bBox) { if (!isObject(bBox)) { return null; } var ppValue = void 0; if ((ppValue = validPPValue(bBox.left)) || (ppValue = validPPValue(bBox.x))) { bBox.left = bBox.x = ppValue; } else { return null; } if ((ppValue = validPPValue(bBox.top)) || (ppValue = validPPValue(bBox.y))) { bBox.top = bBox.y = ppValue; } else { return null; } if ((ppValue = validPPValue(bBox.width)) && ppValue.value >= 0) { bBox.width = ppValue; delete bBox.right; } else if (ppValue = validPPValue(bBox.right)) { bBox.right = ppValue; delete bBox.width; } else { return null; } if ((ppValue = validPPValue(bBox.height)) && ppValue.value >= 0) { bBox.height = ppValue; delete bBox.bottom; } else if (ppValue = validPPValue(bBox.bottom)) { bBox.bottom = ppValue; delete bBox.height; } else { return null; } return bBox; }
[ "function", "validPPBBox", "(", "bBox", ")", "{", "if", "(", "!", "isObject", "(", "bBox", ")", ")", "{", "return", "null", ";", "}", "var", "ppValue", "=", "void", "0", ";", "if", "(", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "left", ")", ")", "||", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "x", ")", ")", ")", "{", "bBox", ".", "left", "=", "bBox", ".", "x", "=", "ppValue", ";", "}", "else", "{", "return", "null", ";", "}", "if", "(", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "top", ")", ")", "||", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "y", ")", ")", ")", "{", "bBox", ".", "top", "=", "bBox", ".", "y", "=", "ppValue", ";", "}", "else", "{", "return", "null", ";", "}", "if", "(", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "width", ")", ")", "&&", "ppValue", ".", "value", ">=", "0", ")", "{", "bBox", ".", "width", "=", "ppValue", ";", "delete", "bBox", ".", "right", ";", "}", "else", "if", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "right", ")", ")", "{", "bBox", ".", "right", "=", "ppValue", ";", "delete", "bBox", ".", "width", ";", "}", "else", "{", "return", "null", ";", "}", "if", "(", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "height", ")", ")", "&&", "ppValue", ".", "value", ">=", "0", ")", "{", "bBox", ".", "height", "=", "ppValue", ";", "delete", "bBox", ".", "bottom", ";", "}", "else", "if", "(", "ppValue", "=", "validPPValue", "(", "bBox", ".", "bottom", ")", ")", "{", "bBox", ".", "bottom", "=", "ppValue", ";", "delete", "bBox", ".", "height", ";", "}", "else", "{", "return", "null", ";", "}", "return", "bBox", ";", "}" ]
An object that simulates BBox but properties are PPValue. @typedef {Object} PPBBox @param {Object} bBox - A target object. @returns {(PPBBox|null)} A normalized `PPBBox`, or null if `bBox` is invalid.
[ "An", "object", "that", "simulates", "BBox", "but", "properties", "are", "PPValue", "." ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/plain-draggable-limit.esm.js#L189-L224
18,644
anseki/plain-draggable
plain-draggable-limit.esm.js
resolvePPBBox
function resolvePPBBox(ppBBox, baseBBox) { var prop2Axis = { left: 'x', right: 'x', x: 'x', width: 'x', top: 'y', bottom: 'y', y: 'y', height: 'y' }, baseOriginXY = { x: baseBBox.left, y: baseBBox.top }, baseSizeXY = { x: baseBBox.width, y: baseBBox.height }; return validBBox(Object.keys(ppBBox).reduce(function (bBox, prop) { bBox[prop] = resolvePPValue(ppBBox[prop], prop === 'width' || prop === 'height' ? 0 : baseOriginXY[prop2Axis[prop]], baseSizeXY[prop2Axis[prop]]); return bBox; }, {})); }
javascript
function resolvePPBBox(ppBBox, baseBBox) { var prop2Axis = { left: 'x', right: 'x', x: 'x', width: 'x', top: 'y', bottom: 'y', y: 'y', height: 'y' }, baseOriginXY = { x: baseBBox.left, y: baseBBox.top }, baseSizeXY = { x: baseBBox.width, y: baseBBox.height }; return validBBox(Object.keys(ppBBox).reduce(function (bBox, prop) { bBox[prop] = resolvePPValue(ppBBox[prop], prop === 'width' || prop === 'height' ? 0 : baseOriginXY[prop2Axis[prop]], baseSizeXY[prop2Axis[prop]]); return bBox; }, {})); }
[ "function", "resolvePPBBox", "(", "ppBBox", ",", "baseBBox", ")", "{", "var", "prop2Axis", "=", "{", "left", ":", "'x'", ",", "right", ":", "'x'", ",", "x", ":", "'x'", ",", "width", ":", "'x'", ",", "top", ":", "'y'", ",", "bottom", ":", "'y'", ",", "y", ":", "'y'", ",", "height", ":", "'y'", "}", ",", "baseOriginXY", "=", "{", "x", ":", "baseBBox", ".", "left", ",", "y", ":", "baseBBox", ".", "top", "}", ",", "baseSizeXY", "=", "{", "x", ":", "baseBBox", ".", "width", ",", "y", ":", "baseBBox", ".", "height", "}", ";", "return", "validBBox", "(", "Object", ".", "keys", "(", "ppBBox", ")", ".", "reduce", "(", "function", "(", "bBox", ",", "prop", ")", "{", "bBox", "[", "prop", "]", "=", "resolvePPValue", "(", "ppBBox", "[", "prop", "]", ",", "prop", "===", "'width'", "||", "prop", "===", "'height'", "?", "0", ":", "baseOriginXY", "[", "prop2Axis", "[", "prop", "]", "]", ",", "baseSizeXY", "[", "prop2Axis", "[", "prop", "]", "]", ")", ";", "return", "bBox", ";", "}", ",", "{", "}", ")", ")", ";", "}" ]
PPBBox -> BBox
[ "PPBBox", "-", ">", "BBox" ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/plain-draggable-limit.esm.js#L234-L243
18,645
anseki/plain-draggable
plain-draggable-limit.esm.js
initAnim
function initAnim(element, gpuTrigger) { var style = element.style; style.webkitTapHighlightColor = 'transparent'; // Only when it has no shadow var cssPropBoxShadow = CSSPrefix.getName('boxShadow'), boxShadow = window.getComputedStyle(element, '')[cssPropBoxShadow]; if (!boxShadow || boxShadow === 'none') { style[cssPropBoxShadow] = '0 0 1px transparent'; } if (gpuTrigger && cssPropTransform) { style[cssPropTransform] = 'translateZ(0)'; } return element; }
javascript
function initAnim(element, gpuTrigger) { var style = element.style; style.webkitTapHighlightColor = 'transparent'; // Only when it has no shadow var cssPropBoxShadow = CSSPrefix.getName('boxShadow'), boxShadow = window.getComputedStyle(element, '')[cssPropBoxShadow]; if (!boxShadow || boxShadow === 'none') { style[cssPropBoxShadow] = '0 0 1px transparent'; } if (gpuTrigger && cssPropTransform) { style[cssPropTransform] = 'translateZ(0)'; } return element; }
[ "function", "initAnim", "(", "element", ",", "gpuTrigger", ")", "{", "var", "style", "=", "element", ".", "style", ";", "style", ".", "webkitTapHighlightColor", "=", "'transparent'", ";", "// Only when it has no shadow", "var", "cssPropBoxShadow", "=", "CSSPrefix", ".", "getName", "(", "'boxShadow'", ")", ",", "boxShadow", "=", "window", ".", "getComputedStyle", "(", "element", ",", "''", ")", "[", "cssPropBoxShadow", "]", ";", "if", "(", "!", "boxShadow", "||", "boxShadow", "===", "'none'", ")", "{", "style", "[", "cssPropBoxShadow", "]", "=", "'0 0 1px transparent'", ";", "}", "if", "(", "gpuTrigger", "&&", "cssPropTransform", ")", "{", "style", "[", "cssPropTransform", "]", "=", "'translateZ(0)'", ";", "}", "return", "element", ";", "}" ]
Optimize an element for animation. @param {Element} element - A target element. @param {?boolean} gpuTrigger - Initialize for SVGElement if `true`. @returns {Element} A target element.
[ "Optimize", "an", "element", "for", "animation", "." ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/plain-draggable-limit.esm.js#L275-L290
18,646
anseki/plain-draggable
plain-draggable-limit.esm.js
moveTranslate
function moveTranslate(props, position) { var elementBBox = props.elementBBox; if (position.left !== elementBBox.left || position.top !== elementBBox.top) { var offset = props.htmlOffset; props.elementStyle[cssPropTransform] = 'translate(' + (position.left + offset.left) + 'px, ' + (position.top + offset.top) + 'px)'; return true; } return false; }
javascript
function moveTranslate(props, position) { var elementBBox = props.elementBBox; if (position.left !== elementBBox.left || position.top !== elementBBox.top) { var offset = props.htmlOffset; props.elementStyle[cssPropTransform] = 'translate(' + (position.left + offset.left) + 'px, ' + (position.top + offset.top) + 'px)'; return true; } return false; }
[ "function", "moveTranslate", "(", "props", ",", "position", ")", "{", "var", "elementBBox", "=", "props", ".", "elementBBox", ";", "if", "(", "position", ".", "left", "!==", "elementBBox", ".", "left", "||", "position", ".", "top", "!==", "elementBBox", ".", "top", ")", "{", "var", "offset", "=", "props", ".", "htmlOffset", ";", "props", ".", "elementStyle", "[", "cssPropTransform", "]", "=", "'translate('", "+", "(", "position", ".", "left", "+", "offset", ".", "left", ")", "+", "'px, '", "+", "(", "position", ".", "top", "+", "offset", ".", "top", ")", "+", "'px)'", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Move by `translate`. @param {props} props - `props` of instance. @param {{left: number, top: number}} position - New position. @returns {boolean} `true` if it was moved.
[ "Move", "by", "translate", "." ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/plain-draggable-limit.esm.js#L327-L335
18,647
anseki/plain-draggable
plain-draggable-limit.esm.js
move
function move(props, position, cbCheck) { var elementBBox = props.elementBBox; function fix() { if (props.minLeft >= props.maxLeft) { // Disabled position.left = elementBBox.left; } else if (position.left < props.minLeft) { position.left = props.minLeft; } else if (position.left > props.maxLeft) { position.left = props.maxLeft; } if (props.minTop >= props.maxTop) { // Disabled position.top = elementBBox.top; } else if (position.top < props.minTop) { position.top = props.minTop; } else if (position.top > props.maxTop) { position.top = props.maxTop; } } fix(); if (cbCheck) { if (cbCheck(position) === false) { return false; } fix(); // Again } var moved = props.moveElm(props, position); if (moved) { // Update elementBBox props.elementBBox = validBBox({ left: position.left, top: position.top, width: elementBBox.width, height: elementBBox.height }); } return moved; }
javascript
function move(props, position, cbCheck) { var elementBBox = props.elementBBox; function fix() { if (props.minLeft >= props.maxLeft) { // Disabled position.left = elementBBox.left; } else if (position.left < props.minLeft) { position.left = props.minLeft; } else if (position.left > props.maxLeft) { position.left = props.maxLeft; } if (props.minTop >= props.maxTop) { // Disabled position.top = elementBBox.top; } else if (position.top < props.minTop) { position.top = props.minTop; } else if (position.top > props.maxTop) { position.top = props.maxTop; } } fix(); if (cbCheck) { if (cbCheck(position) === false) { return false; } fix(); // Again } var moved = props.moveElm(props, position); if (moved) { // Update elementBBox props.elementBBox = validBBox({ left: position.left, top: position.top, width: elementBBox.width, height: elementBBox.height }); } return moved; }
[ "function", "move", "(", "props", ",", "position", ",", "cbCheck", ")", "{", "var", "elementBBox", "=", "props", ".", "elementBBox", ";", "function", "fix", "(", ")", "{", "if", "(", "props", ".", "minLeft", ">=", "props", ".", "maxLeft", ")", "{", "// Disabled", "position", ".", "left", "=", "elementBBox", ".", "left", ";", "}", "else", "if", "(", "position", ".", "left", "<", "props", ".", "minLeft", ")", "{", "position", ".", "left", "=", "props", ".", "minLeft", ";", "}", "else", "if", "(", "position", ".", "left", ">", "props", ".", "maxLeft", ")", "{", "position", ".", "left", "=", "props", ".", "maxLeft", ";", "}", "if", "(", "props", ".", "minTop", ">=", "props", ".", "maxTop", ")", "{", "// Disabled", "position", ".", "top", "=", "elementBBox", ".", "top", ";", "}", "else", "if", "(", "position", ".", "top", "<", "props", ".", "minTop", ")", "{", "position", ".", "top", "=", "props", ".", "minTop", ";", "}", "else", "if", "(", "position", ".", "top", ">", "props", ".", "maxTop", ")", "{", "position", ".", "top", "=", "props", ".", "maxTop", ";", "}", "}", "fix", "(", ")", ";", "if", "(", "cbCheck", ")", "{", "if", "(", "cbCheck", "(", "position", ")", "===", "false", ")", "{", "return", "false", ";", "}", "fix", "(", ")", ";", "// Again", "}", "var", "moved", "=", "props", ".", "moveElm", "(", "props", ",", "position", ")", ";", "if", "(", "moved", ")", "{", "// Update elementBBox", "props", ".", "elementBBox", "=", "validBBox", "(", "{", "left", ":", "position", ".", "left", ",", "top", ":", "position", ".", "top", ",", "width", ":", "elementBBox", ".", "width", ",", "height", ":", "elementBBox", ".", "height", "}", ")", ";", "}", "return", "moved", ";", "}" ]
Set `props.element` position. @param {props} props - `props` of instance. @param {{left: number, top: number}} position - New position. @param {function} [cbCheck] - Callback that is called with valid position, cancel moving if it returns `false`. @returns {boolean} `true` if it was moved.
[ "Set", "props", ".", "element", "position", "." ]
455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8
https://github.com/anseki/plain-draggable/blob/455d48dc0369c37d10d7e07cd8a2a33c12f1a1c8/plain-draggable-limit.esm.js#L344-L381
18,648
bootprint/bootprint-openapi
.thought/helpers.js
function (options) { return qfs.listTree('.', function (filePath) { var file = path.basename(filePath) // Do not traverse into the node_modules directory if (file === 'node_modules' || file === '.git') { return null } // Collect all files "credits.md" if (file === 'credits.md.hbs') { return true } return false }).then(function (creditFiles) { return deep(creditFiles.map(function (creditFile) { console.log("Using credit file", creditFile) var input = _.merge({}, this, { __dirname: path.dirname(creditFile), __filename: creditFile }) return qfs.read(creditFile).then(function (contents) { return options.customize.engine.compile(contents)(input) }) })) }) }
javascript
function (options) { return qfs.listTree('.', function (filePath) { var file = path.basename(filePath) // Do not traverse into the node_modules directory if (file === 'node_modules' || file === '.git') { return null } // Collect all files "credits.md" if (file === 'credits.md.hbs') { return true } return false }).then(function (creditFiles) { return deep(creditFiles.map(function (creditFile) { console.log("Using credit file", creditFile) var input = _.merge({}, this, { __dirname: path.dirname(creditFile), __filename: creditFile }) return qfs.read(creditFile).then(function (contents) { return options.customize.engine.compile(contents)(input) }) })) }) }
[ "function", "(", "options", ")", "{", "return", "qfs", ".", "listTree", "(", "'.'", ",", "function", "(", "filePath", ")", "{", "var", "file", "=", "path", ".", "basename", "(", "filePath", ")", "// Do not traverse into the node_modules directory", "if", "(", "file", "===", "'node_modules'", "||", "file", "===", "'.git'", ")", "{", "return", "null", "}", "// Collect all files \"credits.md\"", "if", "(", "file", "===", "'credits.md.hbs'", ")", "{", "return", "true", "}", "return", "false", "}", ")", ".", "then", "(", "function", "(", "creditFiles", ")", "{", "return", "deep", "(", "creditFiles", ".", "map", "(", "function", "(", "creditFile", ")", "{", "console", ".", "log", "(", "\"Using credit file\"", ",", "creditFile", ")", "var", "input", "=", "_", ".", "merge", "(", "{", "}", ",", "this", ",", "{", "__dirname", ":", "path", ".", "dirname", "(", "creditFile", ")", ",", "__filename", ":", "creditFile", "}", ")", "return", "qfs", ".", "read", "(", "creditFile", ")", ".", "then", "(", "function", "(", "contents", ")", "{", "return", "options", ".", "customize", ".", "engine", ".", "compile", "(", "contents", ")", "(", "input", ")", "}", ")", "}", ")", ")", "}", ")", "}" ]
Collect all credit-files concatenated them and as a list return them @returns {*}
[ "Collect", "all", "credit", "-", "files", "concatenated", "them", "and", "as", "a", "list", "return", "them" ]
a96e2b5964662aab8f9bf30d6494ff1c1bd0f072
https://github.com/bootprint/bootprint-openapi/blob/a96e2b5964662aab8f9bf30d6494ff1c1bd0f072/.thought/helpers.js#L13-L37
18,649
bootprint/bootprint-openapi
.thought/preprocessor.js
createPartialTree
function createPartialTree (currentFile, partials, visitedFiles) { if (visitedFiles[currentFile.name]) { return { label: '*' + currentFile.name + '*', name: currentFile.name } } visitedFiles[currentFile.name] = true var result = { label: currentFile.name, name: currentFile.name, summary: _.trunc(chainOrUndefined(currentFile, 'apidocs', 0, 'parsed', 'description'), { separator: ' ', length: 50 }) } if (currentFile.children.length > 0) { _.merge(result, { children: currentFile.children.map(function (child) { return createPartialTree(partials[child], partials, visitedFiles) }) }) } return result }
javascript
function createPartialTree (currentFile, partials, visitedFiles) { if (visitedFiles[currentFile.name]) { return { label: '*' + currentFile.name + '*', name: currentFile.name } } visitedFiles[currentFile.name] = true var result = { label: currentFile.name, name: currentFile.name, summary: _.trunc(chainOrUndefined(currentFile, 'apidocs', 0, 'parsed', 'description'), { separator: ' ', length: 50 }) } if (currentFile.children.length > 0) { _.merge(result, { children: currentFile.children.map(function (child) { return createPartialTree(partials[child], partials, visitedFiles) }) }) } return result }
[ "function", "createPartialTree", "(", "currentFile", ",", "partials", ",", "visitedFiles", ")", "{", "if", "(", "visitedFiles", "[", "currentFile", ".", "name", "]", ")", "{", "return", "{", "label", ":", "'*'", "+", "currentFile", ".", "name", "+", "'*'", ",", "name", ":", "currentFile", ".", "name", "}", "}", "visitedFiles", "[", "currentFile", ".", "name", "]", "=", "true", "var", "result", "=", "{", "label", ":", "currentFile", ".", "name", ",", "name", ":", "currentFile", ".", "name", ",", "summary", ":", "_", ".", "trunc", "(", "chainOrUndefined", "(", "currentFile", ",", "'apidocs'", ",", "0", ",", "'parsed'", ",", "'description'", ")", ",", "{", "separator", ":", "' '", ",", "length", ":", "50", "}", ")", "}", "if", "(", "currentFile", ".", "children", ".", "length", ">", "0", ")", "{", "_", ".", "merge", "(", "result", ",", "{", "children", ":", "currentFile", ".", "children", ".", "map", "(", "function", "(", "child", ")", "{", "return", "createPartialTree", "(", "partials", "[", "child", "]", ",", "partials", ",", "visitedFiles", ")", "}", ")", "}", ")", "}", "return", "result", "}" ]
Generate a call hierarchy of the template and its partials @param currentFile @param partials
[ "Generate", "a", "call", "hierarchy", "of", "the", "template", "and", "its", "partials" ]
a96e2b5964662aab8f9bf30d6494ff1c1bd0f072
https://github.com/bootprint/bootprint-openapi/blob/a96e2b5964662aab8f9bf30d6494ff1c1bd0f072/.thought/preprocessor.js#L72-L97
18,650
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }
javascript
function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }
[ "function", "(", "target", ")", "{", "var", "undef", ";", "each", "(", "arguments", ",", "function", "(", "arg", ",", "i", ")", "{", "if", "(", "i", ">", "0", ")", "{", "each", "(", "arg", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "!==", "undef", ")", "{", "if", "(", "typeOf", "(", "target", "[", "key", "]", ")", "===", "typeOf", "(", "value", ")", "&&", "!", "!", "~", "inArray", "(", "typeOf", "(", "value", ")", ",", "[", "'array'", ",", "'object'", "]", ")", ")", "{", "extend", "(", "target", "[", "key", "]", ",", "value", ")", ";", "}", "else", "{", "target", "[", "key", "]", "=", "value", ";", "}", "}", "}", ")", ";", "}", "}", ")", ";", "return", "target", ";", "}" ]
Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object.
[ "Extends", "the", "specified", "object", "with", "another", "object", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L142-L159
18,651
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }
javascript
function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }
[ "function", "(", "obj", ")", "{", "var", "prop", ";", "if", "(", "!", "obj", "||", "typeOf", "(", "obj", ")", "!==", "'object'", ")", "{", "return", "true", ";", "}", "for", "(", "prop", "in", "obj", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean}
[ "Checks", "if", "object", "is", "empty", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L208-L220
18,652
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }
javascript
function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }
[ "function", "(", "str", ")", "{", "if", "(", "!", "str", ")", "{", "return", "str", ";", "}", "return", "String", ".", "prototype", ".", "trim", "?", "String", ".", "prototype", ".", "trim", ".", "call", "(", "str", ")", ":", "str", ".", "toString", "(", ")", ".", "replace", "(", "/", "^\\s*", "/", ",", "''", ")", ".", "replace", "(", "/", "\\s*$", "/", ",", "''", ")", ";", "}" ]
Trims white spaces around the string @method trim @static @param {String} str @return {String}
[ "Trims", "white", "spaces", "around", "the", "string" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L421-L426
18,653
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }
javascript
function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }
[ "function", "(", "size", ")", "{", "if", "(", "typeof", "(", "size", ")", "!==", "'string'", ")", "{", "return", "size", ";", "}", "var", "muls", "=", "{", "t", ":", "1099511627776", ",", "g", ":", "1073741824", ",", "m", ":", "1048576", ",", "k", ":", "1024", "}", ",", "mul", ";", "size", "=", "/", "^([0-9]+)([mgk]?)$", "/", ".", "exec", "(", "size", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "[^0-9mkg]", "/", "g", ",", "''", ")", ")", ";", "mul", "=", "size", "[", "2", "]", ";", "size", "=", "+", "size", "[", "1", "]", ";", "if", "(", "muls", ".", "hasOwnProperty", "(", "mul", ")", ")", "{", "size", "*=", "muls", "[", "mul", "]", ";", "}", "return", "size", ";", "}" ]
Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes.
[ "Parses", "the", "specified", "size", "string", "into", "a", "byte", "value", ".", "For", "example", "10kb", "becomes", "10240", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L437-L458
18,654
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }
javascript
function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }
[ "function", "(", "type", ",", "fn", ",", "priority", ",", "scope", ")", "{", "var", "self", "=", "this", ",", "list", ";", "type", "=", "Basic", ".", "trim", "(", "type", ")", ";", "if", "(", "/", "\\s", "/", ".", "test", "(", "type", ")", ")", "{", "// multiple event types were passed for one handler", "Basic", ".", "each", "(", "type", ".", "split", "(", "/", "\\s+", "/", ")", ",", "function", "(", "type", ")", "{", "self", ".", "addEventListener", "(", "type", ",", "fn", ",", "priority", ",", "scope", ")", ";", "}", ")", ";", "return", ";", "}", "type", "=", "type", ".", "toLowerCase", "(", ")", ";", "priority", "=", "parseInt", "(", "priority", ",", "10", ")", "||", "0", ";", "list", "=", "eventpool", "[", "this", ".", "uid", "]", "&&", "eventpool", "[", "this", ".", "uid", "]", "[", "type", "]", "||", "[", "]", ";", "list", ".", "push", "(", "{", "fn", ":", "fn", ",", "priority", ":", "priority", ",", "scope", ":", "scope", "||", "this", "}", ")", ";", "if", "(", "!", "eventpool", "[", "this", ".", "uid", "]", ")", "{", "eventpool", "[", "this", ".", "uid", "]", "=", "{", "}", ";", "}", "eventpool", "[", "this", ".", "uid", "]", "[", "type", "]", "=", "list", ";", "}" ]
Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in
[ "Register", "a", "handler", "to", "a", "specific", "event", "dispatched", "by", "the", "object" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L1769-L1792
18,655
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }
javascript
function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }
[ "function", "(", "type", ",", "fn", ")", "{", "type", "=", "type", ".", "toLowerCase", "(", ")", ";", "var", "list", "=", "eventpool", "[", "this", ".", "uid", "]", "&&", "eventpool", "[", "this", ".", "uid", "]", "[", "type", "]", ",", "i", ";", "if", "(", "list", ")", "{", "if", "(", "fn", ")", "{", "for", "(", "i", "=", "list", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "list", "[", "i", "]", ".", "fn", "===", "fn", ")", "{", "list", ".", "splice", "(", "i", ",", "1", ")", ";", "break", ";", "}", "}", "}", "else", "{", "list", "=", "[", "]", ";", "}", "// delete event list if it has become empty", "if", "(", "!", "list", ".", "length", ")", "{", "delete", "eventpool", "[", "this", ".", "uid", "]", "[", "type", "]", ";", "// and object specific entry in a hash if it has no more listeners attached", "if", "(", "Basic", ".", "isEmptyObj", "(", "eventpool", "[", "this", ".", "uid", "]", ")", ")", "{", "delete", "eventpool", "[", "this", ".", "uid", "]", ";", "}", "}", "}", "}" ]
Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister
[ "Unregister", "the", "handler", "from", "the", "event", "or", "if", "former", "was", "not", "specified", "-", "unregister", "all", "handlers" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L1812-L1839
18,656
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }
javascript
function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }
[ "function", "(", "type", ")", "{", "var", "uid", ",", "list", ",", "args", ",", "tmpEvt", ",", "evt", "=", "{", "}", ",", "result", "=", "true", ",", "undef", ";", "if", "(", "Basic", ".", "typeOf", "(", "type", ")", "!==", "'string'", ")", "{", "// we can't use original object directly (because of Silverlight)", "tmpEvt", "=", "type", ";", "if", "(", "Basic", ".", "typeOf", "(", "tmpEvt", ".", "type", ")", "===", "'string'", ")", "{", "type", "=", "tmpEvt", ".", "type", ";", "if", "(", "tmpEvt", ".", "total", "!==", "undef", "&&", "tmpEvt", ".", "loaded", "!==", "undef", ")", "{", "// progress event", "evt", ".", "total", "=", "tmpEvt", ".", "total", ";", "evt", ".", "loaded", "=", "tmpEvt", ".", "loaded", ";", "}", "evt", ".", "async", "=", "tmpEvt", ".", "async", "||", "false", ";", "}", "else", "{", "throw", "new", "x", ".", "EventException", "(", "x", ".", "EventException", ".", "UNSPECIFIED_EVENT_TYPE_ERR", ")", ";", "}", "}", "// check if event is meant to be dispatched on an object having specific uid", "if", "(", "type", ".", "indexOf", "(", "'::'", ")", "!==", "-", "1", ")", "{", "(", "function", "(", "arr", ")", "{", "uid", "=", "arr", "[", "0", "]", ";", "type", "=", "arr", "[", "1", "]", ";", "}", "(", "type", ".", "split", "(", "'::'", ")", ")", ")", ";", "}", "else", "{", "uid", "=", "this", ".", "uid", ";", "}", "type", "=", "type", ".", "toLowerCase", "(", ")", ";", "list", "=", "eventpool", "[", "uid", "]", "&&", "eventpool", "[", "uid", "]", "[", "type", "]", ";", "if", "(", "list", ")", "{", "// sort event list by prority", "list", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", ".", "priority", "-", "a", ".", "priority", ";", "}", ")", ";", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "// first argument will be pseudo-event object", "args", ".", "shift", "(", ")", ";", "evt", ".", "type", "=", "type", ";", "args", ".", "unshift", "(", "evt", ")", ";", "// Dispatch event to all listeners", "var", "queue", "=", "[", "]", ";", "Basic", ".", "each", "(", "list", ",", "function", "(", "handler", ")", "{", "// explicitly set the target, otherwise events fired from shims do not get it", "args", "[", "0", "]", ".", "target", "=", "handler", ".", "scope", ";", "// if event is marked as async, detach the handler", "if", "(", "evt", ".", "async", ")", "{", "queue", ".", "push", "(", "function", "(", "cb", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "cb", "(", "handler", ".", "fn", ".", "apply", "(", "handler", ".", "scope", ",", "args", ")", "===", "false", ")", ";", "}", ",", "1", ")", ";", "}", ")", ";", "}", "else", "{", "queue", ".", "push", "(", "function", "(", "cb", ")", "{", "cb", "(", "handler", ".", "fn", ".", "apply", "(", "handler", ".", "scope", ",", "args", ")", "===", "false", ")", ";", "// if handler returns false stop propagation", "}", ")", ";", "}", "}", ")", ";", "if", "(", "queue", ".", "length", ")", "{", "Basic", ".", "inSeries", "(", "queue", ",", "function", "(", "err", ")", "{", "result", "=", "!", "err", ";", "}", ")", ";", "}", "}", "return", "result", ";", "}" ]
Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false
[ "Dispatch", "the", "event" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L1860-L1930
18,657
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }
javascript
function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }
[ "function", "(", ")", "{", "var", "container", ",", "shimContainer", "=", "Dom", ".", "get", "(", "this", ".", "shimid", ")", ";", "// if no container for shim, create one", "if", "(", "!", "shimContainer", ")", "{", "container", "=", "this", ".", "options", ".", "container", "?", "Dom", ".", "get", "(", "this", ".", "options", ".", "container", ")", ":", "document", ".", "body", ";", "// create shim container and insert it at an absolute position into the outer container", "shimContainer", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "shimContainer", ".", "id", "=", "this", ".", "shimid", ";", "shimContainer", ".", "className", "=", "'moxie-shim moxie-shim-'", "+", "this", ".", "type", ";", "Basic", ".", "extend", "(", "shimContainer", ".", "style", ",", "{", "position", ":", "'absolute'", ",", "top", ":", "'0px'", ",", "left", ":", "'0px'", ",", "width", ":", "'1px'", ",", "height", ":", "'1px'", ",", "overflow", ":", "'hidden'", "}", ")", ";", "container", ".", "appendChild", "(", "shimContainer", ")", ";", "container", "=", "null", ";", "}", "return", "shimContainer", ";", "}" ]
Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement}
[ "Returns", "container", "for", "the", "runtime", "as", "DOM", "element" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L2443-L2469
18,658
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy'); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }
javascript
function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy'); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }
[ "function", "(", "data", ")", "{", "if", "(", "this", ".", "ruid", ")", "{", "this", ".", "getRuntime", "(", ")", ".", "exec", ".", "call", "(", "this", ",", "'Blob'", ",", "'destroy'", ")", ";", "this", ".", "disconnectRuntime", "(", ")", ";", "this", ".", "ruid", "=", "null", ";", "}", "data", "=", "data", "||", "''", ";", "// if dataUrl, convert to binary string", "var", "matches", "=", "data", ".", "match", "(", "/", "^data:([^;]*);base64,", "/", ")", ";", "if", "(", "matches", ")", "{", "this", ".", "type", "=", "matches", "[", "1", "]", ";", "data", "=", "Encode", ".", "atob", "(", "data", ".", "substring", "(", "data", ".", "indexOf", "(", "'base64,'", ")", "+", "7", ")", ")", ";", "}", "this", ".", "size", "=", "data", ".", "length", ";", "blobpool", "[", "this", ".", "uid", "]", "=", "data", ";", "}" ]
Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value
[ "Detaches", "blob", "from", "any", "runtime", "that", "it", "depends", "on", "and", "initialize", "with", "standalone", "value" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3037-L3056
18,659
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }
javascript
function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }
[ "function", "(", ")", "{", "self", ".", "convertEventPropsToHandlers", "(", "dispatches", ")", ";", "self", ".", "bind", "(", "'RuntimeInit'", ",", "function", "(", "e", ",", "runtime", ")", "{", "self", ".", "ruid", "=", "runtime", ".", "uid", ";", "self", ".", "shimid", "=", "runtime", ".", "shimid", ";", "self", ".", "bind", "(", "\"Ready\"", ",", "function", "(", ")", "{", "self", ".", "trigger", "(", "\"Refresh\"", ")", ";", "}", ",", "999", ")", ";", "self", ".", "bind", "(", "\"Change\"", ",", "function", "(", ")", "{", "var", "files", "=", "runtime", ".", "exec", ".", "call", "(", "self", ",", "'FileInput'", ",", "'getFiles'", ")", ";", "self", ".", "files", "=", "[", "]", ";", "Basic", ".", "each", "(", "files", ",", "function", "(", "file", ")", "{", "// ignore empty files (IE10 for example hangs if you try to send them via XHR)", "if", "(", "file", ".", "size", "===", "0", ")", "{", "return", "true", ";", "}", "self", ".", "files", ".", "push", "(", "new", "File", "(", "self", ".", "ruid", ",", "file", ")", ")", ";", "}", ")", ";", "}", ",", "999", ")", ";", "// re-position and resize shim container", "self", ".", "bind", "(", "'Refresh'", ",", "function", "(", ")", "{", "var", "pos", ",", "size", ",", "browseButton", ",", "shimContainer", ";", "browseButton", "=", "Dom", ".", "get", "(", "options", ".", "browse_button", ")", ";", "shimContainer", "=", "Dom", ".", "get", "(", "runtime", ".", "shimid", ")", ";", "// do not use runtime.getShimContainer(), since it will create container if it doesn't exist", "if", "(", "browseButton", ")", "{", "pos", "=", "Dom", ".", "getPos", "(", "browseButton", ",", "Dom", ".", "get", "(", "options", ".", "container", ")", ")", ";", "size", "=", "Dom", ".", "getSize", "(", "browseButton", ")", ";", "if", "(", "shimContainer", ")", "{", "Basic", ".", "extend", "(", "shimContainer", ".", "style", ",", "{", "top", ":", "pos", ".", "y", "+", "'px'", ",", "left", ":", "pos", ".", "x", "+", "'px'", ",", "width", ":", "size", ".", "w", "+", "'px'", ",", "height", ":", "size", ".", "h", "+", "'px'", "}", ")", ";", "}", "}", "shimContainer", "=", "browseButton", "=", "null", ";", "}", ")", ";", "runtime", ".", "exec", ".", "call", "(", "self", ",", "'FileInput'", ",", "'init'", ",", "options", ")", ";", "}", ")", ";", "// runtime needs: options.required_features, options.runtime_order and options.container", "self", ".", "connectRuntime", "(", "Basic", ".", "extend", "(", "{", "}", ",", "options", ",", "{", "required_caps", ":", "{", "select_file", ":", "true", "}", "}", ")", ")", ";", "}" ]
Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init
[ "Initializes", "the", "file", "-", "picker", "connects", "it", "to", "runtime", "and", "dispatches", "event", "ready", "when", "done", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3414-L3471
18,660
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }
javascript
function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }
[ "function", "(", "state", ")", "{", "var", "runtime", "=", "this", ".", "getRuntime", "(", ")", ";", "if", "(", "runtime", ")", "{", "runtime", ".", "exec", ".", "call", "(", "this", ",", "'FileInput'", ",", "'disable'", ",", "Basic", ".", "typeOf", "(", "state", ")", "===", "'undefined'", "?", "true", ":", "state", ")", ";", "}", "}" ]
Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false
[ "Disables", "file", "-", "picker", "element", "so", "that", "it", "doesn", "t", "react", "to", "mouse", "clicks", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3479-L3484
18,661
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; }
javascript
function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; }
[ "function", "(", ")", "{", "var", "runtime", "=", "this", ".", "getRuntime", "(", ")", ";", "if", "(", "runtime", ")", "{", "runtime", ".", "exec", ".", "call", "(", "this", ",", "'FileInput'", ",", "'destroy'", ")", ";", "this", ".", "disconnectRuntime", "(", ")", ";", "}", "if", "(", "Basic", ".", "typeOf", "(", "this", ".", "files", ")", "===", "'array'", ")", "{", "// no sense in leaving associated files behind", "Basic", ".", "each", "(", "this", ".", "files", ",", "function", "(", "file", ")", "{", "file", ".", "destroy", "(", ")", ";", "}", ")", ";", "}", "this", ".", "files", "=", "null", ";", "}" ]
Destroy component. @method destroy
[ "Destroy", "component", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3502-L3516
18,662
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }
javascript
function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }
[ "function", "(", ")", "{", "this", ".", "result", "=", "null", ";", "if", "(", "Basic", ".", "inArray", "(", "this", ".", "readyState", ",", "[", "FileReader", ".", "EMPTY", ",", "FileReader", ".", "DONE", "]", ")", "!==", "-", "1", ")", "{", "return", ";", "}", "else", "if", "(", "this", ".", "readyState", "===", "FileReader", ".", "LOADING", ")", "{", "this", ".", "readyState", "=", "FileReader", ".", "DONE", ";", "}", "if", "(", "_fr", ")", "{", "_fr", ".", "getRuntime", "(", ")", ".", "exec", ".", "call", "(", "this", ",", "'FileReader'", ",", "'abort'", ")", ";", "}", "this", ".", "trigger", "(", "'abort'", ")", ";", "this", ".", "trigger", "(", "'loadend'", ")", ";", "}" ]
Aborts preloading process. @method abort
[ "Aborts", "preloading", "process", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3721-L3736
18,663
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; }
javascript
function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; }
[ "function", "(", ")", "{", "this", ".", "abort", "(", ")", ";", "if", "(", "_fr", ")", "{", "_fr", ".", "getRuntime", "(", ")", ".", "exec", ".", "call", "(", "this", ",", "'FileReader'", ",", "'destroy'", ")", ";", "_fr", ".", "disconnectRuntime", "(", ")", ";", "}", "self", "=", "_fr", "=", "null", ";", "}" ]
Destroy component and release resources. @method destroy
[ "Destroy", "component", "and", "release", "resources", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3743-L3752
18,664
aFarkas/webshim
src/shims/moxie/js/moxie-swf.js
function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }
javascript
function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }
[ "function", "(", "url", ")", "{", "var", "ports", "=", "{", "// we ignore default ports", "http", ":", "80", ",", "https", ":", "443", "}", ",", "urlp", "=", "parseUrl", "(", "url", ")", ";", "return", "urlp", ".", "scheme", "+", "'://'", "+", "urlp", ".", "host", "+", "(", "urlp", ".", "port", "!==", "ports", "[", "urlp", ".", "scheme", "]", "?", "':'", "+", "urlp", ".", "port", ":", "''", ")", "+", "urlp", ".", "path", "+", "(", "urlp", ".", "query", "?", "urlp", ".", "query", ":", "''", ")", ";", "}" ]
Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url
[ "Resolve", "url", "-", "among", "other", "things", "will", "turn", "relative", "url", "to", "absolute" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/moxie/js/moxie-swf.js#L3953-L3962
18,665
aFarkas/webshim
demos/demo-js/src/prism.js
function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } return root[inside] = ret; }
javascript
function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } return root[inside] = ret; }
[ "function", "(", "inside", ",", "before", ",", "insert", ",", "root", ")", "{", "root", "=", "root", "||", "_", ".", "languages", ";", "var", "grammar", "=", "root", "[", "inside", "]", ";", "var", "ret", "=", "{", "}", ";", "for", "(", "var", "token", "in", "grammar", ")", "{", "if", "(", "grammar", ".", "hasOwnProperty", "(", "token", ")", ")", "{", "if", "(", "token", "==", "before", ")", "{", "for", "(", "var", "newToken", "in", "insert", ")", "{", "if", "(", "insert", ".", "hasOwnProperty", "(", "newToken", ")", ")", "{", "ret", "[", "newToken", "]", "=", "insert", "[", "newToken", "]", ";", "}", "}", "}", "ret", "[", "token", "]", "=", "grammar", "[", "token", "]", ";", "}", "}", "return", "root", "[", "inside", "]", "=", "ret", ";", "}" ]
Insert a token before another token in a language literal
[ "Insert", "a", "token", "before", "another", "token", "in", "a", "language", "literal" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/demos/demo-js/src/prism.js#L54-L78
18,666
aFarkas/webshim
src/shims/picture.js
updateMetrics
function updateMetrics() { var dprM; isVwDirty = false; DPR = window.devicePixelRatio; cssCache = {}; sizeLengthCache = {}; dprM = (DPR || 1) * cfg.xQuant; if(!cfg.uT){ cfg.maxX = Math.max(1.3, cfg.maxX); dprM = Math.min( dprM, cfg.maxX ); ri.DPR = dprM; } units.width = Math.max(window.innerWidth || 0, docElem.clientWidth); units.height = Math.max(window.innerHeight || 0, docElem.clientHeight); units.vw = units.width / 100; units.vh = units.height / 100; units.em = ri.getEmValue(); units.rem = units.em; lazyFactor = cfg.lazyFactor / 2; lazyFactor = (lazyFactor * dprM) + lazyFactor; substractCurRes = 0.4 + (0.1 * dprM); lowTreshHold = 0.5 + (0.2 * dprM); partialLowTreshHold = 0.5 + (0.25 * dprM); tMemory = dprM + 1.3; if(!(isLandscape = units.width > units.height)){ lazyFactor *= 0.9; } if(supportAbort){ lazyFactor *= 0.9; } evalID = [units.width, units.height, dprM].join('-'); }
javascript
function updateMetrics() { var dprM; isVwDirty = false; DPR = window.devicePixelRatio; cssCache = {}; sizeLengthCache = {}; dprM = (DPR || 1) * cfg.xQuant; if(!cfg.uT){ cfg.maxX = Math.max(1.3, cfg.maxX); dprM = Math.min( dprM, cfg.maxX ); ri.DPR = dprM; } units.width = Math.max(window.innerWidth || 0, docElem.clientWidth); units.height = Math.max(window.innerHeight || 0, docElem.clientHeight); units.vw = units.width / 100; units.vh = units.height / 100; units.em = ri.getEmValue(); units.rem = units.em; lazyFactor = cfg.lazyFactor / 2; lazyFactor = (lazyFactor * dprM) + lazyFactor; substractCurRes = 0.4 + (0.1 * dprM); lowTreshHold = 0.5 + (0.2 * dprM); partialLowTreshHold = 0.5 + (0.25 * dprM); tMemory = dprM + 1.3; if(!(isLandscape = units.width > units.height)){ lazyFactor *= 0.9; } if(supportAbort){ lazyFactor *= 0.9; } evalID = [units.width, units.height, dprM].join('-'); }
[ "function", "updateMetrics", "(", ")", "{", "var", "dprM", ";", "isVwDirty", "=", "false", ";", "DPR", "=", "window", ".", "devicePixelRatio", ";", "cssCache", "=", "{", "}", ";", "sizeLengthCache", "=", "{", "}", ";", "dprM", "=", "(", "DPR", "||", "1", ")", "*", "cfg", ".", "xQuant", ";", "if", "(", "!", "cfg", ".", "uT", ")", "{", "cfg", ".", "maxX", "=", "Math", ".", "max", "(", "1.3", ",", "cfg", ".", "maxX", ")", ";", "dprM", "=", "Math", ".", "min", "(", "dprM", ",", "cfg", ".", "maxX", ")", ";", "ri", ".", "DPR", "=", "dprM", ";", "}", "units", ".", "width", "=", "Math", ".", "max", "(", "window", ".", "innerWidth", "||", "0", ",", "docElem", ".", "clientWidth", ")", ";", "units", ".", "height", "=", "Math", ".", "max", "(", "window", ".", "innerHeight", "||", "0", ",", "docElem", ".", "clientHeight", ")", ";", "units", ".", "vw", "=", "units", ".", "width", "/", "100", ";", "units", ".", "vh", "=", "units", ".", "height", "/", "100", ";", "units", ".", "em", "=", "ri", ".", "getEmValue", "(", ")", ";", "units", ".", "rem", "=", "units", ".", "em", ";", "lazyFactor", "=", "cfg", ".", "lazyFactor", "/", "2", ";", "lazyFactor", "=", "(", "lazyFactor", "*", "dprM", ")", "+", "lazyFactor", ";", "substractCurRes", "=", "0.4", "+", "(", "0.1", "*", "dprM", ")", ";", "lowTreshHold", "=", "0.5", "+", "(", "0.2", "*", "dprM", ")", ";", "partialLowTreshHold", "=", "0.5", "+", "(", "0.25", "*", "dprM", ")", ";", "tMemory", "=", "dprM", "+", "1.3", ";", "if", "(", "!", "(", "isLandscape", "=", "units", ".", "width", ">", "units", ".", "height", ")", ")", "{", "lazyFactor", "*=", "0.9", ";", "}", "if", "(", "supportAbort", ")", "{", "lazyFactor", "*=", "0.9", ";", "}", "evalID", "=", "[", "units", ".", "width", ",", "units", ".", "height", ",", "dprM", "]", ".", "join", "(", "'-'", ")", ";", "}" ]
updates the internal vW property with the current viewport width in px
[ "updates", "the", "internal", "vW", "property", "with", "the", "current", "viewport", "width", "in", "px" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/src/shims/picture.js#L273-L319
18,667
aFarkas/webshim
demos/demos/mediaelement/assets/jquery.colorbox.js
getIndex
function getIndex(increment) { var max = $related.length, newIndex = (index + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; }
javascript
function getIndex(increment) { var max = $related.length, newIndex = (index + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; }
[ "function", "getIndex", "(", "increment", ")", "{", "var", "max", "=", "$related", ".", "length", ",", "newIndex", "=", "(", "index", "+", "increment", ")", "%", "max", ";", "return", "(", "newIndex", "<", "0", ")", "?", "max", "+", "newIndex", ":", "newIndex", ";", "}" ]
Determine the next and previous members in a group.
[ "Determine", "the", "next", "and", "previous", "members", "in", "a", "group", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/demos/demos/mediaelement/assets/jquery.colorbox.js#L137-L143
18,668
aFarkas/webshim
demos/demos/mediaelement/assets/jquery.colorbox.js
appendHTML
function appendHTML() { if (!$box && document.body) { init = false; $window = $(window); $box = $tag(div).attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}).hide(); $overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $tag(div, "Wrapper"); $content = $tag(div, "Content").append( $loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")), $title = $tag(div, "Title"), $current = $tag(div, "Current"), $next = $tag(div, "Next"), $prev = $tag(div, "Previous"), $slideshow = $tag(div, "Slideshow").bind(event_open, slideshow), $close = $tag(div, "Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $tag(div).append( $tag(div, "TopLeft"), $topBorder = $tag(div, "TopCenter"), $tag(div, "TopRight") ), $tag(div, false, 'clear:left').append( $leftBorder = $tag(div, "MiddleLeft"), $content, $rightBorder = $tag(div, "MiddleRight") ), $tag(div, false, 'clear:left').append( $tag(div, "BottomLeft"), $bottomBorder = $tag(div, "BottomCenter"), $tag(div, "BottomRight") ) ).find('div div').css({'float': 'left'}); $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $groupControls = $next.add($prev).add($current).add($slideshow); $(document.body).append($overlay, $box.append($wrap, $loadingBay)); } }
javascript
function appendHTML() { if (!$box && document.body) { init = false; $window = $(window); $box = $tag(div).attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}).hide(); $overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $tag(div, "Wrapper"); $content = $tag(div, "Content").append( $loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")), $title = $tag(div, "Title"), $current = $tag(div, "Current"), $next = $tag(div, "Next"), $prev = $tag(div, "Previous"), $slideshow = $tag(div, "Slideshow").bind(event_open, slideshow), $close = $tag(div, "Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $tag(div).append( $tag(div, "TopLeft"), $topBorder = $tag(div, "TopCenter"), $tag(div, "TopRight") ), $tag(div, false, 'clear:left').append( $leftBorder = $tag(div, "MiddleLeft"), $content, $rightBorder = $tag(div, "MiddleRight") ), $tag(div, false, 'clear:left').append( $tag(div, "BottomLeft"), $bottomBorder = $tag(div, "BottomCenter"), $tag(div, "BottomRight") ) ).find('div div').css({'float': 'left'}); $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $groupControls = $next.add($prev).add($current).add($slideshow); $(document.body).append($overlay, $box.append($wrap, $loadingBay)); } }
[ "function", "appendHTML", "(", ")", "{", "if", "(", "!", "$box", "&&", "document", ".", "body", ")", "{", "init", "=", "false", ";", "$window", "=", "$", "(", "window", ")", ";", "$box", "=", "$tag", "(", "div", ")", ".", "attr", "(", "{", "id", ":", "colorbox", ",", "'class'", ":", "isIE", "?", "prefix", "+", "(", "isIE6", "?", "'IE6'", ":", "'IE'", ")", ":", "''", "}", ")", ".", "hide", "(", ")", ";", "$overlay", "=", "$tag", "(", "div", ",", "\"Overlay\"", ",", "isIE6", "?", "'position:absolute'", ":", "''", ")", ".", "hide", "(", ")", ";", "$wrap", "=", "$tag", "(", "div", ",", "\"Wrapper\"", ")", ";", "$content", "=", "$tag", "(", "div", ",", "\"Content\"", ")", ".", "append", "(", "$loaded", "=", "$tag", "(", "div", ",", "\"LoadedContent\"", ",", "'width:0; height:0; overflow:hidden'", ")", ",", "$loadingOverlay", "=", "$tag", "(", "div", ",", "\"LoadingOverlay\"", ")", ".", "add", "(", "$tag", "(", "div", ",", "\"LoadingGraphic\"", ")", ")", ",", "$title", "=", "$tag", "(", "div", ",", "\"Title\"", ")", ",", "$current", "=", "$tag", "(", "div", ",", "\"Current\"", ")", ",", "$next", "=", "$tag", "(", "div", ",", "\"Next\"", ")", ",", "$prev", "=", "$tag", "(", "div", ",", "\"Previous\"", ")", ",", "$slideshow", "=", "$tag", "(", "div", ",", "\"Slideshow\"", ")", ".", "bind", "(", "event_open", ",", "slideshow", ")", ",", "$close", "=", "$tag", "(", "div", ",", "\"Close\"", ")", ")", ";", "$wrap", ".", "append", "(", "// The 3x3 Grid that makes up ColorBox", "$tag", "(", "div", ")", ".", "append", "(", "$tag", "(", "div", ",", "\"TopLeft\"", ")", ",", "$topBorder", "=", "$tag", "(", "div", ",", "\"TopCenter\"", ")", ",", "$tag", "(", "div", ",", "\"TopRight\"", ")", ")", ",", "$tag", "(", "div", ",", "false", ",", "'clear:left'", ")", ".", "append", "(", "$leftBorder", "=", "$tag", "(", "div", ",", "\"MiddleLeft\"", ")", ",", "$content", ",", "$rightBorder", "=", "$tag", "(", "div", ",", "\"MiddleRight\"", ")", ")", ",", "$tag", "(", "div", ",", "false", ",", "'clear:left'", ")", ".", "append", "(", "$tag", "(", "div", ",", "\"BottomLeft\"", ")", ",", "$bottomBorder", "=", "$tag", "(", "div", ",", "\"BottomCenter\"", ")", ",", "$tag", "(", "div", ",", "\"BottomRight\"", ")", ")", ")", ".", "find", "(", "'div div'", ")", ".", "css", "(", "{", "'float'", ":", "'left'", "}", ")", ";", "$loadingBay", "=", "$tag", "(", "div", ",", "false", ",", "'position:absolute; width:9999px; visibility:hidden; display:none'", ")", ";", "$groupControls", "=", "$next", ".", "add", "(", "$prev", ")", ".", "add", "(", "$current", ")", ".", "add", "(", "$slideshow", ")", ";", "$", "(", "document", ".", "body", ")", ".", "append", "(", "$overlay", ",", "$box", ".", "append", "(", "$wrap", ",", "$loadingBay", ")", ")", ";", "}", "}" ]
ColorBox's markup needs to be added to the DOM prior to being called so that the browser will go ahead and load the CSS background images.
[ "ColorBox", "s", "markup", "needs", "to", "be", "added", "to", "the", "DOM", "prior", "to", "being", "called", "so", "that", "the", "browser", "will", "go", "ahead", "and", "load", "the", "CSS", "background", "images", "." ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/demos/demos/mediaelement/assets/jquery.colorbox.js#L296-L339
18,669
aFarkas/webshim
demos/demos/mediaelement/assets/jquery.colorbox.js
addBindings
function addBindings() { if ($box) { if (!init) { init = true; // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6 interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Setting padding to remove the need to do size conversions during the animation step. $box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}); // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1]) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); $('.' + boxElement, document).live('click', function (e) { // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt. // See: http://jacklmoore.com/notes/click-events/ if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) { e.preventDefault(); launch(this); } }); } return true; } return false; }
javascript
function addBindings() { if ($box) { if (!init) { init = true; // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6 interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Setting padding to remove the need to do size conversions during the animation step. $box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}); // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1]) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); $('.' + boxElement, document).live('click', function (e) { // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt. // See: http://jacklmoore.com/notes/click-events/ if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) { e.preventDefault(); launch(this); } }); } return true; } return false; }
[ "function", "addBindings", "(", ")", "{", "if", "(", "$box", ")", "{", "if", "(", "!", "init", ")", "{", "init", "=", "true", ";", "// Cache values needed for size calculations", "interfaceHeight", "=", "$topBorder", ".", "height", "(", ")", "+", "$bottomBorder", ".", "height", "(", ")", "+", "$content", ".", "outerHeight", "(", "true", ")", "-", "$content", ".", "height", "(", ")", ";", "//Subtraction needed for IE6", "interfaceWidth", "=", "$leftBorder", ".", "width", "(", ")", "+", "$rightBorder", ".", "width", "(", ")", "+", "$content", ".", "outerWidth", "(", "true", ")", "-", "$content", ".", "width", "(", ")", ";", "loadedHeight", "=", "$loaded", ".", "outerHeight", "(", "true", ")", ";", "loadedWidth", "=", "$loaded", ".", "outerWidth", "(", "true", ")", ";", "// Setting padding to remove the need to do size conversions during the animation step.", "$box", ".", "css", "(", "{", "\"padding-bottom\"", ":", "interfaceHeight", ",", "\"padding-right\"", ":", "interfaceWidth", "}", ")", ";", "// Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.", "$next", ".", "click", "(", "function", "(", ")", "{", "publicMethod", ".", "next", "(", ")", ";", "}", ")", ";", "$prev", ".", "click", "(", "function", "(", ")", "{", "publicMethod", ".", "prev", "(", ")", ";", "}", ")", ";", "$close", ".", "click", "(", "function", "(", ")", "{", "publicMethod", ".", "close", "(", ")", ";", "}", ")", ";", "$overlay", ".", "click", "(", "function", "(", ")", "{", "if", "(", "settings", ".", "overlayClose", ")", "{", "publicMethod", ".", "close", "(", ")", ";", "}", "}", ")", ";", "// Key Bindings", "$", "(", "document", ")", ".", "bind", "(", "'keydown.'", "+", "prefix", ",", "function", "(", "e", ")", "{", "var", "key", "=", "e", ".", "keyCode", ";", "if", "(", "open", "&&", "settings", ".", "escKey", "&&", "key", "===", "27", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "publicMethod", ".", "close", "(", ")", ";", "}", "if", "(", "open", "&&", "settings", ".", "arrowKey", "&&", "$related", "[", "1", "]", ")", "{", "if", "(", "key", "===", "37", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "$prev", ".", "click", "(", ")", ";", "}", "else", "if", "(", "key", "===", "39", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "$next", ".", "click", "(", ")", ";", "}", "}", "}", ")", ";", "$", "(", "'.'", "+", "boxElement", ",", "document", ")", ".", "live", "(", "'click'", ",", "function", "(", "e", ")", "{", "// ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt.", "// See: http://jacklmoore.com/notes/click-events/", "if", "(", "!", "(", "e", ".", "which", ">", "1", "||", "e", ".", "shiftKey", "||", "e", ".", "altKey", "||", "e", ".", "metaKey", ")", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "launch", "(", "this", ")", ";", "}", "}", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Add ColorBox's event bindings
[ "Add", "ColorBox", "s", "event", "bindings" ]
1600cc692854ac06bf128681bb0f7dd3ccf6b35d
https://github.com/aFarkas/webshim/blob/1600cc692854ac06bf128681bb0f7dd3ccf6b35d/demos/demos/mediaelement/assets/jquery.colorbox.js#L342-L402
18,670
barc/express-hbs
lib/hbs.js
function(layouts) { var currentLayout; layouts = layouts.slice(0); currentLayout = self.compile(str, layoutFile); layouts.push(currentLayout); if (useCache) { self.cache[layoutFile] = layouts.slice(0); } cb(null, layouts); }
javascript
function(layouts) { var currentLayout; layouts = layouts.slice(0); currentLayout = self.compile(str, layoutFile); layouts.push(currentLayout); if (useCache) { self.cache[layoutFile] = layouts.slice(0); } cb(null, layouts); }
[ "function", "(", "layouts", ")", "{", "var", "currentLayout", ";", "layouts", "=", "layouts", ".", "slice", "(", "0", ")", ";", "currentLayout", "=", "self", ".", "compile", "(", "str", ",", "layoutFile", ")", ";", "layouts", ".", "push", "(", "currentLayout", ")", ";", "if", "(", "useCache", ")", "{", "self", ".", "cache", "[", "layoutFile", "]", "=", "layouts", ".", "slice", "(", "0", ")", ";", "}", "cb", "(", "null", ",", "layouts", ")", ";", "}" ]
This function returns the current layout stack to the caller
[ "This", "function", "returns", "the", "current", "layout", "stack", "to", "the", "caller" ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L116-L125
18,671
barc/express-hbs
lib/hbs.js
parseLayout
function parseLayout(str, filename, cb) { var layoutFile = self.declaredLayoutFile(str, filename); if (layoutFile) { self.cacheLayout(layoutFile, options.cache, cb); } else { cb(null, null); } }
javascript
function parseLayout(str, filename, cb) { var layoutFile = self.declaredLayoutFile(str, filename); if (layoutFile) { self.cacheLayout(layoutFile, options.cache, cb); } else { cb(null, null); } }
[ "function", "parseLayout", "(", "str", ",", "filename", ",", "cb", ")", "{", "var", "layoutFile", "=", "self", ".", "declaredLayoutFile", "(", "str", ",", "filename", ")", ";", "if", "(", "layoutFile", ")", "{", "self", ".", "cacheLayout", "(", "layoutFile", ",", "options", ".", "cache", ",", "cb", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "null", ")", ";", "}", "}" ]
Allow a layout to be declared as a handlebars comment to remain spec compatible with handlebars. Valid directives {{!< foo}} # foo.hbs in same directory as template {{!< ../layouts/default}} # default.hbs in parent layout directory {{!< ../layouts/default.html}} # default.html in parent layout directory
[ "Allow", "a", "layout", "to", "be", "declared", "as", "a", "handlebars", "comment", "to", "remain", "spec", "compatible", "with", "handlebars", "." ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L466-L473
18,672
barc/express-hbs
lib/hbs.js
renderTemplate
function renderTemplate(template, locals, cb) { var res; try { var localTemplateOptions = self.getLocalTemplateOptions(locals); var localsClone = _.extend({}, locals); self.updateLocalTemplateOptions(localsClone, undefined); res = template(localsClone, _.merge({}, self._options.templateOptions, localTemplateOptions)); } catch (err) { if (err.message) { err.message = '[' + template.__filename + '] ' + err.message; } else if (typeof err === 'string') { return cb('[' + template.__filename + '] ' + err, null); } return cb(err, null); } cb(null, res); }
javascript
function renderTemplate(template, locals, cb) { var res; try { var localTemplateOptions = self.getLocalTemplateOptions(locals); var localsClone = _.extend({}, locals); self.updateLocalTemplateOptions(localsClone, undefined); res = template(localsClone, _.merge({}, self._options.templateOptions, localTemplateOptions)); } catch (err) { if (err.message) { err.message = '[' + template.__filename + '] ' + err.message; } else if (typeof err === 'string') { return cb('[' + template.__filename + '] ' + err, null); } return cb(err, null); } cb(null, res); }
[ "function", "renderTemplate", "(", "template", ",", "locals", ",", "cb", ")", "{", "var", "res", ";", "try", "{", "var", "localTemplateOptions", "=", "self", ".", "getLocalTemplateOptions", "(", "locals", ")", ";", "var", "localsClone", "=", "_", ".", "extend", "(", "{", "}", ",", "locals", ")", ";", "self", ".", "updateLocalTemplateOptions", "(", "localsClone", ",", "undefined", ")", ";", "res", "=", "template", "(", "localsClone", ",", "_", ".", "merge", "(", "{", "}", ",", "self", ".", "_options", ".", "templateOptions", ",", "localTemplateOptions", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "message", ")", "{", "err", ".", "message", "=", "'['", "+", "template", ".", "__filename", "+", "'] '", "+", "err", ".", "message", ";", "}", "else", "if", "(", "typeof", "err", "===", "'string'", ")", "{", "return", "cb", "(", "'['", "+", "template", ".", "__filename", "+", "'] '", "+", "err", ",", "null", ")", ";", "}", "return", "cb", "(", "err", ",", "null", ")", ";", "}", "cb", "(", "null", ",", "res", ")", ";", "}" ]
Renders `template` with given `locals` and calls `cb` with the resulting HTML string. @param template @param locals @param cb
[ "Renders", "template", "with", "given", "locals", "and", "calls", "cb", "with", "the", "resulting", "HTML", "string", "." ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L483-L500
18,673
barc/express-hbs
lib/hbs.js
render
function render(template, locals, layoutTemplates, cb) { if (!layoutTemplates) layoutTemplates = []; // We'll render templates from bottom to top of the stack, each template // being passed the rendered string of the previous ones as `body` var i = layoutTemplates.length - 1; var _stackRenderer = function(err, htmlStr) { if (err) return cb(err); if (i >= 0) { locals.body = htmlStr; renderTemplate(layoutTemplates[i--], locals, _stackRenderer); } else { cb(null, htmlStr); } }; // Start the rendering with the innermost page template renderTemplate(template, locals, _stackRenderer); }
javascript
function render(template, locals, layoutTemplates, cb) { if (!layoutTemplates) layoutTemplates = []; // We'll render templates from bottom to top of the stack, each template // being passed the rendered string of the previous ones as `body` var i = layoutTemplates.length - 1; var _stackRenderer = function(err, htmlStr) { if (err) return cb(err); if (i >= 0) { locals.body = htmlStr; renderTemplate(layoutTemplates[i--], locals, _stackRenderer); } else { cb(null, htmlStr); } }; // Start the rendering with the innermost page template renderTemplate(template, locals, _stackRenderer); }
[ "function", "render", "(", "template", ",", "locals", ",", "layoutTemplates", ",", "cb", ")", "{", "if", "(", "!", "layoutTemplates", ")", "layoutTemplates", "=", "[", "]", ";", "// We'll render templates from bottom to top of the stack, each template", "// being passed the rendered string of the previous ones as `body`", "var", "i", "=", "layoutTemplates", ".", "length", "-", "1", ";", "var", "_stackRenderer", "=", "function", "(", "err", ",", "htmlStr", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "locals", ".", "body", "=", "htmlStr", ";", "renderTemplate", "(", "layoutTemplates", "[", "i", "--", "]", ",", "locals", ",", "_stackRenderer", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "htmlStr", ")", ";", "}", "}", ";", "// Start the rendering with the innermost page template", "renderTemplate", "(", "template", ",", "locals", ",", "_stackRenderer", ")", ";", "}" ]
Renders `template` with an optional set of nested `layoutTemplates` using data in `locals`.
[ "Renders", "template", "with", "an", "optional", "set", "of", "nested", "layoutTemplates", "using", "data", "in", "locals", "." ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L507-L527
18,674
barc/express-hbs
lib/hbs.js
loadBeautify
function loadBeautify() { if (!self.beautify) { self.beautify = require('js-beautify').html; var rc = path.join(process.cwd(), '.jsbeautifyrc'); if (fs.existsSync(rc)) { self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8')); } } }
javascript
function loadBeautify() { if (!self.beautify) { self.beautify = require('js-beautify').html; var rc = path.join(process.cwd(), '.jsbeautifyrc'); if (fs.existsSync(rc)) { self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8')); } } }
[ "function", "loadBeautify", "(", ")", "{", "if", "(", "!", "self", ".", "beautify", ")", "{", "self", ".", "beautify", "=", "require", "(", "'js-beautify'", ")", ".", "html", ";", "var", "rc", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'.jsbeautifyrc'", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "rc", ")", ")", "{", "self", ".", "beautifyrc", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "rc", ",", "'utf8'", ")", ")", ";", "}", "}", "}" ]
Lazy loads js-beautify, which should not be used in production env.
[ "Lazy", "loads", "js", "-", "beautify", "which", "should", "not", "be", "used", "in", "production", "env", "." ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L533-L541
18,675
barc/express-hbs
lib/hbs.js
getSourceTemplate
function getSourceTemplate(cb) { if (options.cache) { var info = self.cache[filename]; if (info) { return cb(null, info.source, info.template); } } fs.readFile(filename, 'utf8', function(err, source) { if (err) return cb(err); var template = self.compile(source, filename); if (options.cache) { self.cache[filename] = { source: source, template: template }; } return cb(null, source, template); }); }
javascript
function getSourceTemplate(cb) { if (options.cache) { var info = self.cache[filename]; if (info) { return cb(null, info.source, info.template); } } fs.readFile(filename, 'utf8', function(err, source) { if (err) return cb(err); var template = self.compile(source, filename); if (options.cache) { self.cache[filename] = { source: source, template: template }; } return cb(null, source, template); }); }
[ "function", "getSourceTemplate", "(", "cb", ")", "{", "if", "(", "options", ".", "cache", ")", "{", "var", "info", "=", "self", ".", "cache", "[", "filename", "]", ";", "if", "(", "info", ")", "{", "return", "cb", "(", "null", ",", "info", ".", "source", ",", "info", ".", "template", ")", ";", "}", "}", "fs", ".", "readFile", "(", "filename", ",", "'utf8'", ",", "function", "(", "err", ",", "source", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "template", "=", "self", ".", "compile", "(", "source", ",", "filename", ")", ";", "if", "(", "options", ".", "cache", ")", "{", "self", ".", "cache", "[", "filename", "]", "=", "{", "source", ":", "source", ",", "template", ":", "template", "}", ";", "}", "return", "cb", "(", "null", ",", "source", ",", "template", ")", ";", "}", ")", ";", "}" ]
Gets the source and compiled template for filename either from the cache or compiling it on the fly.
[ "Gets", "the", "source", "and", "compiled", "template", "for", "filename", "either", "from", "the", "cache", "or", "compiling", "it", "on", "the", "fly", "." ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L547-L567
18,676
barc/express-hbs
lib/hbs.js
compileFile
function compileFile(locals, cb) { getSourceTemplate(function(err, source, template) { if (err) return cb(err); // Try to get the layout parseLayout(source, filename, function(err, layoutTemplates) { if (err) return cb(err); function renderIt(layoutTemplates) { if (self._options.beautify) { return render(template, locals, layoutTemplates, function(err, html) { if (err) return cb(err); loadBeautify(); return cb(null, self.beautify(html, self.beautifyrc)); }); } return render(template, locals, layoutTemplates, cb); } // Determine which layout to use if (typeof options.layout !== 'undefined' && !options.layout) { // If options.layout is falsy, behave as if no layout should be used - suppress defaults renderIt(null); } else if (layoutTemplates) { // 1. Layout specified in template renderIt(layoutTemplates); } else if (typeof options.layout !== 'undefined' && options.layout) { // 2. Layout specified by options from render var layoutFile = self.layoutPath(filename, options.layout); self.cacheLayout(layoutFile, options.cache, function(err, layoutTemplates) { if (err) return cb(err); renderIt(layoutTemplates); }); } else if (self.defaultLayoutTemplates) { // 3. Default layout specified when middleware was configured. renderIt(self.defaultLayoutTemplates); } else { // render without a template renderIt(null); } }); }); }
javascript
function compileFile(locals, cb) { getSourceTemplate(function(err, source, template) { if (err) return cb(err); // Try to get the layout parseLayout(source, filename, function(err, layoutTemplates) { if (err) return cb(err); function renderIt(layoutTemplates) { if (self._options.beautify) { return render(template, locals, layoutTemplates, function(err, html) { if (err) return cb(err); loadBeautify(); return cb(null, self.beautify(html, self.beautifyrc)); }); } return render(template, locals, layoutTemplates, cb); } // Determine which layout to use if (typeof options.layout !== 'undefined' && !options.layout) { // If options.layout is falsy, behave as if no layout should be used - suppress defaults renderIt(null); } else if (layoutTemplates) { // 1. Layout specified in template renderIt(layoutTemplates); } else if (typeof options.layout !== 'undefined' && options.layout) { // 2. Layout specified by options from render var layoutFile = self.layoutPath(filename, options.layout); self.cacheLayout(layoutFile, options.cache, function(err, layoutTemplates) { if (err) return cb(err); renderIt(layoutTemplates); }); } else if (self.defaultLayoutTemplates) { // 3. Default layout specified when middleware was configured. renderIt(self.defaultLayoutTemplates); } else { // render without a template renderIt(null); } }); }); }
[ "function", "compileFile", "(", "locals", ",", "cb", ")", "{", "getSourceTemplate", "(", "function", "(", "err", ",", "source", ",", "template", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "// Try to get the layout", "parseLayout", "(", "source", ",", "filename", ",", "function", "(", "err", ",", "layoutTemplates", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "function", "renderIt", "(", "layoutTemplates", ")", "{", "if", "(", "self", ".", "_options", ".", "beautify", ")", "{", "return", "render", "(", "template", ",", "locals", ",", "layoutTemplates", ",", "function", "(", "err", ",", "html", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "loadBeautify", "(", ")", ";", "return", "cb", "(", "null", ",", "self", ".", "beautify", "(", "html", ",", "self", ".", "beautifyrc", ")", ")", ";", "}", ")", ";", "}", "return", "render", "(", "template", ",", "locals", ",", "layoutTemplates", ",", "cb", ")", ";", "}", "// Determine which layout to use", "if", "(", "typeof", "options", ".", "layout", "!==", "'undefined'", "&&", "!", "options", ".", "layout", ")", "{", "// If options.layout is falsy, behave as if no layout should be used - suppress defaults", "renderIt", "(", "null", ")", ";", "}", "else", "if", "(", "layoutTemplates", ")", "{", "// 1. Layout specified in template", "renderIt", "(", "layoutTemplates", ")", ";", "}", "else", "if", "(", "typeof", "options", ".", "layout", "!==", "'undefined'", "&&", "options", ".", "layout", ")", "{", "// 2. Layout specified by options from render", "var", "layoutFile", "=", "self", ".", "layoutPath", "(", "filename", ",", "options", ".", "layout", ")", ";", "self", ".", "cacheLayout", "(", "layoutFile", ",", "options", ".", "cache", ",", "function", "(", "err", ",", "layoutTemplates", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "renderIt", "(", "layoutTemplates", ")", ";", "}", ")", ";", "}", "else", "if", "(", "self", ".", "defaultLayoutTemplates", ")", "{", "// 3. Default layout specified when middleware was configured.", "renderIt", "(", "self", ".", "defaultLayoutTemplates", ")", ";", "}", "else", "{", "// render without a template", "renderIt", "(", "null", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Compiles a file into a template and a layoutTemplate, then renders it above.
[ "Compiles", "a", "file", "into", "a", "template", "and", "a", "layoutTemplate", "then", "renders", "it", "above", "." ]
2e110bc428deba608fdbd815641ccdcf2e48e164
https://github.com/barc/express-hbs/blob/2e110bc428deba608fdbd815641ccdcf2e48e164/lib/hbs.js#L572-L615
18,677
paixaop/node-sodium
lib/toBuffer.js
toBuffer
function toBuffer(value, encoding) { if( typeof value === 'string') { encoding = encoding || 'hex'; if( !re.test(encoding) ) { throw new Error('[toBuffer] bad encoding. Must be: utf8|ascii|binary|hex|utf16le|ucs2|base64'); } try { return Buffer.from(value, encoding); } catch (e) { throw new Error('[toBuffer] string value could not be converted to a buffer :' + e.message); } } else if( typeof value === 'object' ) { if( Buffer.isBuffer(value) ) { return value; } else if( value instanceof Array ) { try { return Buffer.from(value); } catch (e) { throw new Error('[toBuffer] Array could not be converted to a buffer :' + e.message); } } } throw new Error('[toBuffer] unsupported type in value. Use Buffer, string or Array'); }
javascript
function toBuffer(value, encoding) { if( typeof value === 'string') { encoding = encoding || 'hex'; if( !re.test(encoding) ) { throw new Error('[toBuffer] bad encoding. Must be: utf8|ascii|binary|hex|utf16le|ucs2|base64'); } try { return Buffer.from(value, encoding); } catch (e) { throw new Error('[toBuffer] string value could not be converted to a buffer :' + e.message); } } else if( typeof value === 'object' ) { if( Buffer.isBuffer(value) ) { return value; } else if( value instanceof Array ) { try { return Buffer.from(value); } catch (e) { throw new Error('[toBuffer] Array could not be converted to a buffer :' + e.message); } } } throw new Error('[toBuffer] unsupported type in value. Use Buffer, string or Array'); }
[ "function", "toBuffer", "(", "value", ",", "encoding", ")", "{", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "encoding", "=", "encoding", "||", "'hex'", ";", "if", "(", "!", "re", ".", "test", "(", "encoding", ")", ")", "{", "throw", "new", "Error", "(", "'[toBuffer] bad encoding. Must be: utf8|ascii|binary|hex|utf16le|ucs2|base64'", ")", ";", "}", "try", "{", "return", "Buffer", ".", "from", "(", "value", ",", "encoding", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'[toBuffer] string value could not be converted to a buffer :'", "+", "e", ".", "message", ")", ";", "}", "}", "else", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "if", "(", "Buffer", ".", "isBuffer", "(", "value", ")", ")", "{", "return", "value", ";", "}", "else", "if", "(", "value", "instanceof", "Array", ")", "{", "try", "{", "return", "Buffer", ".", "from", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'[toBuffer] Array could not be converted to a buffer :'", "+", "e", ".", "message", ")", ";", "}", "}", "}", "throw", "new", "Error", "(", "'[toBuffer] unsupported type in value. Use Buffer, string or Array'", ")", ";", "}" ]
Convert value into a buffer @param {String|Buffer|Array} value a buffer, and array of bytes or a string that you want to convert to a buffer @param {String} [encoding] encoding to use in conversion if value is a string. Defaults to 'hex' @returns {*}
[ "Convert", "value", "into", "a", "buffer" ]
6d7a02f2a52e6707c5db8c96bec6c853b1d9afcf
https://github.com/paixaop/node-sodium/blob/6d7a02f2a52e6707c5db8c96bec6c853b1d9afcf/lib/toBuffer.js#L21-L53
18,678
revivek/oy
lib/utils/CSS.js
raiseOnUnsafeCSS
function raiseOnUnsafeCSS() { var css = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var foundInName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '\'not provided\''; css = new _cleanCss2.default({ shorthandCompacting: false }).minify(css).styles; if (css.match(/-moz-binding/i)) { throw new Error('Unsafe CSS found in ' + foundInName + ': "-moz-binding"'); } else if (css.match(/expression/i)) { throw new Error('Unsafe CSS found in ' + foundInName + ': "expression"'); } return css; }
javascript
function raiseOnUnsafeCSS() { var css = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var foundInName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '\'not provided\''; css = new _cleanCss2.default({ shorthandCompacting: false }).minify(css).styles; if (css.match(/-moz-binding/i)) { throw new Error('Unsafe CSS found in ' + foundInName + ': "-moz-binding"'); } else if (css.match(/expression/i)) { throw new Error('Unsafe CSS found in ' + foundInName + ': "expression"'); } return css; }
[ "function", "raiseOnUnsafeCSS", "(", ")", "{", "var", "css", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "''", ";", "var", "foundInName", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "'\\'not provided\\''", ";", "css", "=", "new", "_cleanCss2", ".", "default", "(", "{", "shorthandCompacting", ":", "false", "}", ")", ".", "minify", "(", "css", ")", ".", "styles", ";", "if", "(", "css", ".", "match", "(", "/", "-moz-binding", "/", "i", ")", ")", "{", "throw", "new", "Error", "(", "'Unsafe CSS found in '", "+", "foundInName", "+", "': \"-moz-binding\"'", ")", ";", "}", "else", "if", "(", "css", ".", "match", "(", "/", "expression", "/", "i", ")", ")", "{", "throw", "new", "Error", "(", "'Unsafe CSS found in '", "+", "foundInName", "+", "': \"expression\"'", ")", ";", "}", "return", "css", ";", "}" ]
Validate against common CSS vulnerabilities.
[ "Validate", "against", "common", "CSS", "vulnerabilities", "." ]
b15803a975d3c7842ab54da50e72200e17a0acaf
https://github.com/revivek/oy/blob/b15803a975d3c7842ab54da50e72200e17a0acaf/lib/utils/CSS.js#L15-L28
18,679
twskj/pretty-swag
pretty-swag.js
sortTags
function sortTags(tagA, tagB) { if ((tagA[0] === tagA[0].toUpperCase()) && (tagB[0] !== tagB[0].toUpperCase())) { return 1; } else if ((tagA[0] !== tagA[0].toUpperCase()) && (tagB[0] === tagB[0].toUpperCase())) { return -1; } else { return tagA < tagB; } }
javascript
function sortTags(tagA, tagB) { if ((tagA[0] === tagA[0].toUpperCase()) && (tagB[0] !== tagB[0].toUpperCase())) { return 1; } else if ((tagA[0] !== tagA[0].toUpperCase()) && (tagB[0] === tagB[0].toUpperCase())) { return -1; } else { return tagA < tagB; } }
[ "function", "sortTags", "(", "tagA", ",", "tagB", ")", "{", "if", "(", "(", "tagA", "[", "0", "]", "===", "tagA", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", "&&", "(", "tagB", "[", "0", "]", "!==", "tagB", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", ")", "{", "return", "1", ";", "}", "else", "if", "(", "(", "tagA", "[", "0", "]", "!==", "tagA", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", "&&", "(", "tagB", "[", "0", "]", "===", "tagB", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", ")", "{", "return", "-", "1", ";", "}", "else", "{", "return", "tagA", "<", "tagB", ";", "}", "}" ]
sort capital letter first
[ "sort", "capital", "letter", "first" ]
232486dd2482bb7b42522522a62921f746b43b0f
https://github.com/twskj/pretty-swag/blob/232486dd2482bb7b42522522a62921f746b43b0f/pretty-swag.js#L150-L161
18,680
TooTallNate/node-lame
lib/encoder.js
Encoder
function Encoder (opts) { if (!(this instanceof Encoder)) { return new Encoder(opts); } Transform.call(this, opts); // lame malloc()s the "gfp" buffer this.gfp = binding.lame_init(); // set default options if (!opts) opts = {}; if (null == opts.channels) opts.channels = 2; if (null == opts.bitDepth) opts.bitDepth = 16; if (null == opts.sampleRate) opts.sampleRate = 44100; if (null == opts.signed) opts.signed = opts.bitDepth != 8; if (opts.float && opts.bitDepth == DOUBLE_BITS) { this.inputType = PCM_TYPE_DOUBLE; } else if (opts.float && opts.bitDepth == FLOAT_BITS) { this.inputType = PCM_TYPE_FLOAT; } else if (!opts.float && opts.bitDepth == SHORT_BITS) { this.inputType = PCM_TYPE_SHORT_INT; } else { throw new Error('unsupported PCM format!'); } // copy over opts to the encoder instance Object.keys(opts).forEach(function(key){ if (key[0] != '_' && Encoder.prototype.hasOwnProperty(key)) { debug('setting opt %j', key); this[key] = opts[key]; } }, this); }
javascript
function Encoder (opts) { if (!(this instanceof Encoder)) { return new Encoder(opts); } Transform.call(this, opts); // lame malloc()s the "gfp" buffer this.gfp = binding.lame_init(); // set default options if (!opts) opts = {}; if (null == opts.channels) opts.channels = 2; if (null == opts.bitDepth) opts.bitDepth = 16; if (null == opts.sampleRate) opts.sampleRate = 44100; if (null == opts.signed) opts.signed = opts.bitDepth != 8; if (opts.float && opts.bitDepth == DOUBLE_BITS) { this.inputType = PCM_TYPE_DOUBLE; } else if (opts.float && opts.bitDepth == FLOAT_BITS) { this.inputType = PCM_TYPE_FLOAT; } else if (!opts.float && opts.bitDepth == SHORT_BITS) { this.inputType = PCM_TYPE_SHORT_INT; } else { throw new Error('unsupported PCM format!'); } // copy over opts to the encoder instance Object.keys(opts).forEach(function(key){ if (key[0] != '_' && Encoder.prototype.hasOwnProperty(key)) { debug('setting opt %j', key); this[key] = opts[key]; } }, this); }
[ "function", "Encoder", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Encoder", ")", ")", "{", "return", "new", "Encoder", "(", "opts", ")", ";", "}", "Transform", ".", "call", "(", "this", ",", "opts", ")", ";", "// lame malloc()s the \"gfp\" buffer", "this", ".", "gfp", "=", "binding", ".", "lame_init", "(", ")", ";", "// set default options", "if", "(", "!", "opts", ")", "opts", "=", "{", "}", ";", "if", "(", "null", "==", "opts", ".", "channels", ")", "opts", ".", "channels", "=", "2", ";", "if", "(", "null", "==", "opts", ".", "bitDepth", ")", "opts", ".", "bitDepth", "=", "16", ";", "if", "(", "null", "==", "opts", ".", "sampleRate", ")", "opts", ".", "sampleRate", "=", "44100", ";", "if", "(", "null", "==", "opts", ".", "signed", ")", "opts", ".", "signed", "=", "opts", ".", "bitDepth", "!=", "8", ";", "if", "(", "opts", ".", "float", "&&", "opts", ".", "bitDepth", "==", "DOUBLE_BITS", ")", "{", "this", ".", "inputType", "=", "PCM_TYPE_DOUBLE", ";", "}", "else", "if", "(", "opts", ".", "float", "&&", "opts", ".", "bitDepth", "==", "FLOAT_BITS", ")", "{", "this", ".", "inputType", "=", "PCM_TYPE_FLOAT", ";", "}", "else", "if", "(", "!", "opts", ".", "float", "&&", "opts", ".", "bitDepth", "==", "SHORT_BITS", ")", "{", "this", ".", "inputType", "=", "PCM_TYPE_SHORT_INT", ";", "}", "else", "{", "throw", "new", "Error", "(", "'unsupported PCM format!'", ")", ";", "}", "// copy over opts to the encoder instance", "Object", ".", "keys", "(", "opts", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "[", "0", "]", "!=", "'_'", "&&", "Encoder", ".", "prototype", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "debug", "(", "'setting opt %j'", ",", "key", ")", ";", "this", "[", "key", "]", "=", "opts", "[", "key", "]", ";", "}", "}", ",", "this", ")", ";", "}" ]
The `Encoder` class is a Transform stream class. Write raw PCM data, out comes an MP3 file. @param {Object} opts PCM stream format info and stream options @api public
[ "The", "Encoder", "class", "is", "a", "Transform", "stream", "class", ".", "Write", "raw", "PCM", "data", "out", "comes", "an", "MP3", "file", "." ]
8b2b798c48e95af1a12cdc30de6ad214d2308833
https://github.com/TooTallNate/node-lame/blob/8b2b798c48e95af1a12cdc30de6ad214d2308833/lib/encoder.js#L71-L104
18,681
TooTallNate/node-lame
lib/decoder.js
Decoder
function Decoder (opts) { if (!(this instanceof Decoder)) { return new Decoder(opts); } Transform.call(this, opts); var ret; ret = binding.mpg123_new(opts ? opts.decoder : null); if (Buffer.isBuffer(ret)) { this.mh = ret; } else { throw new Error('mpg123_new() failed: ' + ret); } ret = binding.mpg123_open_feed(this.mh); if (MPG123_OK != ret) { throw new Error('mpg123_open_feed() failed: ' + ret); } debug('created new Decoder instance'); }
javascript
function Decoder (opts) { if (!(this instanceof Decoder)) { return new Decoder(opts); } Transform.call(this, opts); var ret; ret = binding.mpg123_new(opts ? opts.decoder : null); if (Buffer.isBuffer(ret)) { this.mh = ret; } else { throw new Error('mpg123_new() failed: ' + ret); } ret = binding.mpg123_open_feed(this.mh); if (MPG123_OK != ret) { throw new Error('mpg123_open_feed() failed: ' + ret); } debug('created new Decoder instance'); }
[ "function", "Decoder", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Decoder", ")", ")", "{", "return", "new", "Decoder", "(", "opts", ")", ";", "}", "Transform", ".", "call", "(", "this", ",", "opts", ")", ";", "var", "ret", ";", "ret", "=", "binding", ".", "mpg123_new", "(", "opts", "?", "opts", ".", "decoder", ":", "null", ")", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "ret", ")", ")", "{", "this", ".", "mh", "=", "ret", ";", "}", "else", "{", "throw", "new", "Error", "(", "'mpg123_new() failed: '", "+", "ret", ")", ";", "}", "ret", "=", "binding", ".", "mpg123_open_feed", "(", "this", ".", "mh", ")", ";", "if", "(", "MPG123_OK", "!=", "ret", ")", "{", "throw", "new", "Error", "(", "'mpg123_open_feed() failed: '", "+", "ret", ")", ";", "}", "debug", "(", "'created new Decoder instance'", ")", ";", "}" ]
`Decoder` Stream class. Accepts an MP3 file and spits out raw PCM data.
[ "Decoder", "Stream", "class", ".", "Accepts", "an", "MP3", "file", "and", "spits", "out", "raw", "PCM", "data", "." ]
8b2b798c48e95af1a12cdc30de6ad214d2308833
https://github.com/TooTallNate/node-lame/blob/8b2b798c48e95af1a12cdc30de6ad214d2308833/lib/decoder.js#L46-L65
18,682
anvaka/ngraph.forcelayout
index.js
function() { if (bodiesCount === 0) return true; // TODO: This will never fire 'stable' var lastMove = physicsSimulator.step(); // Save the movement in case if someone wants to query it in the step // callback. api.lastMove = lastMove; // Allow listeners to perform low-level actions after nodes are updated. api.fire('step'); var ratio = lastMove/bodiesCount; var isStableNow = ratio <= 0.01; // TODO: The number is somewhat arbitrary... if (wasStable !== isStableNow) { wasStable = isStableNow; onStableChanged(isStableNow); } return isStableNow; }
javascript
function() { if (bodiesCount === 0) return true; // TODO: This will never fire 'stable' var lastMove = physicsSimulator.step(); // Save the movement in case if someone wants to query it in the step // callback. api.lastMove = lastMove; // Allow listeners to perform low-level actions after nodes are updated. api.fire('step'); var ratio = lastMove/bodiesCount; var isStableNow = ratio <= 0.01; // TODO: The number is somewhat arbitrary... if (wasStable !== isStableNow) { wasStable = isStableNow; onStableChanged(isStableNow); } return isStableNow; }
[ "function", "(", ")", "{", "if", "(", "bodiesCount", "===", "0", ")", "return", "true", ";", "// TODO: This will never fire 'stable'", "var", "lastMove", "=", "physicsSimulator", ".", "step", "(", ")", ";", "// Save the movement in case if someone wants to query it in the step", "// callback.", "api", ".", "lastMove", "=", "lastMove", ";", "// Allow listeners to perform low-level actions after nodes are updated.", "api", ".", "fire", "(", "'step'", ")", ";", "var", "ratio", "=", "lastMove", "/", "bodiesCount", ";", "var", "isStableNow", "=", "ratio", "<=", "0.01", ";", "// TODO: The number is somewhat arbitrary...", "if", "(", "wasStable", "!==", "isStableNow", ")", "{", "wasStable", "=", "isStableNow", ";", "onStableChanged", "(", "isStableNow", ")", ";", "}", "return", "isStableNow", ";", "}" ]
Performs one step of iterative layout algorithm @returns {boolean} true if the system should be considered stable; False otherwise. The system is stable if no further call to `step()` can improve the layout.
[ "Performs", "one", "step", "of", "iterative", "layout", "algorithm" ]
23f4e5e59628c7ec8a202f92d393a5bb91c3e5cf
https://github.com/anvaka/ngraph.forcelayout/blob/23f4e5e59628c7ec8a202f92d393a5bb91c3e5cf/index.js#L46-L67
18,683
anvaka/ngraph.forcelayout
index.js
function (nodeId) { var body = getInitializedBody(nodeId); body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1)); physicsSimulator.invalidateBBox(); }
javascript
function (nodeId) { var body = getInitializedBody(nodeId); body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1)); physicsSimulator.invalidateBBox(); }
[ "function", "(", "nodeId", ")", "{", "var", "body", "=", "getInitializedBody", "(", "nodeId", ")", ";", "body", ".", "setPosition", ".", "apply", "(", "body", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "physicsSimulator", ".", "invalidateBBox", "(", ")", ";", "}" ]
Sets position of a node to a given coordinates @param {string} nodeId node identifier @param {number} x position of a node @param {number} y position of a node @param {number=} z position of node (only if applicable to body)
[ "Sets", "position", "of", "a", "node", "to", "a", "given", "coordinates" ]
23f4e5e59628c7ec8a202f92d393a5bb91c3e5cf
https://github.com/anvaka/ngraph.forcelayout/blob/23f4e5e59628c7ec8a202f92d393a5bb91c3e5cf/index.js#L83-L87
18,684
anvaka/ngraph.forcelayout
index.js
isNodeOriginallyPinned
function isNodeOriginallyPinned(node) { return (node && (node.isPinned || (node.data && node.data.isPinned))); }
javascript
function isNodeOriginallyPinned(node) { return (node && (node.isPinned || (node.data && node.data.isPinned))); }
[ "function", "isNodeOriginallyPinned", "(", "node", ")", "{", "return", "(", "node", "&&", "(", "node", ".", "isPinned", "||", "(", "node", ".", "data", "&&", "node", ".", "data", ".", "isPinned", ")", ")", ")", ";", "}" ]
Checks whether graph node has in its settings pinned attribute, which means layout algorithm cannot move it. Node can be marked as pinned, if it has "isPinned" attribute, or when node.data has it. @param {Object} node a graph node to check @return {Boolean} true if node should be treated as pinned; false otherwise.
[ "Checks", "whether", "graph", "node", "has", "in", "its", "settings", "pinned", "attribute", "which", "means", "layout", "algorithm", "cannot", "move", "it", ".", "Node", "can", "be", "marked", "as", "pinned", "if", "it", "has", "isPinned", "attribute", "or", "when", "node", ".", "data", "has", "it", "." ]
23f4e5e59628c7ec8a202f92d393a5bb91c3e5cf
https://github.com/anvaka/ngraph.forcelayout/blob/23f4e5e59628c7ec8a202f92d393a5bb91c3e5cf/index.js#L349-L351
18,685
pouchdb-community/relational-pouch
lib/index.js
toRawDoc
function toRawDoc(typeInfo, obj) { obj = extend(true, {}, obj); var doc = {}; if (obj.rev) { doc._rev = obj.rev; delete obj.rev; } if (obj.attachments) { doc._attachments = obj.attachments; delete obj.attachments; } var id = obj.id || uuid(); delete obj.id; doc._id = serialize(typeInfo.documentType, id); if (typeInfo.relations) { Object.keys(typeInfo.relations).forEach(function (field) { var relationDef = typeInfo.relations[field]; var relationType = Object.keys(relationDef)[0]; if (relationType === 'belongsTo') { if (obj[field] && typeof obj[field].id !== 'undefined') { obj[field] = obj[field].id; } } else { // hasMany var relatedType = relationDef[relationType]; if (relatedType.options && relatedType.options.queryInverse) { delete obj[field]; return; } if (obj[field]) { var dependents = obj[field].map(function (dependent) { if (dependent && typeof dependent.id !== 'undefined') { return dependent.id; } return dependent; }); obj[field] = dependents; } else { obj[field] = []; } } }); } doc.data = obj; return doc; }
javascript
function toRawDoc(typeInfo, obj) { obj = extend(true, {}, obj); var doc = {}; if (obj.rev) { doc._rev = obj.rev; delete obj.rev; } if (obj.attachments) { doc._attachments = obj.attachments; delete obj.attachments; } var id = obj.id || uuid(); delete obj.id; doc._id = serialize(typeInfo.documentType, id); if (typeInfo.relations) { Object.keys(typeInfo.relations).forEach(function (field) { var relationDef = typeInfo.relations[field]; var relationType = Object.keys(relationDef)[0]; if (relationType === 'belongsTo') { if (obj[field] && typeof obj[field].id !== 'undefined') { obj[field] = obj[field].id; } } else { // hasMany var relatedType = relationDef[relationType]; if (relatedType.options && relatedType.options.queryInverse) { delete obj[field]; return; } if (obj[field]) { var dependents = obj[field].map(function (dependent) { if (dependent && typeof dependent.id !== 'undefined') { return dependent.id; } return dependent; }); obj[field] = dependents; } else { obj[field] = []; } } }); } doc.data = obj; return doc; }
[ "function", "toRawDoc", "(", "typeInfo", ",", "obj", ")", "{", "obj", "=", "extend", "(", "true", ",", "{", "}", ",", "obj", ")", ";", "var", "doc", "=", "{", "}", ";", "if", "(", "obj", ".", "rev", ")", "{", "doc", ".", "_rev", "=", "obj", ".", "rev", ";", "delete", "obj", ".", "rev", ";", "}", "if", "(", "obj", ".", "attachments", ")", "{", "doc", ".", "_attachments", "=", "obj", ".", "attachments", ";", "delete", "obj", ".", "attachments", ";", "}", "var", "id", "=", "obj", ".", "id", "||", "uuid", "(", ")", ";", "delete", "obj", ".", "id", ";", "doc", ".", "_id", "=", "serialize", "(", "typeInfo", ".", "documentType", ",", "id", ")", ";", "if", "(", "typeInfo", ".", "relations", ")", "{", "Object", ".", "keys", "(", "typeInfo", ".", "relations", ")", ".", "forEach", "(", "function", "(", "field", ")", "{", "var", "relationDef", "=", "typeInfo", ".", "relations", "[", "field", "]", ";", "var", "relationType", "=", "Object", ".", "keys", "(", "relationDef", ")", "[", "0", "]", ";", "if", "(", "relationType", "===", "'belongsTo'", ")", "{", "if", "(", "obj", "[", "field", "]", "&&", "typeof", "obj", "[", "field", "]", ".", "id", "!==", "'undefined'", ")", "{", "obj", "[", "field", "]", "=", "obj", "[", "field", "]", ".", "id", ";", "}", "}", "else", "{", "// hasMany", "var", "relatedType", "=", "relationDef", "[", "relationType", "]", ";", "if", "(", "relatedType", ".", "options", "&&", "relatedType", ".", "options", ".", "queryInverse", ")", "{", "delete", "obj", "[", "field", "]", ";", "return", ";", "}", "if", "(", "obj", "[", "field", "]", ")", "{", "var", "dependents", "=", "obj", "[", "field", "]", ".", "map", "(", "function", "(", "dependent", ")", "{", "if", "(", "dependent", "&&", "typeof", "dependent", ".", "id", "!==", "'undefined'", ")", "{", "return", "dependent", ".", "id", ";", "}", "return", "dependent", ";", "}", ")", ";", "obj", "[", "field", "]", "=", "dependents", ";", "}", "else", "{", "obj", "[", "field", "]", "=", "[", "]", ";", "}", "}", "}", ")", ";", "}", "doc", ".", "data", "=", "obj", ";", "return", "doc", ";", "}" ]
Transform a relational object into a PouchDB doc.
[ "Transform", "a", "relational", "object", "into", "a", "PouchDB", "doc", "." ]
19e871a10522c074ce5f59d57faa3f0b2e6337e3
https://github.com/pouchdb-community/relational-pouch/blob/19e871a10522c074ce5f59d57faa3f0b2e6337e3/lib/index.js#L98-L149
18,686
pouchdb-community/relational-pouch
lib/index.js
fromRawDoc
function fromRawDoc(pouchDoc) { var obj = pouchDoc.data; obj.id = deserialize(pouchDoc._id); obj.rev = pouchDoc._rev; if (pouchDoc._attachments) { obj.attachments = pouchDoc._attachments; } return obj; }
javascript
function fromRawDoc(pouchDoc) { var obj = pouchDoc.data; obj.id = deserialize(pouchDoc._id); obj.rev = pouchDoc._rev; if (pouchDoc._attachments) { obj.attachments = pouchDoc._attachments; } return obj; }
[ "function", "fromRawDoc", "(", "pouchDoc", ")", "{", "var", "obj", "=", "pouchDoc", ".", "data", ";", "obj", ".", "id", "=", "deserialize", "(", "pouchDoc", ".", "_id", ")", ";", "obj", ".", "rev", "=", "pouchDoc", ".", "_rev", ";", "if", "(", "pouchDoc", ".", "_attachments", ")", "{", "obj", ".", "attachments", "=", "pouchDoc", ".", "_attachments", ";", "}", "return", "obj", ";", "}" ]
Transform a PouchDB doc into a relational object.
[ "Transform", "a", "PouchDB", "doc", "into", "a", "relational", "object", "." ]
19e871a10522c074ce5f59d57faa3f0b2e6337e3
https://github.com/pouchdb-community/relational-pouch/blob/19e871a10522c074ce5f59d57faa3f0b2e6337e3/lib/index.js#L154-L162
18,687
pouchdb-community/relational-pouch
lib/index.js
isDeleted
function isDeleted(type, id) { var typeInfo = getTypeInfo(type); return db.get(serialize(typeInfo.documentType, id)) .then(function (doc) { return !!doc._deleted; }) .catch(function (err) { return err.reason === "deleted" ? true : null; }); }
javascript
function isDeleted(type, id) { var typeInfo = getTypeInfo(type); return db.get(serialize(typeInfo.documentType, id)) .then(function (doc) { return !!doc._deleted; }) .catch(function (err) { return err.reason === "deleted" ? true : null; }); }
[ "function", "isDeleted", "(", "type", ",", "id", ")", "{", "var", "typeInfo", "=", "getTypeInfo", "(", "type", ")", ";", "return", "db", ".", "get", "(", "serialize", "(", "typeInfo", ".", "documentType", ",", "id", ")", ")", ".", "then", "(", "function", "(", "doc", ")", "{", "return", "!", "!", "doc", ".", "_deleted", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "err", ".", "reason", "===", "\"deleted\"", "?", "true", ":", "null", ";", "}", ")", ";", "}" ]
true = deleted, false = exists, null = not in database
[ "true", "=", "deleted", "false", "=", "exists", "null", "=", "not", "in", "database" ]
19e871a10522c074ce5f59d57faa3f0b2e6337e3
https://github.com/pouchdb-community/relational-pouch/blob/19e871a10522c074ce5f59d57faa3f0b2e6337e3/lib/index.js#L246-L252
18,688
joeljeske/karma-parallel
lib/karma-parallelizer.js
initKarmaParallelizer
function initKarmaParallelizer(root, karma, shardIndexInfoMap) { var idParamExtractor = /(\?|&)id=(\d+)(&|$)/; var matches = idParamExtractor.exec(parent.location.search); var id = (matches && matches[2]) || null; if ( !id || !shardIndexInfoMap.hasOwnProperty(id) || !shardIndexInfoMap[id].shouldShard ) { /* eslint-disable-next-line no-console */ console.warn( 'Skipping sharding. Could not find karma-parallel initialization data.' ); return; } var shardIndexInfo = shardIndexInfoMap[id]; var strategy = overrideSuiteStategy(getSpecSuiteStrategy(shardIndexInfo)); var fakeContextStatus = createFakeTestContext(root, strategy); var origStart = karma.start; karma.start = function() { fakeContextStatus.beforeStartup(); origStart.call(this); }; }
javascript
function initKarmaParallelizer(root, karma, shardIndexInfoMap) { var idParamExtractor = /(\?|&)id=(\d+)(&|$)/; var matches = idParamExtractor.exec(parent.location.search); var id = (matches && matches[2]) || null; if ( !id || !shardIndexInfoMap.hasOwnProperty(id) || !shardIndexInfoMap[id].shouldShard ) { /* eslint-disable-next-line no-console */ console.warn( 'Skipping sharding. Could not find karma-parallel initialization data.' ); return; } var shardIndexInfo = shardIndexInfoMap[id]; var strategy = overrideSuiteStategy(getSpecSuiteStrategy(shardIndexInfo)); var fakeContextStatus = createFakeTestContext(root, strategy); var origStart = karma.start; karma.start = function() { fakeContextStatus.beforeStartup(); origStart.call(this); }; }
[ "function", "initKarmaParallelizer", "(", "root", ",", "karma", ",", "shardIndexInfoMap", ")", "{", "var", "idParamExtractor", "=", "/", "(\\?|&)id=(\\d+)(&|$)", "/", ";", "var", "matches", "=", "idParamExtractor", ".", "exec", "(", "parent", ".", "location", ".", "search", ")", ";", "var", "id", "=", "(", "matches", "&&", "matches", "[", "2", "]", ")", "||", "null", ";", "if", "(", "!", "id", "||", "!", "shardIndexInfoMap", ".", "hasOwnProperty", "(", "id", ")", "||", "!", "shardIndexInfoMap", "[", "id", "]", ".", "shouldShard", ")", "{", "/* eslint-disable-next-line no-console */", "console", ".", "warn", "(", "'Skipping sharding. Could not find karma-parallel initialization data.'", ")", ";", "return", ";", "}", "var", "shardIndexInfo", "=", "shardIndexInfoMap", "[", "id", "]", ";", "var", "strategy", "=", "overrideSuiteStategy", "(", "getSpecSuiteStrategy", "(", "shardIndexInfo", ")", ")", ";", "var", "fakeContextStatus", "=", "createFakeTestContext", "(", "root", ",", "strategy", ")", ";", "var", "origStart", "=", "karma", ".", "start", ";", "karma", ".", "start", "=", "function", "(", ")", "{", "fakeContextStatus", ".", "beforeStartup", "(", ")", ";", "origStart", ".", "call", "(", "this", ")", ";", "}", ";", "}" ]
This file gets loaded into the executing browsers and overrides the `describe` functions
[ "This", "file", "gets", "loaded", "into", "the", "executing", "browsers", "and", "overrides", "the", "describe", "functions" ]
17cebcb41c270d200e2fe023121c7802020e461f
https://github.com/joeljeske/karma-parallel/blob/17cebcb41c270d200e2fe023121c7802020e461f/lib/karma-parallelizer.js#L5-L31
18,689
joeljeske/karma-parallel
lib/karma-parallelizer.js
wrap
function wrap(fn, isFocus, isDescription, isSpec) { if (!fn) return fn; return function(name, def) { if (isDescription && depth === 0) { // Reset isFaking on top-level descriptions isFaking = !shouldUseDescription(name, def); } hasOwnSpecs = hasOwnSpecs || (isSpec && !isFaking); hasOtherSpecs = hasOtherSpecs || (isSpec && isFaking); hasFocusedWhileFaking = hasFocusedWhileFaking || (isFocus && isFaking); hasFocusedWithoutFaking = hasFocusedWithoutFaking || (isFocus && !isFaking); if (isDescription) def = wrapDescription(def); if (!isFaking || forceDescribe) { // Call through to framework and return the result return fn.call(this, name, def); } else if (isDescription) { // If its a fake description, then we need to call through to eval inner its() looking for focuses // TODO, do we ever need parameters? def(); } }; }
javascript
function wrap(fn, isFocus, isDescription, isSpec) { if (!fn) return fn; return function(name, def) { if (isDescription && depth === 0) { // Reset isFaking on top-level descriptions isFaking = !shouldUseDescription(name, def); } hasOwnSpecs = hasOwnSpecs || (isSpec && !isFaking); hasOtherSpecs = hasOtherSpecs || (isSpec && isFaking); hasFocusedWhileFaking = hasFocusedWhileFaking || (isFocus && isFaking); hasFocusedWithoutFaking = hasFocusedWithoutFaking || (isFocus && !isFaking); if (isDescription) def = wrapDescription(def); if (!isFaking || forceDescribe) { // Call through to framework and return the result return fn.call(this, name, def); } else if (isDescription) { // If its a fake description, then we need to call through to eval inner its() looking for focuses // TODO, do we ever need parameters? def(); } }; }
[ "function", "wrap", "(", "fn", ",", "isFocus", ",", "isDescription", ",", "isSpec", ")", "{", "if", "(", "!", "fn", ")", "return", "fn", ";", "return", "function", "(", "name", ",", "def", ")", "{", "if", "(", "isDescription", "&&", "depth", "===", "0", ")", "{", "// Reset isFaking on top-level descriptions", "isFaking", "=", "!", "shouldUseDescription", "(", "name", ",", "def", ")", ";", "}", "hasOwnSpecs", "=", "hasOwnSpecs", "||", "(", "isSpec", "&&", "!", "isFaking", ")", ";", "hasOtherSpecs", "=", "hasOtherSpecs", "||", "(", "isSpec", "&&", "isFaking", ")", ";", "hasFocusedWhileFaking", "=", "hasFocusedWhileFaking", "||", "(", "isFocus", "&&", "isFaking", ")", ";", "hasFocusedWithoutFaking", "=", "hasFocusedWithoutFaking", "||", "(", "isFocus", "&&", "!", "isFaking", ")", ";", "if", "(", "isDescription", ")", "def", "=", "wrapDescription", "(", "def", ")", ";", "if", "(", "!", "isFaking", "||", "forceDescribe", ")", "{", "// Call through to framework and return the result", "return", "fn", ".", "call", "(", "this", ",", "name", ",", "def", ")", ";", "}", "else", "if", "(", "isDescription", ")", "{", "// If its a fake description, then we need to call through to eval inner its() looking for focuses", "// TODO, do we ever need parameters?", "def", "(", ")", ";", "}", "}", ";", "}" ]
On focus spec in mocha we need to return the test result and need to
[ "On", "focus", "spec", "in", "mocha", "we", "need", "to", "return", "the", "test", "result", "and", "need", "to" ]
17cebcb41c270d200e2fe023121c7802020e461f
https://github.com/joeljeske/karma-parallel/blob/17cebcb41c270d200e2fe023121c7802020e461f/lib/karma-parallelizer.js#L109-L134
18,690
makeomatic/redux-connect
modules/containers/decorator.js
wrapWithDispatch
function wrapWithDispatch(asyncItems) { return asyncItems.map((item) => { const { key } = item; if (!key) return item; return { ...item, promise: (options) => { const { store: { dispatch } } = options; const next = item.promise(options); // NOTE: possibly refactor this with a breaking change in mind for future versions // we can return result of processed promise/thunk if need be if (isPromise(next)) { dispatch(load(key)); // add action dispatchers next .then(data => dispatch(loadSuccess(key, data))) .catch(err => dispatch(loadFail(key, err))); } else if (next) { dispatch(loadSuccess(key, next)); } return next; }, }; }); }
javascript
function wrapWithDispatch(asyncItems) { return asyncItems.map((item) => { const { key } = item; if (!key) return item; return { ...item, promise: (options) => { const { store: { dispatch } } = options; const next = item.promise(options); // NOTE: possibly refactor this with a breaking change in mind for future versions // we can return result of processed promise/thunk if need be if (isPromise(next)) { dispatch(load(key)); // add action dispatchers next .then(data => dispatch(loadSuccess(key, data))) .catch(err => dispatch(loadFail(key, err))); } else if (next) { dispatch(loadSuccess(key, next)); } return next; }, }; }); }
[ "function", "wrapWithDispatch", "(", "asyncItems", ")", "{", "return", "asyncItems", ".", "map", "(", "(", "item", ")", "=>", "{", "const", "{", "key", "}", "=", "item", ";", "if", "(", "!", "key", ")", "return", "item", ";", "return", "{", "...", "item", ",", "promise", ":", "(", "options", ")", "=>", "{", "const", "{", "store", ":", "{", "dispatch", "}", "}", "=", "options", ";", "const", "next", "=", "item", ".", "promise", "(", "options", ")", ";", "// NOTE: possibly refactor this with a breaking change in mind for future versions", "// we can return result of processed promise/thunk if need be", "if", "(", "isPromise", "(", "next", ")", ")", "{", "dispatch", "(", "load", "(", "key", ")", ")", ";", "// add action dispatchers", "next", ".", "then", "(", "data", "=>", "dispatch", "(", "loadSuccess", "(", "key", ",", "data", ")", ")", ")", ".", "catch", "(", "err", "=>", "dispatch", "(", "loadFail", "(", "key", ",", "err", ")", ")", ")", ";", "}", "else", "if", "(", "next", ")", "{", "dispatch", "(", "loadSuccess", "(", "key", ",", "next", ")", ")", ";", "}", "return", "next", ";", "}", ",", "}", ";", "}", ")", ";", "}" ]
Wraps react components with data loaders @param {Array} asyncItems @return {WrappedComponent}
[ "Wraps", "react", "components", "with", "data", "loaders" ]
a4b292ba14e6137cf3d975ba55814f846cbb0300
https://github.com/makeomatic/redux-connect/blob/a4b292ba14e6137cf3d975ba55814f846cbb0300/modules/containers/decorator.js#L11-L38
18,691
ecomfe/est
lib/custom-functions.js
function (less) { var Keyword = less.tree.Keyword; var DetachedRuleset = less.tree.DetachedRuleset; var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; }; if (!functions) { functions = { isruleset: function (n) { return isa(n, DetachedRuleset); } }; } return functions; }
javascript
function (less) { var Keyword = less.tree.Keyword; var DetachedRuleset = less.tree.DetachedRuleset; var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; }; if (!functions) { functions = { isruleset: function (n) { return isa(n, DetachedRuleset); } }; } return functions; }
[ "function", "(", "less", ")", "{", "var", "Keyword", "=", "less", ".", "tree", ".", "Keyword", ";", "var", "DetachedRuleset", "=", "less", ".", "tree", ".", "DetachedRuleset", ";", "var", "isa", "=", "function", "(", "n", ",", "Type", ")", "{", "return", "(", "n", "instanceof", "Type", ")", "?", "Keyword", ".", "True", ":", "Keyword", ".", "False", ";", "}", ";", "if", "(", "!", "functions", ")", "{", "functions", "=", "{", "isruleset", ":", "function", "(", "n", ")", "{", "return", "isa", "(", "n", ",", "DetachedRuleset", ")", ";", "}", "}", ";", "}", "return", "functions", ";", "}" ]
Get an instance of the plugin module @param {Object} less the less.js instance @return {Object} the functions to be injected
[ "Get", "an", "instance", "of", "the", "plugin", "module" ]
0c6858c925abf7d208ab977b3f4c0000307318b6
https://github.com/ecomfe/est/blob/0c6858c925abf7d208ab977b3f4c0000307318b6/lib/custom-functions.js#L37-L54
18,692
ecomfe/est
lib/index.js
extend
function extend(dest, source) { dest = dest || {}; source = source || {}; var result = clone(dest); for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = source[key]; } } return result; }
javascript
function extend(dest, source) { dest = dest || {}; source = source || {}; var result = clone(dest); for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = source[key]; } } return result; }
[ "function", "extend", "(", "dest", ",", "source", ")", "{", "dest", "=", "dest", "||", "{", "}", ";", "source", "=", "source", "||", "{", "}", ";", "var", "result", "=", "clone", "(", "dest", ")", ";", "for", "(", "var", "key", "in", "source", ")", "{", "if", "(", "source", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "result", "[", "key", "]", "=", "source", "[", "key", "]", ";", "}", "}", "return", "result", ";", "}" ]
Extend the destination object with the given source @param {Object} dest the object to be extended @param {Object} source the source object @return {Object} the extended object
[ "Extend", "the", "destination", "object", "with", "the", "given", "source" ]
0c6858c925abf7d208ab977b3f4c0000307318b6
https://github.com/ecomfe/est/blob/0c6858c925abf7d208ab977b3f4c0000307318b6/lib/index.js#L33-L44
18,693
ecomfe/est
lib/index.js
function (qs) { var items = qs.split('&'); var options = {}; items = items.filter(function (item) { return item.match(/^[\w_-]+=?$|^[\w_-]+=[^=]+$/); }).forEach(function (item) { var kv = item.split('='); var value = kv[1]; if (value === undefined || value === '') { value = true; } else if (value.toLowerCase() === 'false') { value = false; } options[kv[0]] = value; }); return options; }
javascript
function (qs) { var items = qs.split('&'); var options = {}; items = items.filter(function (item) { return item.match(/^[\w_-]+=?$|^[\w_-]+=[^=]+$/); }).forEach(function (item) { var kv = item.split('='); var value = kv[1]; if (value === undefined || value === '') { value = true; } else if (value.toLowerCase() === 'false') { value = false; } options[kv[0]] = value; }); return options; }
[ "function", "(", "qs", ")", "{", "var", "items", "=", "qs", ".", "split", "(", "'&'", ")", ";", "var", "options", "=", "{", "}", ";", "items", "=", "items", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", ".", "match", "(", "/", "^[\\w_-]+=?$|^[\\w_-]+=[^=]+$", "/", ")", ";", "}", ")", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "kv", "=", "item", ".", "split", "(", "'='", ")", ";", "var", "value", "=", "kv", "[", "1", "]", ";", "if", "(", "value", "===", "undefined", "||", "value", "===", "''", ")", "{", "value", "=", "true", ";", "}", "else", "if", "(", "value", ".", "toLowerCase", "(", ")", "===", "'false'", ")", "{", "value", "=", "false", ";", "}", "options", "[", "kv", "[", "0", "]", "]", "=", "value", ";", "}", ")", ";", "return", "options", ";", "}" ]
Parses the plugin options @method @param {string} qs the input query string @return {Object} the parse result
[ "Parses", "the", "plugin", "options" ]
0c6858c925abf7d208ab977b3f4c0000307318b6
https://github.com/ecomfe/est/blob/0c6858c925abf7d208ab977b3f4c0000307318b6/lib/index.js#L138-L156
18,694
trailsjs/sails-permissions
api/services/PermissionService.js
function(objects, user) { if (!_.isArray(objects)) { return PermissionService.isForeignObject(user.id)(objects); } return _.any(objects, PermissionService.isForeignObject(user.id)); }
javascript
function(objects, user) { if (!_.isArray(objects)) { return PermissionService.isForeignObject(user.id)(objects); } return _.any(objects, PermissionService.isForeignObject(user.id)); }
[ "function", "(", "objects", ",", "user", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "objects", ")", ")", "{", "return", "PermissionService", ".", "isForeignObject", "(", "user", ".", "id", ")", "(", "objects", ")", ";", "}", "return", "_", ".", "any", "(", "objects", ",", "PermissionService", ".", "isForeignObject", "(", "user", ".", "id", ")", ")", ";", "}" ]
Given an object, or a list of objects, return true if the list contains objects not owned by the specified user.
[ "Given", "an", "object", "or", "a", "list", "of", "objects", "return", "true", "if", "the", "list", "contains", "objects", "not", "owned", "by", "the", "specified", "user", "." ]
826d504711662bf43a5c266667dd4487553a8a41
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/PermissionService.js#L18-L23
18,695
trailsjs/sails-permissions
api/services/PermissionService.js
function(req) { // handle add/remove routes that have :parentid as the primary key field var originalId; if (req.params.parentid) { originalId = req.params.id; req.params.id = req.params.parentid; } return new Promise(function(resolve, reject) { sails.hooks.blueprints.middleware.find(req, { ok: resolve, serverError: reject, // this isn't perfect, since it returns a 500 error instead of a 404 error // but it is better than crashing the app when a record doesn't exist notFound: reject }); }) .then(function(result) { if (originalId !== undefined) { req.params.id = originalId; } return result; }); }
javascript
function(req) { // handle add/remove routes that have :parentid as the primary key field var originalId; if (req.params.parentid) { originalId = req.params.id; req.params.id = req.params.parentid; } return new Promise(function(resolve, reject) { sails.hooks.blueprints.middleware.find(req, { ok: resolve, serverError: reject, // this isn't perfect, since it returns a 500 error instead of a 404 error // but it is better than crashing the app when a record doesn't exist notFound: reject }); }) .then(function(result) { if (originalId !== undefined) { req.params.id = originalId; } return result; }); }
[ "function", "(", "req", ")", "{", "// handle add/remove routes that have :parentid as the primary key field", "var", "originalId", ";", "if", "(", "req", ".", "params", ".", "parentid", ")", "{", "originalId", "=", "req", ".", "params", ".", "id", ";", "req", ".", "params", ".", "id", "=", "req", ".", "params", ".", "parentid", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "sails", ".", "hooks", ".", "blueprints", ".", "middleware", ".", "find", "(", "req", ",", "{", "ok", ":", "resolve", ",", "serverError", ":", "reject", ",", "// this isn't perfect, since it returns a 500 error instead of a 404 error", "// but it is better than crashing the app when a record doesn't exist", "notFound", ":", "reject", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "originalId", "!==", "undefined", ")", "{", "req", ".", "params", ".", "id", "=", "originalId", ";", "}", "return", "result", ";", "}", ")", ";", "}" ]
Find objects that some arbitrary action would be performed on, given the same request. @param options.model @param options.query TODO this will be less expensive when waterline supports a caching layer
[ "Find", "objects", "that", "some", "arbitrary", "action", "would", "be", "performed", "on", "given", "the", "same", "request", "." ]
826d504711662bf43a5c266667dd4487553a8a41
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/PermissionService.js#L45-L70
18,696
trailsjs/sails-permissions
api/services/PermissionService.js
function(options) { var user = options.user.email || options.user.username return [ 'User', user, 'is not permitted to', options.method, options.model.name ].join(' '); }
javascript
function(options) { var user = options.user.email || options.user.username return [ 'User', user, 'is not permitted to', options.method, options.model.name ].join(' '); }
[ "function", "(", "options", ")", "{", "var", "user", "=", "options", ".", "user", ".", "email", "||", "options", ".", "user", ".", "username", "return", "[", "'User'", ",", "user", ",", "'is not permitted to'", ",", "options", ".", "method", ",", "options", ".", "model", ".", "name", "]", ".", "join", "(", "' '", ")", ";", "}" ]
Build an error message
[ "Build", "an", "error", "message" ]
826d504711662bf43a5c266667dd4487553a8a41
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/PermissionService.js#L186-L191
18,697
trailsjs/sails-permissions
api/services/PermissionService.js
function(options) { var ok = Promise.resolve(); var permissions = options.permissions; if (!_.isArray(permissions)) { permissions = [permissions]; } // look up the model id based on the model name for each permission, and change it to an id ok = ok.then(function() { return Promise.all(permissions.map(function(permission) { return Model.findOne({ name: permission.model }) .then(function(model) { permission.model = model.id; return permission; }); })); }); // look up user ids based on usernames, and replace the names with ids ok = ok.then(function(permissions) { if (options.users) { return User.find({ username: options.users }) .then(function(users) { options.users = users; }); } }); ok = ok.then(function(users) { return Role.create(options); }); return ok; }
javascript
function(options) { var ok = Promise.resolve(); var permissions = options.permissions; if (!_.isArray(permissions)) { permissions = [permissions]; } // look up the model id based on the model name for each permission, and change it to an id ok = ok.then(function() { return Promise.all(permissions.map(function(permission) { return Model.findOne({ name: permission.model }) .then(function(model) { permission.model = model.id; return permission; }); })); }); // look up user ids based on usernames, and replace the names with ids ok = ok.then(function(permissions) { if (options.users) { return User.find({ username: options.users }) .then(function(users) { options.users = users; }); } }); ok = ok.then(function(users) { return Role.create(options); }); return ok; }
[ "function", "(", "options", ")", "{", "var", "ok", "=", "Promise", ".", "resolve", "(", ")", ";", "var", "permissions", "=", "options", ".", "permissions", ";", "if", "(", "!", "_", ".", "isArray", "(", "permissions", ")", ")", "{", "permissions", "=", "[", "permissions", "]", ";", "}", "// look up the model id based on the model name for each permission, and change it to an id", "ok", "=", "ok", ".", "then", "(", "function", "(", ")", "{", "return", "Promise", ".", "all", "(", "permissions", ".", "map", "(", "function", "(", "permission", ")", "{", "return", "Model", ".", "findOne", "(", "{", "name", ":", "permission", ".", "model", "}", ")", ".", "then", "(", "function", "(", "model", ")", "{", "permission", ".", "model", "=", "model", ".", "id", ";", "return", "permission", ";", "}", ")", ";", "}", ")", ")", ";", "}", ")", ";", "// look up user ids based on usernames, and replace the names with ids", "ok", "=", "ok", ".", "then", "(", "function", "(", "permissions", ")", "{", "if", "(", "options", ".", "users", ")", "{", "return", "User", ".", "find", "(", "{", "username", ":", "options", ".", "users", "}", ")", ".", "then", "(", "function", "(", "users", ")", "{", "options", ".", "users", "=", "users", ";", "}", ")", ";", "}", "}", ")", ";", "ok", "=", "ok", ".", "then", "(", "function", "(", "users", ")", "{", "return", "Role", ".", "create", "(", "options", ")", ";", "}", ")", ";", "return", "ok", ";", "}" ]
create a new role @param options @param options.name {string} - role name @param options.permissions {permission object, or array of permissions objects} @param options.permissions.model {string} - the name of the model that the permission is associated with @param options.permissions.criteria - optional criteria object @param options.permissions.criteria.where - optional waterline query syntax object for specifying permissions @param options.permissions.criteria.blacklist {string array} - optional attribute blacklist @param options.users {array of user names} - optional array of user ids that have this role
[ "create", "a", "new", "role" ]
826d504711662bf43a5c266667dd4487553a8a41
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/PermissionService.js#L211-L251
18,698
trailsjs/sails-permissions
api/services/PermissionService.js
function(options) { var findRole = options.role ? Role.findOne({ name: options.role }) : null; var findUser = options.user ? User.findOne({ username: options.user }) : null; var ok = Promise.all([findRole, findUser, Model.findOne({ name: options.model })]); ok = ok.then(([ role, user, model ]) => { var query = { model: model.id, action: options.action, relation: options.relation }; if (role && role.id) { query.role = role.id; } else if (user && user.id) { query.user = user.id; } else { return Promise.reject(new Error('You must provide either a user or role to revoke the permission from')); } return Permission.destroy(query); }); return ok; }
javascript
function(options) { var findRole = options.role ? Role.findOne({ name: options.role }) : null; var findUser = options.user ? User.findOne({ username: options.user }) : null; var ok = Promise.all([findRole, findUser, Model.findOne({ name: options.model })]); ok = ok.then(([ role, user, model ]) => { var query = { model: model.id, action: options.action, relation: options.relation }; if (role && role.id) { query.role = role.id; } else if (user && user.id) { query.user = user.id; } else { return Promise.reject(new Error('You must provide either a user or role to revoke the permission from')); } return Permission.destroy(query); }); return ok; }
[ "function", "(", "options", ")", "{", "var", "findRole", "=", "options", ".", "role", "?", "Role", ".", "findOne", "(", "{", "name", ":", "options", ".", "role", "}", ")", ":", "null", ";", "var", "findUser", "=", "options", ".", "user", "?", "User", ".", "findOne", "(", "{", "username", ":", "options", ".", "user", "}", ")", ":", "null", ";", "var", "ok", "=", "Promise", ".", "all", "(", "[", "findRole", ",", "findUser", ",", "Model", ".", "findOne", "(", "{", "name", ":", "options", ".", "model", "}", ")", "]", ")", ";", "ok", "=", "ok", ".", "then", "(", "(", "[", "role", ",", "user", ",", "model", "]", ")", "=>", "{", "var", "query", "=", "{", "model", ":", "model", ".", "id", ",", "action", ":", "options", ".", "action", ",", "relation", ":", "options", ".", "relation", "}", ";", "if", "(", "role", "&&", "role", ".", "id", ")", "{", "query", ".", "role", "=", "role", ".", "id", ";", "}", "else", "if", "(", "user", "&&", "user", ".", "id", ")", "{", "query", ".", "user", "=", "user", ".", "id", ";", "}", "else", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'You must provide either a user or role to revoke the permission from'", ")", ")", ";", "}", "return", "Permission", ".", "destroy", "(", "query", ")", ";", "}", ")", ";", "return", "ok", ";", "}" ]
revoke permission from role @param options @param options.role {string} - the name of the role related to the permission. This, or options.user should be set, but not both. @param options.user {string} - the name of the user related to the permission. This, or options.role should be set, but not both. @param options.model {string} - the name of the model for the permission @param options.action {string} - the name of the action for the permission @param options.relation {string} - the type of the relation (owner or role)
[ "revoke", "permission", "from", "role" ]
826d504711662bf43a5c266667dd4487553a8a41
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/PermissionService.js#L370-L401
18,699
trailsjs/sails-permissions
api/services/PermissionService.js
function(user, action, model, body) { return function(obj) { return new Promise(function(resolve, reject) { Model.findOne({ identity: model }).then(function(model) { return Permission.find({ model: model.id, action: action, relation: 'user', user: user }).populate('criteria'); }).then(function(permission) { if (permission.length > 0 && PermissionService.hasPassingCriteria(obj, permission, body)) { resolve(true); } else { resolve(false); } }).catch(reject); }); }; }
javascript
function(user, action, model, body) { return function(obj) { return new Promise(function(resolve, reject) { Model.findOne({ identity: model }).then(function(model) { return Permission.find({ model: model.id, action: action, relation: 'user', user: user }).populate('criteria'); }).then(function(permission) { if (permission.length > 0 && PermissionService.hasPassingCriteria(obj, permission, body)) { resolve(true); } else { resolve(false); } }).catch(reject); }); }; }
[ "function", "(", "user", ",", "action", ",", "model", ",", "body", ")", "{", "return", "function", "(", "obj", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "Model", ".", "findOne", "(", "{", "identity", ":", "model", "}", ")", ".", "then", "(", "function", "(", "model", ")", "{", "return", "Permission", ".", "find", "(", "{", "model", ":", "model", ".", "id", ",", "action", ":", "action", ",", "relation", ":", "'user'", ",", "user", ":", "user", "}", ")", ".", "populate", "(", "'criteria'", ")", ";", "}", ")", ".", "then", "(", "function", "(", "permission", ")", "{", "if", "(", "permission", ".", "length", ">", "0", "&&", "PermissionService", ".", "hasPassingCriteria", "(", "obj", ",", "permission", ",", "body", ")", ")", "{", "resolve", "(", "true", ")", ";", "}", "else", "{", "resolve", "(", "false", ")", ";", "}", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ";", "}", ";", "}" ]
Resolve if the user have the permission to perform this action @param user @param action @param model @param body @returns {Function}
[ "Resolve", "if", "the", "user", "have", "the", "permission", "to", "perform", "this", "action" ]
826d504711662bf43a5c266667dd4487553a8a41
https://github.com/trailsjs/sails-permissions/blob/826d504711662bf43a5c266667dd4487553a8a41/api/services/PermissionService.js#L432-L453