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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
adamgruber/mochawesome | src/utils.js | log | function log(msg, level, config) {
// Don't log messages in quiet mode
if (config && config.quiet) return;
const logMethod = console[level] || console.log;
let out = msg;
if (typeof msg === 'object') {
out = stringify(msg, null, 2);
}
logMethod(`[${chalk.gray('mochawesome')}] ${out}\n`);
} | javascript | function log(msg, level, config) {
// Don't log messages in quiet mode
if (config && config.quiet) return;
const logMethod = console[level] || console.log;
let out = msg;
if (typeof msg === 'object') {
out = stringify(msg, null, 2);
}
logMethod(`[${chalk.gray('mochawesome')}] ${out}\n`);
} | [
"function",
"log",
"(",
"msg",
",",
"level",
",",
"config",
")",
"{",
"// Don't log messages in quiet mode",
"if",
"(",
"config",
"&&",
"config",
".",
"quiet",
")",
"return",
";",
"const",
"logMethod",
"=",
"console",
"[",
"level",
"]",
"||",
"console",
".... | Return a classname based on percentage
@param {String} msg - message to log
@param {String} level - log level [log, info, warn, error]
@param {Object} config - configuration object | [
"Return",
"a",
"classname",
"based",
"on",
"percentage"
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L17-L26 | train |
adamgruber/mochawesome | src/utils.js | cleanCode | function cleanCode(str) {
str = str
.replace(/\r\n|[\r\n\u2028\u2029]/g, '\n') // unify linebreaks
.replace(/^\uFEFF/, ''); // replace zero-width no-break space
str = stripFnStart(str) // replace function declaration
.replace(/\)\s*\)\s*$/, ')') // replace closing paren
.replace(/\s*};?\s*$/, ''); ... | javascript | function cleanCode(str) {
str = str
.replace(/\r\n|[\r\n\u2028\u2029]/g, '\n') // unify linebreaks
.replace(/^\uFEFF/, ''); // replace zero-width no-break space
str = stripFnStart(str) // replace function declaration
.replace(/\)\s*\)\s*$/, ')') // replace closing paren
.replace(/\s*};?\s*$/, ''); ... | [
"function",
"cleanCode",
"(",
"str",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\r\\n|[\\r\\n\\u2028\\u2029]",
"/",
"g",
",",
"'\\n'",
")",
"// unify linebreaks",
".",
"replace",
"(",
"/",
"^\\uFEFF",
"/",
",",
"''",
")",
";",
"// replace zer... | Strip the function definition from `str`,
and re-indent for pre whitespace.
@param {String} str - code in
@return {String} cleaned code string | [
"Strip",
"the",
"function",
"definition",
"from",
"str",
"and",
"re",
"-",
"indent",
"for",
"pre",
"whitespace",
"."
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L53-L71 | train |
adamgruber/mochawesome | src/utils.js | createUnifiedDiff | function createUnifiedDiff({ actual, expected }) {
return diff.createPatch('string', actual, expected)
.split('\n')
.splice(4)
.map(line => {
if (line.match(/@@/)) {
return null;
}
if (line.match(/\\ No newline/)) {
return null;
}
return line.replace(/^(-|\+)/... | javascript | function createUnifiedDiff({ actual, expected }) {
return diff.createPatch('string', actual, expected)
.split('\n')
.splice(4)
.map(line => {
if (line.match(/@@/)) {
return null;
}
if (line.match(/\\ No newline/)) {
return null;
}
return line.replace(/^(-|\+)/... | [
"function",
"createUnifiedDiff",
"(",
"{",
"actual",
",",
"expected",
"}",
")",
"{",
"return",
"diff",
".",
"createPatch",
"(",
"'string'",
",",
"actual",
",",
"expected",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"splice",
"(",
"4",
")",
".",
"map",
... | Create a unified diff between two strings
@param {Error} err Error object
@param {string} err.actual Actual result returned
@param {string} err.expected Result expected
@return {string} diff | [
"Create",
"a",
"unified",
"diff",
"between",
"two",
"strings"
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L82-L97 | train |
adamgruber/mochawesome | src/utils.js | normalizeErr | function normalizeErr(err, config) {
const { name, message, actual, expected, stack, showDiff } = err;
let errMessage;
let errDiff;
/**
* Check that a / b have the same type.
*/
function sameType(a, b) {
const objToString = Object.prototype.toString;
return objToString.call(a) === objToString.c... | javascript | function normalizeErr(err, config) {
const { name, message, actual, expected, stack, showDiff } = err;
let errMessage;
let errDiff;
/**
* Check that a / b have the same type.
*/
function sameType(a, b) {
const objToString = Object.prototype.toString;
return objToString.call(a) === objToString.c... | [
"function",
"normalizeErr",
"(",
"err",
",",
"config",
")",
"{",
"const",
"{",
"name",
",",
"message",
",",
"actual",
",",
"expected",
",",
"stack",
",",
"showDiff",
"}",
"=",
"err",
";",
"let",
"errMessage",
";",
"let",
"errDiff",
";",
"/**\n * Check ... | Return a normalized error object
@param {Error} err Error object
@return {Object} normalized error | [
"Return",
"a",
"normalized",
"error",
"object"
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L119-L155 | train |
adamgruber/mochawesome | src/utils.js | cleanSuite | function cleanSuite(suite, totalTestsRegistered, config) {
let duration = 0;
const passingTests = [];
const failingTests = [];
const pendingTests = [];
const skippedTests = [];
const beforeHooks = _.map(
[].concat(suite._beforeAll, suite._beforeEach),
test => cleanTest(test, config)
);
const a... | javascript | function cleanSuite(suite, totalTestsRegistered, config) {
let duration = 0;
const passingTests = [];
const failingTests = [];
const pendingTests = [];
const skippedTests = [];
const beforeHooks = _.map(
[].concat(suite._beforeAll, suite._beforeEach),
test => cleanTest(test, config)
);
const a... | [
"function",
"cleanSuite",
"(",
"suite",
",",
"totalTestsRegistered",
",",
"config",
")",
"{",
"let",
"duration",
"=",
"0",
";",
"const",
"passingTests",
"=",
"[",
"]",
";",
"const",
"failingTests",
"=",
"[",
"]",
";",
"const",
"pendingTests",
"=",
"[",
"... | Return a plain-object representation of `suite` with additional properties for rendering.
@param {Object} suite
@param {Object} totalTestsRegistered
@param {Integer} totalTestsRegistered.total
@return {Object|boolean} cleaned suite or false if suite is empty | [
"Return",
"a",
"plain",
"-",
"object",
"representation",
"of",
"suite",
"with",
"additional",
"properties",
"for",
"rendering",
"."
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L207-L264 | train |
adamgruber/mochawesome | src/utils.js | mapSuites | function mapSuites(suite, totalTestsReg, config) {
const suites = _.compact(_.map(suite.suites, subSuite => (
mapSuites(subSuite, totalTestsReg, config)
)));
const toBeCleaned = Object.assign({}, suite, { suites });
return cleanSuite(toBeCleaned, totalTestsReg, config);
} | javascript | function mapSuites(suite, totalTestsReg, config) {
const suites = _.compact(_.map(suite.suites, subSuite => (
mapSuites(subSuite, totalTestsReg, config)
)));
const toBeCleaned = Object.assign({}, suite, { suites });
return cleanSuite(toBeCleaned, totalTestsReg, config);
} | [
"function",
"mapSuites",
"(",
"suite",
",",
"totalTestsReg",
",",
"config",
")",
"{",
"const",
"suites",
"=",
"_",
".",
"compact",
"(",
"_",
".",
"map",
"(",
"suite",
".",
"suites",
",",
"subSuite",
"=>",
"(",
"mapSuites",
"(",
"subSuite",
",",
"totalT... | Map over a suite, returning a cleaned suite object
and recursively cleaning any nested suites.
@param {Object} suite Suite to map over
@param {Object} totalTestsReg Cumulative count of total tests registered
@param {Integer} totalTestsReg.total
@param {Object} config Reporter configuration | [
"Map",
"over",
"a",
"suite",
"returning",
"a",
"cleaned",
"suite",
"object",
"and",
"recursively",
"cleaning",
"any",
"nested",
"suites",
"."
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/utils.js#L275-L281 | train |
adamgruber/mochawesome | src/config.js | _getOption | function _getOption(optToGet, options, isBool, defaultValue) {
const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`;
if (options && typeof options[optToGet] !== 'undefined') {
return (isBool && typeof options[optToGet] === 'string')
? options[optToGet] === 'true'
: options[optToGet];
}
if (typ... | javascript | function _getOption(optToGet, options, isBool, defaultValue) {
const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`;
if (options && typeof options[optToGet] !== 'undefined') {
return (isBool && typeof options[optToGet] === 'string')
? options[optToGet] === 'true'
: options[optToGet];
}
if (typ... | [
"function",
"_getOption",
"(",
"optToGet",
",",
"options",
",",
"isBool",
",",
"defaultValue",
")",
"{",
"const",
"envVar",
"=",
"`",
"${",
"optToGet",
".",
"toUpperCase",
"(",
")",
"}",
"`",
";",
"if",
"(",
"options",
"&&",
"typeof",
"options",
"[",
"... | Retrieve the value of a user supplied option.
Falls back to `defaultValue`
Order of precedence
1. User-supplied option
2. Environment variable
3. Default value
@param {string} optToGet Option name
@param {object} options User supplied options object
@param {boolean} isBool Treat option as Boolean
@param {string|boo... | [
"Retrieve",
"the",
"value",
"of",
"a",
"user",
"supplied",
"option",
".",
"Falls",
"back",
"to",
"defaultValue",
"Order",
"of",
"precedence",
"1",
".",
"User",
"-",
"supplied",
"option",
"2",
".",
"Environment",
"variable",
"3",
".",
"Default",
"value"
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/config.js#L16-L29 | train |
adamgruber/mochawesome | src/addContext.js | function (...args) {
// Check args to see if we should bother continuing
if ((args.length !== 2) || !isObject(args[0])) {
log(ERRORS.INVALID_ARGS, 'error');
return;
}
const ctx = args[1];
// Ensure that context meets the requirements
if (!_isValidContext(ctx)) {
log(ERRORS.INVALID_CONTEXT(ctx)... | javascript | function (...args) {
// Check args to see if we should bother continuing
if ((args.length !== 2) || !isObject(args[0])) {
log(ERRORS.INVALID_ARGS, 'error');
return;
}
const ctx = args[1];
// Ensure that context meets the requirements
if (!_isValidContext(ctx)) {
log(ERRORS.INVALID_CONTEXT(ctx)... | [
"function",
"(",
"...",
"args",
")",
"{",
"// Check args to see if we should bother continuing",
"if",
"(",
"(",
"args",
".",
"length",
"!==",
"2",
")",
"||",
"!",
"isObject",
"(",
"args",
"[",
"0",
"]",
")",
")",
"{",
"log",
"(",
"ERRORS",
".",
"INVALID... | Add context to the test object so it can
be displayed in the mochawesome report
@param {Object} test object
@param {String|Object} context to add
If context is an object, it must have the shape:
{
title: string that is used as context title in the report
value: the context that is to be added
}
Usage:
it('should tes... | [
"Add",
"context",
"to",
"the",
"test",
"object",
"so",
"it",
"can",
"be",
"displayed",
"in",
"the",
"mochawesome",
"report"
] | ce0cafe0994f4226b1a63b7c14bad2c585193c70 | https://github.com/adamgruber/mochawesome/blob/ce0cafe0994f4226b1a63b7c14bad2c585193c70/src/addContext.js#L70-L115 | train | |
rethinkdb/horizon | client/src/index.js | sendRequest | function sendRequest(type, options) {
// Both remove and removeAll use the type 'remove' in the protocol
const normalizedType = type === 'removeAll' ? 'remove' : type
return socket
.hzRequest({ type: normalizedType, options }) // send the raw request
.takeWhile(resp => resp.state !== 'complete')... | javascript | function sendRequest(type, options) {
// Both remove and removeAll use the type 'remove' in the protocol
const normalizedType = type === 'removeAll' ? 'remove' : type
return socket
.hzRequest({ type: normalizedType, options }) // send the raw request
.takeWhile(resp => resp.state !== 'complete')... | [
"function",
"sendRequest",
"(",
"type",
",",
"options",
")",
"{",
"// Both remove and removeAll use the type 'remove' in the protocol",
"const",
"normalizedType",
"=",
"type",
"===",
"'removeAll'",
"?",
"'remove'",
":",
"type",
"return",
"socket",
".",
"hzRequest",
"(",... | Sends a horizon protocol request to the server, and pulls the data portion of the response out. | [
"Sends",
"a",
"horizon",
"protocol",
"request",
"to",
"the",
"server",
"and",
"pulls",
"the",
"data",
"portion",
"of",
"the",
"response",
"out",
"."
] | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/client/src/index.js#L119-L125 | train |
rethinkdb/horizon | client/src/model.js | isPrimitive | function isPrimitive(value) {
if (value === null) {
return true
}
if (value === undefined) {
return false
}
if (typeof value === 'function') {
return false
}
if ([ 'boolean', 'number', 'string' ].indexOf(typeof value) !== -1) {
return true
}
if (value instanceof Date || value instanceo... | javascript | function isPrimitive(value) {
if (value === null) {
return true
}
if (value === undefined) {
return false
}
if (typeof value === 'function') {
return false
}
if ([ 'boolean', 'number', 'string' ].indexOf(typeof value) !== -1) {
return true
}
if (value instanceof Date || value instanceo... | [
"function",
"isPrimitive",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"value",
"===",
"undefined",
")",
"{",
"return",
"false",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
")",
"... | Whether an object is primitive. We consider functions non-primitives, lump Dates and ArrayBuffers into primitives. | [
"Whether",
"an",
"object",
"is",
"primitive",
".",
"We",
"consider",
"functions",
"non",
"-",
"primitives",
"lump",
"Dates",
"and",
"ArrayBuffers",
"into",
"primitives",
"."
] | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/client/src/model.js#L35-L52 | train |
rethinkdb/horizon | examples/cyclejs-chat-app/dist/app.js | model | function model(inputValue$, messages$) {
return Rx.Observable.combineLatest(
inputValue$.startWith(null),
messages$.startWith([]),
(inputValue, messages) => ({ messages, inputValue })
)
} | javascript | function model(inputValue$, messages$) {
return Rx.Observable.combineLatest(
inputValue$.startWith(null),
messages$.startWith([]),
(inputValue, messages) => ({ messages, inputValue })
)
} | [
"function",
"model",
"(",
"inputValue$",
",",
"messages$",
")",
"{",
"return",
"Rx",
".",
"Observable",
".",
"combineLatest",
"(",
"inputValue$",
".",
"startWith",
"(",
"null",
")",
",",
"messages$",
".",
"startWith",
"(",
"[",
"]",
")",
",",
"(",
"input... | Model takes our action streams and turns them into the stream of app states | [
"Model",
"takes",
"our",
"action",
"streams",
"and",
"turns",
"them",
"into",
"the",
"stream",
"of",
"app",
"states"
] | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L58-L64 | train |
rethinkdb/horizon | examples/cyclejs-chat-app/dist/app.js | view | function view(state$) {
// Displayed for each chat message.
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
... | javascript | function view(state$) {
// Displayed for each chat message.
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
... | [
"function",
"view",
"(",
"state$",
")",
"{",
"// Displayed for each chat message.",
"function",
"chatMessage",
"(",
"msg",
")",
"{",
"return",
"li",
"(",
"'.message'",
",",
"{",
"key",
":",
"msg",
".",
"id",
"}",
",",
"[",
"img",
"(",
"{",
"height",
":",... | View takes the state and create a stream of virtual-dom trees for the app. | [
"View",
"takes",
"the",
"state",
"and",
"create",
"a",
"stream",
"of",
"virtual",
"-",
"dom",
"trees",
"for",
"the",
"app",
"."
] | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L68-L89 | train |
rethinkdb/horizon | examples/cyclejs-chat-app/dist/app.js | chatMessage | function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
} | javascript | function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
} | [
"function",
"chatMessage",
"(",
"msg",
")",
"{",
"return",
"li",
"(",
"'.message'",
",",
"{",
"key",
":",
"msg",
".",
"id",
"}",
",",
"[",
"img",
"(",
"{",
"height",
":",
"'50'",
",",
"width",
":",
"'50'",
",",
"src",
":",
"`",
"${",
"msg",
"."... | Displayed for each chat message. | [
"Displayed",
"for",
"each",
"chat",
"message",
"."
] | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L70-L78 | train |
rethinkdb/horizon | examples/cyclejs-chat-app/dist/app.js | main | function main(sources) {
const intents = intent(sources)
const state$ = model(intents.inputValue$, intents.messages$)
return {
// Send the virtual tree to the real DOM
DOM: view(state$),
// Send our messages to the horizon server
horizon: intents.writeOps$$,
}
} | javascript | function main(sources) {
const intents = intent(sources)
const state$ = model(intents.inputValue$, intents.messages$)
return {
// Send the virtual tree to the real DOM
DOM: view(state$),
// Send our messages to the horizon server
horizon: intents.writeOps$$,
}
} | [
"function",
"main",
"(",
"sources",
")",
"{",
"const",
"intents",
"=",
"intent",
"(",
"sources",
")",
"const",
"state$",
"=",
"model",
"(",
"intents",
".",
"inputValue$",
",",
"intents",
".",
"messages$",
")",
"return",
"{",
"// Send the virtual tree to the re... | In main we just wire everything together | [
"In",
"main",
"we",
"just",
"wire",
"everything",
"together"
] | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/examples/cyclejs-chat-app/dist/app.js#L92-L101 | train |
rethinkdb/horizon | client/src/ast.js | makePresentable | function makePresentable(observable, query) {
// Whether the entire data structure is in each change
const pointQuery = Boolean(query.find)
if (pointQuery) {
let hasEmitted = false
const seedVal = null
// Simplest case: just pass through new_val
return observable
.filter(change => !hasEmitt... | javascript | function makePresentable(observable, query) {
// Whether the entire data structure is in each change
const pointQuery = Boolean(query.find)
if (pointQuery) {
let hasEmitted = false
const seedVal = null
// Simplest case: just pass through new_val
return observable
.filter(change => !hasEmitt... | [
"function",
"makePresentable",
"(",
"observable",
",",
"query",
")",
"{",
"// Whether the entire data structure is in each change",
"const",
"pointQuery",
"=",
"Boolean",
"(",
"query",
".",
"find",
")",
"if",
"(",
"pointQuery",
")",
"{",
"let",
"hasEmitted",
"=",
... | Turn a raw observable of server responses into user-presentable events `observable` is the base observable with full responses coming from the HorizonSocket `query` is the value of `options` in the request | [
"Turn",
"a",
"raw",
"observable",
"of",
"server",
"responses",
"into",
"user",
"-",
"presentable",
"events",
"observable",
"is",
"the",
"base",
"observable",
"with",
"full",
"responses",
"coming",
"from",
"the",
"HorizonSocket",
"query",
"is",
"the",
"value",
... | 6e16c613c8789e484bfc9309d9553a625a09608e | https://github.com/rethinkdb/horizon/blob/6e16c613c8789e484bfc9309d9553a625a09608e/client/src/ast.js#L140-L183 | train |
jabbany/CommentCoreLibrary | demo/scripting/sandbox.js | function(e){
if(e.keyCode === 9){
e.preventDefault();
var cursor = this.selectionStart;
var nv = this.value.substring(0,cursor),
bv = this.value.substring(cursor, this.value.length);;
this.value = nv + "\t" + bv;
this.setSelectionRange(cursor + 1, cursor + 1);
}
} | javascript | function(e){
if(e.keyCode === 9){
e.preventDefault();
var cursor = this.selectionStart;
var nv = this.value.substring(0,cursor),
bv = this.value.substring(cursor, this.value.length);;
this.value = nv + "\t" + bv;
this.setSelectionRange(cursor + 1, cursor + 1);
}
} | [
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"keyCode",
"===",
"9",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"cursor",
"=",
"this",
".",
"selectionStart",
";",
"var",
"nv",
"=",
"this",
".",
"value",
".",
"substring",
"... | Hook tab keys | [
"Hook",
"tab",
"keys"
] | 5486e28e187cd4e490f129ec0cd9d07e6cf1b246 | https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/demo/scripting/sandbox.js#L80-L89 | train | |
jabbany/CommentCoreLibrary | dist/CommentCoreLibrary.js | _match | function _match (rule, cmtData) {
var path = rule.subject.split('.');
var extracted = cmtData;
while (path.length > 0) {
var item = path.shift();
if (item === '') {
continue;
}
if (extracted.hasOwnProperty(item)) {
e... | javascript | function _match (rule, cmtData) {
var path = rule.subject.split('.');
var extracted = cmtData;
while (path.length > 0) {
var item = path.shift();
if (item === '') {
continue;
}
if (extracted.hasOwnProperty(item)) {
e... | [
"function",
"_match",
"(",
"rule",
",",
"cmtData",
")",
"{",
"var",
"path",
"=",
"rule",
".",
"subject",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"extracted",
"=",
"cmtData",
";",
"while",
"(",
"path",
".",
"length",
">",
"0",
")",
"{",
"var",
... | Matches a rule against an input that could be the full or a subset of
the comment data.
@param rule - rule object to match
@param cmtData - full or portion of comment data
@return boolean indicator of match | [
"Matches",
"a",
"rule",
"against",
"an",
"input",
"that",
"could",
"be",
"the",
"full",
"or",
"a",
"subset",
"of",
"the",
"comment",
"data",
"."
] | 5486e28e187cd4e490f129ec0cd9d07e6cf1b246 | https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1266-L1323 | train |
jabbany/CommentCoreLibrary | dist/CommentCoreLibrary.js | CommentFilter | function CommentFilter() {
this.rules = [];
this.modifiers = [];
this.allowUnknownTypes = true;
this.allowTypes = {
'1': true,
'2': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
... | javascript | function CommentFilter() {
this.rules = [];
this.modifiers = [];
this.allowUnknownTypes = true;
this.allowTypes = {
'1': true,
'2': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
... | [
"function",
"CommentFilter",
"(",
")",
"{",
"this",
".",
"rules",
"=",
"[",
"]",
";",
"this",
".",
"modifiers",
"=",
"[",
"]",
";",
"this",
".",
"allowUnknownTypes",
"=",
"true",
";",
"this",
".",
"allowTypes",
"=",
"{",
"'1'",
":",
"true",
",",
"'... | Constructor for CommentFilter
@constructor | [
"Constructor",
"for",
"CommentFilter"
] | 5486e28e187cd4e490f129ec0cd9d07e6cf1b246 | https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1329-L1343 | train |
jabbany/CommentCoreLibrary | dist/CommentCoreLibrary.js | function (text) {
if (text.charAt(0) === '[') {
switch (text.charAt(text.length - 1)) {
case ']':
return text;
case '"':
return text + ']';
case ',':
return text.substring(0, text.length - 1) ... | javascript | function (text) {
if (text.charAt(0) === '[') {
switch (text.charAt(text.length - 1)) {
case ']':
return text;
case '"':
return text + ']';
case ',':
return text.substring(0, text.length - 1) ... | [
"function",
"(",
"text",
")",
"{",
"if",
"(",
"text",
".",
"charAt",
"(",
"0",
")",
"===",
"'['",
")",
"{",
"switch",
"(",
"text",
".",
"charAt",
"(",
"text",
".",
"length",
"-",
"1",
")",
")",
"{",
"case",
"']'",
":",
"return",
"text",
";",
... | Fix Mode7 comments when they are bad | [
"Fix",
"Mode7",
"comments",
"when",
"they",
"are",
"bad"
] | 5486e28e187cd4e490f129ec0cd9d07e6cf1b246 | https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1863-L1878 | train | |
jabbany/CommentCoreLibrary | dist/CommentCoreLibrary.js | function (text) {
text = text.replace(new RegExp('</([^d])','g'), '</disabled $1');
text = text.replace(new RegExp('</(\S{2,})','g'), '</disabled $1');
text = text.replace(new RegExp('<([^d/]\W*?)','g'), '<disabled $1');
text = text.replace(new RegExp('<([^/ ]{2,}\W*?)','g'), '<disabled ... | javascript | function (text) {
text = text.replace(new RegExp('</([^d])','g'), '</disabled $1');
text = text.replace(new RegExp('</(\S{2,})','g'), '</disabled $1');
text = text.replace(new RegExp('<([^d/]\W*?)','g'), '<disabled $1');
text = text.replace(new RegExp('<([^/ ]{2,}\W*?)','g'), '<disabled ... | [
"function",
"(",
"text",
")",
"{",
"text",
"=",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'</([^d])'",
",",
"'g'",
")",
",",
"'</disabled $1'",
")",
";",
"text",
"=",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'</(\\S{2,})'",
",",
... | Try to escape unsafe HTML code. DO NOT trust that this handles all cases Please do not allow insecure DOM parsing unless you can trust your input source. | [
"Try",
"to",
"escape",
"unsafe",
"HTML",
"code",
".",
"DO",
"NOT",
"trust",
"that",
"this",
"handles",
"all",
"cases",
"Please",
"do",
"not",
"allow",
"insecure",
"DOM",
"parsing",
"unless",
"you",
"can",
"trust",
"your",
"input",
"source",
"."
] | 5486e28e187cd4e490f129ec0cd9d07e6cf1b246 | https://github.com/jabbany/CommentCoreLibrary/blob/5486e28e187cd4e490f129ec0cd9d07e6cf1b246/dist/CommentCoreLibrary.js#L1882-L1888 | train | |
puleos/object-hash | index.js | isNativeFunction | function isNativeFunction(f) {
if ((typeof f) !== 'function') {
return false;
}
var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
return exp.exec(Function.prototype.toString.call(f)) != null;
} | javascript | function isNativeFunction(f) {
if ((typeof f) !== 'function') {
return false;
}
var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
return exp.exec(Function.prototype.toString.call(f)) != null;
} | [
"function",
"isNativeFunction",
"(",
"f",
")",
"{",
"if",
"(",
"(",
"typeof",
"f",
")",
"!==",
"'function'",
")",
"{",
"return",
"false",
";",
"}",
"var",
"exp",
"=",
"/",
"^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$",
"/",
"i",
";",
"retur... | Check if the given function is a native function | [
"Check",
"if",
"the",
"given",
"function",
"is",
"a",
"native",
"function"
] | c70080cc88b4b54abffe723659bde530474f1d17 | https://github.com/puleos/object-hash/blob/c70080cc88b4b54abffe723659bde530474f1d17/index.js#L105-L111 | train |
puleos/object-hash | index.js | PassThrough | function PassThrough() {
return {
buf: '',
write: function(b) {
this.buf += b;
},
end: function(b) {
this.buf += b;
},
read: function() {
return this.buf;
}
};
} | javascript | function PassThrough() {
return {
buf: '',
write: function(b) {
this.buf += b;
},
end: function(b) {
this.buf += b;
},
read: function() {
return this.buf;
}
};
} | [
"function",
"PassThrough",
"(",
")",
"{",
"return",
"{",
"buf",
":",
"''",
",",
"write",
":",
"function",
"(",
"b",
")",
"{",
"this",
".",
"buf",
"+=",
"b",
";",
"}",
",",
"end",
":",
"function",
"(",
"b",
")",
"{",
"this",
".",
"buf",
"+=",
... | Mini-implementation of stream.PassThrough We are far from having need for the full implementation, and we can make assumptions like "many writes, then only one final read" and we can ignore encoding specifics | [
"Mini",
"-",
"implementation",
"of",
"stream",
".",
"PassThrough",
"We",
"are",
"far",
"from",
"having",
"need",
"for",
"the",
"full",
"implementation",
"and",
"we",
"can",
"make",
"assumptions",
"like",
"many",
"writes",
"then",
"only",
"one",
"final",
"rea... | c70080cc88b4b54abffe723659bde530474f1d17 | https://github.com/puleos/object-hash/blob/c70080cc88b4b54abffe723659bde530474f1d17/index.js#L425-L441 | train |
schteppe/poly-decomp.js | src/index.js | lineInt | function lineInt(l1,l2,precision){
precision = precision || 0;
var i = [0,0]; // point
var a1, b1, c1, a2, b2, c2, det; // scalars
a1 = l1[1][1] - l1[0][1];
b1 = l1[0][0] - l1[1][0];
c1 = a1 * l1[0][0] + b1 * l1[0][1];
a2 = l2[1][1] - l2[0][1];
b2 = l2[0][0] - l2[1][0];
c2 = a2 * l2[... | javascript | function lineInt(l1,l2,precision){
precision = precision || 0;
var i = [0,0]; // point
var a1, b1, c1, a2, b2, c2, det; // scalars
a1 = l1[1][1] - l1[0][1];
b1 = l1[0][0] - l1[1][0];
c1 = a1 * l1[0][0] + b1 * l1[0][1];
a2 = l2[1][1] - l2[0][1];
b2 = l2[0][0] - l2[1][0];
c2 = a2 * l2[... | [
"function",
"lineInt",
"(",
"l1",
",",
"l2",
",",
"precision",
")",
"{",
"precision",
"=",
"precision",
"||",
"0",
";",
"var",
"i",
"=",
"[",
"0",
",",
"0",
"]",
";",
"// point",
"var",
"a1",
",",
"b1",
",",
"c1",
",",
"a2",
",",
"b2",
",",
"... | Compute the intersection between two lines.
@static
@method lineInt
@param {Array} l1 Line vector 1
@param {Array} l2 Line vector 2
@param {Number} precision Precision to use when checking if the lines are parallel
@return {Array} The intersection point. | [
"Compute",
"the",
"intersection",
"between",
"two",
"lines",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L19-L35 | train |
schteppe/poly-decomp.js | src/index.js | lineSegmentsIntersect | function lineSegmentsIntersect(p1, p2, q1, q2){
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var da = q2[0] - q1[0];
var db = q2[1] - q1[1];
// segments are parallel
if((da*dy - db*dx) === 0){
return false;
}
var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx);
var t = (da * (p1[... | javascript | function lineSegmentsIntersect(p1, p2, q1, q2){
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var da = q2[0] - q1[0];
var db = q2[1] - q1[1];
// segments are parallel
if((da*dy - db*dx) === 0){
return false;
}
var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx);
var t = (da * (p1[... | [
"function",
"lineSegmentsIntersect",
"(",
"p1",
",",
"p2",
",",
"q1",
",",
"q2",
")",
"{",
"var",
"dx",
"=",
"p2",
"[",
"0",
"]",
"-",
"p1",
"[",
"0",
"]",
";",
"var",
"dy",
"=",
"p2",
"[",
"1",
"]",
"-",
"p1",
"[",
"1",
"]",
";",
"var",
... | Checks if two line segments intersects.
@method segmentsIntersect
@param {Array} p1 The start vertex of the first line segment.
@param {Array} p2 The end vertex of the first line segment.
@param {Array} q1 The start vertex of the second line segment.
@param {Array} q2 The end vertex of the second line segment.
@return ... | [
"Checks",
"if",
"two",
"line",
"segments",
"intersects",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L46-L61 | train |
schteppe/poly-decomp.js | src/index.js | triangleArea | function triangleArea(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
} | javascript | function triangleArea(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
} | [
"function",
"triangleArea",
"(",
"a",
",",
"b",
",",
"c",
")",
"{",
"return",
"(",
"(",
"(",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
")",
"*",
"(",
"c",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
")",
")",
"-",
"(",
"(",
"c",
"[",
... | Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order.
@static
@method area
@param {Array} a
@param {Array} b
@param {Array} c
@return {Number} | [
"Get",
"the",
"area",
"of",
"a",
"triangle",
"spanned",
"by",
"the",
"three",
"given",
"points",
".",
"Note",
"that",
"the",
"area",
"will",
"be",
"negative",
"if",
"the",
"points",
"are",
"not",
"given",
"in",
"counter",
"-",
"clockwise",
"order",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L72-L74 | train |
schteppe/poly-decomp.js | src/index.js | collinear | function collinear(a,b,c,thresholdAngle) {
if(!thresholdAngle){
return triangleArea(a, b, c) === 0;
} else {
var ab = tmpPoint1,
bc = tmpPoint2;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
bc[0] = c[0]-b[0];
bc[1] = c[1]-b[1];
var dot = ab[0]*bc[0]... | javascript | function collinear(a,b,c,thresholdAngle) {
if(!thresholdAngle){
return triangleArea(a, b, c) === 0;
} else {
var ab = tmpPoint1,
bc = tmpPoint2;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
bc[0] = c[0]-b[0];
bc[1] = c[1]-b[1];
var dot = ab[0]*bc[0]... | [
"function",
"collinear",
"(",
"a",
",",
"b",
",",
"c",
",",
"thresholdAngle",
")",
"{",
"if",
"(",
"!",
"thresholdAngle",
")",
"{",
"return",
"triangleArea",
"(",
"a",
",",
"b",
",",
"c",
")",
"===",
"0",
";",
"}",
"else",
"{",
"var",
"ab",
"=",
... | Check if three points are collinear
@method collinear
@param {Array} a
@param {Array} b
@param {Array} c
@param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision.... | [
"Check",
"if",
"three",
"points",
"are",
"collinear"
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L104-L122 | train |
schteppe/poly-decomp.js | src/index.js | polygonAt | function polygonAt(polygon, i){
var s = polygon.length;
return polygon[i < 0 ? i % s + s : i % s];
} | javascript | function polygonAt(polygon, i){
var s = polygon.length;
return polygon[i < 0 ? i % s + s : i % s];
} | [
"function",
"polygonAt",
"(",
"polygon",
",",
"i",
")",
"{",
"var",
"s",
"=",
"polygon",
".",
"length",
";",
"return",
"polygon",
"[",
"i",
"<",
"0",
"?",
"i",
"%",
"s",
"+",
"s",
":",
"i",
"%",
"s",
"]",
";",
"}"
] | Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle.
@method at
@param {Number} i
@return {Array} | [
"Get",
"a",
"vertex",
"at",
"position",
"i",
".",
"It",
"does",
"not",
"matter",
"if",
"i",
"is",
"out",
"of",
"bounds",
"this",
"function",
"will",
"just",
"cycle",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L136-L139 | train |
schteppe/poly-decomp.js | src/index.js | polygonAppend | function polygonAppend(polygon, poly, from, to){
for(var i=from; i<to; i++){
polygon.push(poly[i]);
}
} | javascript | function polygonAppend(polygon, poly, from, to){
for(var i=from; i<to; i++){
polygon.push(poly[i]);
}
} | [
"function",
"polygonAppend",
"(",
"polygon",
",",
"poly",
",",
"from",
",",
"to",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"from",
";",
"i",
"<",
"to",
";",
"i",
"++",
")",
"{",
"polygon",
".",
"push",
"(",
"poly",
"[",
"i",
"]",
")",
";",
"}",... | Append points "from" to "to"-1 from an other polygon "poly" onto this one.
@method append
@param {Polygon} poly The polygon to get points from.
@param {Number} from The vertex index in "poly".
@param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending.
@return {Array} | [
"Append",
"points",
"from",
"to",
"to",
"-",
"1",
"from",
"an",
"other",
"polygon",
"poly",
"onto",
"this",
"one",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L158-L162 | train |
schteppe/poly-decomp.js | src/index.js | polygonMakeCCW | function polygonMakeCCW(polygon){
var br = 0,
v = polygon;
// find bottom right point
for (var i = 1; i < polygon.length; ++i) {
if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) {
br = i;
}
}
// reverse poly if clockwise
if (!isLeft(po... | javascript | function polygonMakeCCW(polygon){
var br = 0,
v = polygon;
// find bottom right point
for (var i = 1; i < polygon.length; ++i) {
if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) {
br = i;
}
}
// reverse poly if clockwise
if (!isLeft(po... | [
"function",
"polygonMakeCCW",
"(",
"polygon",
")",
"{",
"var",
"br",
"=",
"0",
",",
"v",
"=",
"polygon",
";",
"// find bottom right point",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"polygon",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"... | Make sure that the polygon vertices are ordered counter-clockwise.
@method makeCCW | [
"Make",
"sure",
"that",
"the",
"polygon",
"vertices",
"are",
"ordered",
"counter",
"-",
"clockwise",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L168-L186 | train |
schteppe/poly-decomp.js | src/index.js | polygonReverse | function polygonReverse(polygon){
var tmp = [];
var N = polygon.length;
for(var i=0; i!==N; i++){
tmp.push(polygon.pop());
}
for(var i=0; i!==N; i++){
polygon[i] = tmp[i];
}
} | javascript | function polygonReverse(polygon){
var tmp = [];
var N = polygon.length;
for(var i=0; i!==N; i++){
tmp.push(polygon.pop());
}
for(var i=0; i!==N; i++){
polygon[i] = tmp[i];
}
} | [
"function",
"polygonReverse",
"(",
"polygon",
")",
"{",
"var",
"tmp",
"=",
"[",
"]",
";",
"var",
"N",
"=",
"polygon",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"!==",
"N",
";",
"i",
"++",
")",
"{",
"tmp",
".",
"push",
"(... | Reverse the vertices in the polygon
@method reverse | [
"Reverse",
"the",
"vertices",
"in",
"the",
"polygon"
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L192-L201 | train |
schteppe/poly-decomp.js | src/index.js | polygonIsReflex | function polygonIsReflex(polygon, i){
return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1));
} | javascript | function polygonIsReflex(polygon, i){
return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1));
} | [
"function",
"polygonIsReflex",
"(",
"polygon",
",",
"i",
")",
"{",
"return",
"isRight",
"(",
"polygonAt",
"(",
"polygon",
",",
"i",
"-",
"1",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"i",
")",
",",
"polygonAt",
"(",
"polygon",
",",
"i",
"+",
"1",
... | Check if a point in the polygon is a reflex point
@method isReflex
@param {Number} i
@return {Boolean} | [
"Check",
"if",
"a",
"point",
"in",
"the",
"polygon",
"is",
"a",
"reflex",
"point"
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L209-L211 | train |
schteppe/poly-decomp.js | src/index.js | polygonCopy | function polygonCopy(polygon, i,j,targetPoly){
var p = targetPoly || [];
polygonClear(p);
if (i < j) {
// Insert all vertices from i to j
for(var k=i; k<=j; k++){
p.push(polygon[k]);
}
} else {
// Insert vertices 0 to j
for(var k=0; k<=j; k++){
... | javascript | function polygonCopy(polygon, i,j,targetPoly){
var p = targetPoly || [];
polygonClear(p);
if (i < j) {
// Insert all vertices from i to j
for(var k=i; k<=j; k++){
p.push(polygon[k]);
}
} else {
// Insert vertices 0 to j
for(var k=0; k<=j; k++){
... | [
"function",
"polygonCopy",
"(",
"polygon",
",",
"i",
",",
"j",
",",
"targetPoly",
")",
"{",
"var",
"p",
"=",
"targetPoly",
"||",
"[",
"]",
";",
"polygonClear",
"(",
"p",
")",
";",
"if",
"(",
"i",
"<",
"j",
")",
"{",
"// Insert all vertices from i to j"... | Copy the polygon from vertex i to vertex j.
@method copy
@param {Number} i
@param {Number} j
@param {Polygon} [targetPoly] Optional target polygon to save in.
@return {Polygon} The resulting copy. | [
"Copy",
"the",
"polygon",
"from",
"vertex",
"i",
"to",
"vertex",
"j",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L278-L301 | train |
schteppe/poly-decomp.js | src/index.js | polygonDecomp | function polygonDecomp(polygon){
var edges = polygonGetCutEdges(polygon);
if(edges.length > 0){
return polygonSlice(polygon, edges);
} else {
return [polygon];
}
} | javascript | function polygonDecomp(polygon){
var edges = polygonGetCutEdges(polygon);
if(edges.length > 0){
return polygonSlice(polygon, edges);
} else {
return [polygon];
}
} | [
"function",
"polygonDecomp",
"(",
"polygon",
")",
"{",
"var",
"edges",
"=",
"polygonGetCutEdges",
"(",
"polygon",
")",
";",
"if",
"(",
"edges",
".",
"length",
">",
"0",
")",
"{",
"return",
"polygonSlice",
"(",
"polygon",
",",
"edges",
")",
";",
"}",
"e... | Decomposes the polygon into one or more convex sub-Polygons.
@method decomp
@return {Array} An array or Polygon objects. | [
"Decomposes",
"the",
"polygon",
"into",
"one",
"or",
"more",
"convex",
"sub",
"-",
"Polygons",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L342-L349 | train |
schteppe/poly-decomp.js | src/index.js | polygonIsSimple | function polygonIsSimple(polygon){
var path = polygon, i;
// Check
for(i=0; i<path.length-1; i++){
for(var j=0; j<i-1; j++){
if(lineSegmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
return false;
}
}
}
// Check the segment between t... | javascript | function polygonIsSimple(polygon){
var path = polygon, i;
// Check
for(i=0; i<path.length-1; i++){
for(var j=0; j<i-1; j++){
if(lineSegmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
return false;
}
}
}
// Check the segment between t... | [
"function",
"polygonIsSimple",
"(",
"polygon",
")",
"{",
"var",
"path",
"=",
"polygon",
",",
"i",
";",
"// Check",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"path",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",... | Checks that the line segments of this polygon do not intersect each other.
@method isSimple
@param {Array} path An array of vertices e.g. [[0,0],[0,1],...]
@return {Boolean}
@todo Should it check all segments with all others? | [
"Checks",
"that",
"the",
"line",
"segments",
"of",
"this",
"polygon",
"do",
"not",
"intersect",
"each",
"other",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L404-L423 | train |
schteppe/poly-decomp.js | src/index.js | polygonRemoveCollinearPoints | function polygonRemoveCollinearPoints(polygon, precision){
var num = 0;
for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){
if(collinear(polygonAt(polygon, i-1),polygonAt(polygon, i),polygonAt(polygon, i+1),precision)){
// Remove the middle point
polygon.splice(i%polygon.... | javascript | function polygonRemoveCollinearPoints(polygon, precision){
var num = 0;
for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){
if(collinear(polygonAt(polygon, i-1),polygonAt(polygon, i),polygonAt(polygon, i+1),precision)){
// Remove the middle point
polygon.splice(i%polygon.... | [
"function",
"polygonRemoveCollinearPoints",
"(",
"polygon",
",",
"precision",
")",
"{",
"var",
"num",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"polygon",
".",
"length",
"-",
"1",
";",
"polygon",
".",
"length",
">",
"3",
"&&",
"i",
">=",
"0",
";",
... | Remove collinear points in the polygon.
@method removeCollinearPoints
@param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision.
@return {Number} The number of points removed | [
"Remove",
"collinear",
"points",
"in",
"the",
"polygon",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L603-L613 | train |
schteppe/poly-decomp.js | src/index.js | polygonRemoveDuplicatePoints | function polygonRemoveDuplicatePoints(polygon, precision){
for(var i=polygon.length-1; i>=1; --i){
var pi = polygon[i];
for(var j=i-1; j>=0; --j){
if(points_eq(pi, polygon[j], precision)){
polygon.splice(i,1);
continue;
}
}
}
} | javascript | function polygonRemoveDuplicatePoints(polygon, precision){
for(var i=polygon.length-1; i>=1; --i){
var pi = polygon[i];
for(var j=i-1; j>=0; --j){
if(points_eq(pi, polygon[j], precision)){
polygon.splice(i,1);
continue;
}
}
}
} | [
"function",
"polygonRemoveDuplicatePoints",
"(",
"polygon",
",",
"precision",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"polygon",
".",
"length",
"-",
"1",
";",
"i",
">=",
"1",
";",
"--",
"i",
")",
"{",
"var",
"pi",
"=",
"polygon",
"[",
"i",
"]",
";",... | Remove duplicate points in the polygon.
@method removeDuplicatePoints
@param {Number} [precision] The threshold to use when determining whether two points are the same. Use zero for best precision. | [
"Remove",
"duplicate",
"points",
"in",
"the",
"polygon",
"."
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L620-L630 | train |
schteppe/poly-decomp.js | src/index.js | scalar_eq | function scalar_eq(a,b,precision){
precision = precision || 0;
return Math.abs(a-b) <= precision;
} | javascript | function scalar_eq(a,b,precision){
precision = precision || 0;
return Math.abs(a-b) <= precision;
} | [
"function",
"scalar_eq",
"(",
"a",
",",
"b",
",",
"precision",
")",
"{",
"precision",
"=",
"precision",
"||",
"0",
";",
"return",
"Math",
".",
"abs",
"(",
"a",
"-",
"b",
")",
"<=",
"precision",
";",
"}"
] | Check if two scalars are equal
@static
@method eq
@param {Number} a
@param {Number} b
@param {Number} [precision]
@return {Boolean} | [
"Check",
"if",
"two",
"scalars",
"are",
"equal"
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L641-L644 | train |
schteppe/poly-decomp.js | src/index.js | points_eq | function points_eq(a,b,precision){
return scalar_eq(a[0],b[0],precision) && scalar_eq(a[1],b[1],precision);
} | javascript | function points_eq(a,b,precision){
return scalar_eq(a[0],b[0],precision) && scalar_eq(a[1],b[1],precision);
} | [
"function",
"points_eq",
"(",
"a",
",",
"b",
",",
"precision",
")",
"{",
"return",
"scalar_eq",
"(",
"a",
"[",
"0",
"]",
",",
"b",
"[",
"0",
"]",
",",
"precision",
")",
"&&",
"scalar_eq",
"(",
"a",
"[",
"1",
"]",
",",
"b",
"[",
"1",
"]",
",",... | Check if two points are equal
@static
@method points_eq
@param {Array} a
@param {Array} b
@param {Number} [precision]
@return {Boolean} | [
"Check",
"if",
"two",
"points",
"are",
"equal"
] | 4eebc5b5780d8ffd8094615622b701e34a7835e8 | https://github.com/schteppe/poly-decomp.js/blob/4eebc5b5780d8ffd8094615622b701e34a7835e8/src/index.js#L655-L657 | train |
Raynos/mercury | examples/unidirectional/backbone/observ-backbone.js | serialize | function serialize(model) {
var data = model.toJSON();
Object.keys(data).forEach(function serializeRecur(key) {
var value = data[key];
// if any value can be serialized toJSON() then do it
if (value && value.toJSON) {
data[key] = data[key].toJSON();
}
});
retu... | javascript | function serialize(model) {
var data = model.toJSON();
Object.keys(data).forEach(function serializeRecur(key) {
var value = data[key];
// if any value can be serialized toJSON() then do it
if (value && value.toJSON) {
data[key] = data[key].toJSON();
}
});
retu... | [
"function",
"serialize",
"(",
"model",
")",
"{",
"var",
"data",
"=",
"model",
".",
"toJSON",
"(",
")",
";",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"forEach",
"(",
"function",
"serializeRecur",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"data",... | convert a Backbone model to JSON | [
"convert",
"a",
"Backbone",
"model",
"to",
"JSON"
] | 58fae95356efacb6b2a7f91b44ed5c0b46aab78c | https://github.com/Raynos/mercury/blob/58fae95356efacb6b2a7f91b44ed5c0b46aab78c/examples/unidirectional/backbone/observ-backbone.js#L30-L40 | train |
Raynos/mercury | examples/unidirectional/backbone/observ-backbone.js | listen | function listen(model, listener) {
model.on('change', listener);
model.values().forEach(function listenRecur(value) {
var isCollection = value && value._byId;
if (!isCollection) {
return;
}
// for each collection listen to it
// console.log('listenCollectio... | javascript | function listen(model, listener) {
model.on('change', listener);
model.values().forEach(function listenRecur(value) {
var isCollection = value && value._byId;
if (!isCollection) {
return;
}
// for each collection listen to it
// console.log('listenCollectio... | [
"function",
"listen",
"(",
"model",
",",
"listener",
")",
"{",
"model",
".",
"on",
"(",
"'change'",
",",
"listener",
")",
";",
"model",
".",
"values",
"(",
")",
".",
"forEach",
"(",
"function",
"listenRecur",
"(",
"value",
")",
"{",
"var",
"isCollectio... | listen to a Backbone model | [
"listen",
"to",
"a",
"Backbone",
"model"
] | 58fae95356efacb6b2a7f91b44ed5c0b46aab78c | https://github.com/Raynos/mercury/blob/58fae95356efacb6b2a7f91b44ed5c0b46aab78c/examples/unidirectional/backbone/observ-backbone.js#L43-L57 | train |
Raynos/mercury | examples/unidirectional/backbone/observ-backbone.js | listenCollection | function listenCollection(collection, listener) {
collection.forEach(function listenModel(model) {
listen(model, listener);
});
collection.on('add', function onAdd(model) {
listen(model, listener);
listener();
});
} | javascript | function listenCollection(collection, listener) {
collection.forEach(function listenModel(model) {
listen(model, listener);
});
collection.on('add', function onAdd(model) {
listen(model, listener);
listener();
});
} | [
"function",
"listenCollection",
"(",
"collection",
",",
"listener",
")",
"{",
"collection",
".",
"forEach",
"(",
"function",
"listenModel",
"(",
"model",
")",
"{",
"listen",
"(",
"model",
",",
"listener",
")",
";",
"}",
")",
";",
"collection",
".",
"on",
... | listen to a Backbone collection | [
"listen",
"to",
"a",
"Backbone",
"collection"
] | 58fae95356efacb6b2a7f91b44ed5c0b46aab78c | https://github.com/Raynos/mercury/blob/58fae95356efacb6b2a7f91b44ed5c0b46aab78c/examples/unidirectional/backbone/observ-backbone.js#L60-L69 | train |
reframejs/reframe | helpers/webpack-config-mod/index.js | parseBabelThing | function parseBabelThing(babelThing) {
assert_usage([String, Array].includes(babelThing.constructor));
let name;
let options;
if( babelThing.constructor === Array ) {
name = babelThing[0];
options = babelThing[1];
} else {
name = babelThing;
}
assert_usage(name.constr... | javascript | function parseBabelThing(babelThing) {
assert_usage([String, Array].includes(babelThing.constructor));
let name;
let options;
if( babelThing.constructor === Array ) {
name = babelThing[0];
options = babelThing[1];
} else {
name = babelThing;
}
assert_usage(name.constr... | [
"function",
"parseBabelThing",
"(",
"babelThing",
")",
"{",
"assert_usage",
"(",
"[",
"String",
",",
"Array",
"]",
".",
"includes",
"(",
"babelThing",
".",
"constructor",
")",
")",
";",
"let",
"name",
";",
"let",
"options",
";",
"if",
"(",
"babelThing",
... | Works for babel presets as well as for babel plugins | [
"Works",
"for",
"babel",
"presets",
"as",
"well",
"as",
"for",
"babel",
"plugins"
] | d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c | https://github.com/reframejs/reframe/blob/d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c/helpers/webpack-config-mod/index.js#L163-L179 | train |
reframejs/reframe | plugins/react/common.js | applyViewWrappers | function applyViewWrappers({reactElement, initialProps, viewWrappers=[]}) {
viewWrappers
.forEach(viewWrapper => {
reactElement = viewWrapper(reactElement, initialProps);
});
return reactElement;
} | javascript | function applyViewWrappers({reactElement, initialProps, viewWrappers=[]}) {
viewWrappers
.forEach(viewWrapper => {
reactElement = viewWrapper(reactElement, initialProps);
});
return reactElement;
} | [
"function",
"applyViewWrappers",
"(",
"{",
"reactElement",
",",
"initialProps",
",",
"viewWrappers",
"=",
"[",
"]",
"}",
")",
"{",
"viewWrappers",
".",
"forEach",
"(",
"viewWrapper",
"=>",
"{",
"reactElement",
"=",
"viewWrapper",
"(",
"reactElement",
",",
"ini... | Apply view wrappers. E.g. the `@reframe/react-router` plugin adds a view wrapper to add the provider-components `<BrowserRouter>` and `<StaticRouter>`. | [
"Apply",
"view",
"wrappers",
".",
"E",
".",
"g",
".",
"the"
] | d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c | https://github.com/reframejs/reframe/blob/d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c/plugins/react/common.js#L17-L23 | train |
reframejs/reframe | plugins/build/index.js | assemble_modifiers | function assemble_modifiers(modifier_name, configParts) {
const assert_usage = require('reassert/usage');
// `configParts` holds all globalConfig parts
// `config` holds a webpack config
let supra_modifier = ({config}) => config;
// We assemble all `configParts`'s config modifiers into one `supra_... | javascript | function assemble_modifiers(modifier_name, configParts) {
const assert_usage = require('reassert/usage');
// `configParts` holds all globalConfig parts
// `config` holds a webpack config
let supra_modifier = ({config}) => config;
// We assemble all `configParts`'s config modifiers into one `supra_... | [
"function",
"assemble_modifiers",
"(",
"modifier_name",
",",
"configParts",
")",
"{",
"const",
"assert_usage",
"=",
"require",
"(",
"'reassert/usage'",
")",
";",
"// `configParts` holds all globalConfig parts",
"// `config` holds a webpack config",
"let",
"supra_modifier",
"=... | We assemble several webpack config modifiers into one supra modifier | [
"We",
"assemble",
"several",
"webpack",
"config",
"modifiers",
"into",
"one",
"supra",
"modifier"
] | d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c | https://github.com/reframejs/reframe/blob/d89c9baa5b9d5fd4a17a1651a0cfd5a96ca42d8c/plugins/build/index.js#L41-L79 | train |
adobe-photoshop/generator-core | lib/logging.js | StreamFormatter | function StreamFormatter(loggerManager, options) {
if (!(this instanceof StreamFormatter)) {
return new StreamFormatter(loggerManager, options);
}
stream.Readable.call(this, options);
this._buffer = [];
this._pushable = false;
this._ended = false;
log... | javascript | function StreamFormatter(loggerManager, options) {
if (!(this instanceof StreamFormatter)) {
return new StreamFormatter(loggerManager, options);
}
stream.Readable.call(this, options);
this._buffer = [];
this._pushable = false;
this._ended = false;
log... | [
"function",
"StreamFormatter",
"(",
"loggerManager",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"StreamFormatter",
")",
")",
"{",
"return",
"new",
"StreamFormatter",
"(",
"loggerManager",
",",
"options",
")",
";",
"}",
"stream",
"."... | StreamFormatter objects are Readable streams. They output a string represntation
of the log events generated by the "logger" variable.
The "options" argument is passed directly to the stream.Readable constructor.
No configuration of the log format is supported at this time. | [
"StreamFormatter",
"objects",
"are",
"Readable",
"streams",
".",
"They",
"output",
"a",
"string",
"represntation",
"of",
"the",
"log",
"events",
"generated",
"by",
"the",
"logger",
"variable",
"."
] | 24a2c4e38aef79adb42869f200778ab52de4ef36 | https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/logging.js#L316-L327 | train |
adobe-photoshop/generator-core | lib/stdlog.js | logReadableStream | function logReadableStream(stream) {
var encoding = "utf8";
stream.setEncoding(encoding);
stream.on("data", function (chunk) {
writeToLog(chunk, encoding);
});
} | javascript | function logReadableStream(stream) {
var encoding = "utf8";
stream.setEncoding(encoding);
stream.on("data", function (chunk) {
writeToLog(chunk, encoding);
});
} | [
"function",
"logReadableStream",
"(",
"stream",
")",
"{",
"var",
"encoding",
"=",
"\"utf8\"",
";",
"stream",
".",
"setEncoding",
"(",
"encoding",
")",
";",
"stream",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"chunk",
")",
"{",
"writeToLog",
"(",
... | Listen for data on a readable stream, write to the log file
@param {stream.Readable} stream | [
"Listen",
"for",
"data",
"on",
"a",
"readable",
"stream",
"write",
"to",
"the",
"log",
"file"
] | 24a2c4e38aef79adb42869f200778ab52de4ef36 | https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/stdlog.js#L115-L123 | train |
adobe-photoshop/generator-core | lib/stdlog.js | logWriteableStream | function logWriteableStream(stream, colorFunction) {
var write = stream.write;
// The third parameter, callback, will be passed implicitely using arguments
stream.write = function (chunk, encoding) {
// Write to STDOUT right away
try {
write.apply... | javascript | function logWriteableStream(stream, colorFunction) {
var write = stream.write;
// The third parameter, callback, will be passed implicitely using arguments
stream.write = function (chunk, encoding) {
// Write to STDOUT right away
try {
write.apply... | [
"function",
"logWriteableStream",
"(",
"stream",
",",
"colorFunction",
")",
"{",
"var",
"write",
"=",
"stream",
".",
"write",
";",
"// The third parameter, callback, will be passed implicitely using arguments",
"stream",
".",
"write",
"=",
"function",
"(",
"chunk",
",",... | Tap a writable stream and write the data to the log file
@param {stream.Writable} stream
@param {function=} colorFunction optional function to apply color to the log message | [
"Tap",
"a",
"writable",
"stream",
"and",
"write",
"the",
"data",
"to",
"the",
"log",
"file"
] | 24a2c4e38aef79adb42869f200778ab52de4ef36 | https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/stdlog.js#L131-L143 | train |
adobe-photoshop/generator-core | lib/stdlog.js | getLogDirectoryElements | function getLogDirectoryElements(settings) {
var elements,
platform = process.platform;
if (settings.logRoot) {
elements = [settings.logRoot, settings.module];
} else if (platform === "darwin") {
elements = [process.env.HOME, "Library", "Logs", settings.vendo... | javascript | function getLogDirectoryElements(settings) {
var elements,
platform = process.platform;
if (settings.logRoot) {
elements = [settings.logRoot, settings.module];
} else if (platform === "darwin") {
elements = [process.env.HOME, "Library", "Logs", settings.vendo... | [
"function",
"getLogDirectoryElements",
"(",
"settings",
")",
"{",
"var",
"elements",
",",
"platform",
"=",
"process",
".",
"platform",
";",
"if",
"(",
"settings",
".",
"logRoot",
")",
"{",
"elements",
"=",
"[",
"settings",
".",
"logRoot",
",",
"settings",
... | Define the log directory as an array so we can easily create the individual subdirectories if necessary, without requiring an external library like mkdirp | [
"Define",
"the",
"log",
"directory",
"as",
"an",
"array",
"so",
"we",
"can",
"easily",
"create",
"the",
"individual",
"subdirectories",
"if",
"necessary",
"without",
"requiring",
"an",
"external",
"library",
"like",
"mkdirp"
] | 24a2c4e38aef79adb42869f200778ab52de4ef36 | https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/stdlog.js#L147-L162 | train |
adobe-photoshop/generator-core | lib/style.js | extractStyleInfo | function extractStyleInfo(psd/*, opts*/) {
var SON = {};
var layers = psd.layers;
_classnames = [];
_psd = psd;
SON.layers = [];
layers.forEach(function (layer) {
var s = extractLayerStyleInfo(layer);
if (s !== undefined) {
SON.laye... | javascript | function extractStyleInfo(psd/*, opts*/) {
var SON = {};
var layers = psd.layers;
_classnames = [];
_psd = psd;
SON.layers = [];
layers.forEach(function (layer) {
var s = extractLayerStyleInfo(layer);
if (s !== undefined) {
SON.laye... | [
"function",
"extractStyleInfo",
"(",
"psd",
"/*, opts*/",
")",
"{",
"var",
"SON",
"=",
"{",
"}",
";",
"var",
"layers",
"=",
"psd",
".",
"layers",
";",
"_classnames",
"=",
"[",
"]",
";",
"_psd",
"=",
"psd",
";",
"SON",
".",
"layers",
"=",
"[",
"]",
... | Return a SON document for the specified document info
@param {Object} psd document retrieved from Generator.getDocumentInfo()
@return {Object} The SON document for the specified Generator document
Note: This API should be considered private and may be changed/removed at any
time with only a bump to the "patch" versi... | [
"Return",
"a",
"SON",
"document",
"for",
"the",
"specified",
"document",
"info"
] | 24a2c4e38aef79adb42869f200778ab52de4ef36 | https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/style.js#L550-L564 | train |
adobe-photoshop/generator-core | lib/generator.js | function (pixmapWidth, pixmapHeight) {
// Find out if the mask extends beyond the visible pixels
var paddingWanted;
["top", "left", "right", "bottom"].forEach(function (key) {
if (paddedInputBounds[key] !== visibleInputBounds[key]) {
... | javascript | function (pixmapWidth, pixmapHeight) {
// Find out if the mask extends beyond the visible pixels
var paddingWanted;
["top", "left", "right", "bottom"].forEach(function (key) {
if (paddedInputBounds[key] !== visibleInputBounds[key]) {
... | [
"function",
"(",
"pixmapWidth",
",",
"pixmapHeight",
")",
"{",
"// Find out if the mask extends beyond the visible pixels",
"var",
"paddingWanted",
";",
"[",
"\"top\"",
",",
"\"left\"",
",",
"\"right\"",
",",
"\"bottom\"",
"]",
".",
"forEach",
"(",
"function",
"(",
... | The padding depends on the actual size of the returned image, therefore provide a function | [
"The",
"padding",
"depends",
"on",
"the",
"actual",
"size",
"of",
"the",
"returned",
"image",
"therefore",
"provide",
"a",
"function"
] | 24a2c4e38aef79adb42869f200778ab52de4ef36 | https://github.com/adobe-photoshop/generator-core/blob/24a2c4e38aef79adb42869f200778ab52de4ef36/lib/generator.js#L1504-L1539 | train | |
3rd-Eden/memcached | lib/memcached.js | Client | function Client (args, options) {
// Ensure Client instantiated with 'new'
if (!(this instanceof Client)) {
return new Client(args, options);
}
var servers = []
, weights = {}
, regular = 'localhost:11211'
, key;
// Parse down the connection arguments
switch (Object.prototype.toString.call... | javascript | function Client (args, options) {
// Ensure Client instantiated with 'new'
if (!(this instanceof Client)) {
return new Client(args, options);
}
var servers = []
, weights = {}
, regular = 'localhost:11211'
, key;
// Parse down the connection arguments
switch (Object.prototype.toString.call... | [
"function",
"Client",
"(",
"args",
",",
"options",
")",
"{",
"// Ensure Client instantiated with 'new'",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Client",
")",
")",
"{",
"return",
"new",
"Client",
"(",
"args",
",",
"options",
")",
";",
"}",
"var",
"serv... | Constructs a new memcached client
@constructor
@param {Mixed} args Array, string or object with servers
@param {Object} options options
@api public | [
"Constructs",
"a",
"new",
"memcached",
"client"
] | 5438a03ec44c703b5f60012c2208d9a0bc5bc733 | https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L31-L74 | train |
3rd-Eden/memcached | lib/memcached.js | stats | function stats(resultSet) {
var response = {};
if (resultSetIsEmpty(resultSet)) return response;
// add references to the retrieved server
response.server = this.serverAddress;
// Fill the object
resultSet.forEach(function each(statSet) {
if (statSet) response[statSet[0]] =... | javascript | function stats(resultSet) {
var response = {};
if (resultSetIsEmpty(resultSet)) return response;
// add references to the retrieved server
response.server = this.serverAddress;
// Fill the object
resultSet.forEach(function each(statSet) {
if (statSet) response[statSet[0]] =... | [
"function",
"stats",
"(",
"resultSet",
")",
"{",
"var",
"response",
"=",
"{",
"}",
";",
"if",
"(",
"resultSetIsEmpty",
"(",
"resultSet",
")",
")",
"return",
"response",
";",
"// add references to the retrieved server",
"response",
".",
"server",
"=",
"this",
"... | combines the stats array, in to an object | [
"combines",
"the",
"stats",
"array",
"in",
"to",
"an",
"object"
] | 5438a03ec44c703b5f60012c2208d9a0bc5bc733 | https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L588-L601 | train |
3rd-Eden/memcached | lib/memcached.js | handle | function handle(err, results) {
if (err) {
errors.push(err);
}
// add all responses to the array
(Array.isArray(results) ? results : [results]).forEach(function each(value) {
if (value && memcached.namespace.length) {
var ns_key = Object.keys(value)[0]
, ne... | javascript | function handle(err, results) {
if (err) {
errors.push(err);
}
// add all responses to the array
(Array.isArray(results) ? results : [results]).forEach(function each(value) {
if (value && memcached.namespace.length) {
var ns_key = Object.keys(value)[0]
, ne... | [
"function",
"handle",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"{",
"errors",
".",
"push",
"(",
"err",
")",
";",
"}",
"// add all responses to the array",
"(",
"Array",
".",
"isArray",
"(",
"results",
")",
"?",
"results",
":",
"[",
... | handle multiple responses and cache them untill we receive all. | [
"handle",
"multiple",
"responses",
"and",
"cache",
"them",
"untill",
"we",
"receive",
"all",
"."
] | 5438a03ec44c703b5f60012c2208d9a0bc5bc733 | https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L874-L895 | train |
3rd-Eden/memcached | lib/memcached.js | handle | function handle(err, results) {
if (err) {
errors = errors || [];
errors.push(err);
}
if (results) responses = responses.concat(results);
// multi calls should ALWAYS return an array!
if (!--calls) {
callback(errors && errors.length ? errors.pop() : undefined, re... | javascript | function handle(err, results) {
if (err) {
errors = errors || [];
errors.push(err);
}
if (results) responses = responses.concat(results);
// multi calls should ALWAYS return an array!
if (!--calls) {
callback(errors && errors.length ? errors.pop() : undefined, re... | [
"function",
"handle",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"{",
"errors",
"=",
"errors",
"||",
"[",
"]",
";",
"errors",
".",
"push",
"(",
"err",
")",
";",
"}",
"if",
"(",
"results",
")",
"responses",
"=",
"responses",
".",... | handle multiple servers | [
"handle",
"multiple",
"servers"
] | 5438a03ec44c703b5f60012c2208d9a0bc5bc733 | https://github.com/3rd-Eden/memcached/blob/5438a03ec44c703b5f60012c2208d9a0bc5bc733/lib/memcached.js#L1093-L1104 | train |
prescottprue/generator-react-firebase | examples/redux-firestore/src/utils/firebaseMessaging.js | updateUserProfileWithToken | function updateUserProfileWithToken(messagingToken) {
const currentUserUid =
firebase.auth().currentUser && firebase.auth().currentUser.uid
if (!currentUserUid) {
return Promise.resolve();
}
return firebase
.firestore()
.collection('users')
.doc(currentUserUid)
.update({
messaging:... | javascript | function updateUserProfileWithToken(messagingToken) {
const currentUserUid =
firebase.auth().currentUser && firebase.auth().currentUser.uid
if (!currentUserUid) {
return Promise.resolve();
}
return firebase
.firestore()
.collection('users')
.doc(currentUserUid)
.update({
messaging:... | [
"function",
"updateUserProfileWithToken",
"(",
"messagingToken",
")",
"{",
"const",
"currentUserUid",
"=",
"firebase",
".",
"auth",
"(",
")",
".",
"currentUser",
"&&",
"firebase",
".",
"auth",
"(",
")",
".",
"currentUser",
".",
"uid",
"if",
"(",
"!",
"curren... | Write FCM messagingToken to user profile
@param {String} messagingToken - Token to be written to user profile | [
"Write",
"FCM",
"messagingToken",
"to",
"user",
"profile"
] | 8f044b05da7a034018a6384b081df9d380ac22dd | https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/firebaseMessaging.js#L11-L27 | train |
prescottprue/generator-react-firebase | examples/redux-firestore/src/utils/firebaseMessaging.js | getMessagingToken | function getMessagingToken() {
return firebase
.messaging()
.getToken()
.catch(err => {
console.error('Unable to retrieve refreshed token ', err) // eslint-disable-line no-console
return Promise.reject(err)
})
} | javascript | function getMessagingToken() {
return firebase
.messaging()
.getToken()
.catch(err => {
console.error('Unable to retrieve refreshed token ', err) // eslint-disable-line no-console
return Promise.reject(err)
})
} | [
"function",
"getMessagingToken",
"(",
")",
"{",
"return",
"firebase",
".",
"messaging",
"(",
")",
".",
"getToken",
"(",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"console",
".",
"error",
"(",
"'Unable to retrieve refreshed token '",
",",
"err",
")",
"// esli... | Get messaging token from Firebase messaging | [
"Get",
"messaging",
"token",
"from",
"Firebase",
"messaging"
] | 8f044b05da7a034018a6384b081df9d380ac22dd | https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/firebaseMessaging.js#L32-L40 | train |
prescottprue/generator-react-firebase | examples/react-firebase-redux/src/utils/errorHandler.js | initStackdriverErrorReporter | function initStackdriverErrorReporter() {
if (typeof window.StackdriverErrorReporter === 'function') {
window.addEventListener('DOMContentLoaded', () => {
const errorHandler = new window.StackdriverErrorReporter()
errorHandler.start({
key: firebase.apiKey,
projectId: firebase.projectId... | javascript | function initStackdriverErrorReporter() {
if (typeof window.StackdriverErrorReporter === 'function') {
window.addEventListener('DOMContentLoaded', () => {
const errorHandler = new window.StackdriverErrorReporter()
errorHandler.start({
key: firebase.apiKey,
projectId: firebase.projectId... | [
"function",
"initStackdriverErrorReporter",
"(",
")",
"{",
"if",
"(",
"typeof",
"window",
".",
"StackdriverErrorReporter",
"===",
"'function'",
")",
"{",
"window",
".",
"addEventListener",
"(",
"'DOMContentLoaded'",
",",
"(",
")",
"=>",
"{",
"const",
"errorHandler... | Initialize Stackdriver Error Reporter only if api key exists | [
"Initialize",
"Stackdriver",
"Error",
"Reporter",
"only",
"if",
"api",
"key",
"exists"
] | 8f044b05da7a034018a6384b081df9d380ac22dd | https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/react-firebase-redux/src/utils/errorHandler.js#L9-L22 | train |
prescottprue/generator-react-firebase | examples/redux-firestore/src/utils/analytics.js | initGA | function initGA() {
if (analyticsTrackingId) {
ReactGA.initialize(analyticsTrackingId)
ReactGA.set({
appName: environment || 'Production',
appVersion: version
})
}
} | javascript | function initGA() {
if (analyticsTrackingId) {
ReactGA.initialize(analyticsTrackingId)
ReactGA.set({
appName: environment || 'Production',
appVersion: version
})
}
} | [
"function",
"initGA",
"(",
")",
"{",
"if",
"(",
"analyticsTrackingId",
")",
"{",
"ReactGA",
".",
"initialize",
"(",
"analyticsTrackingId",
")",
"ReactGA",
".",
"set",
"(",
"{",
"appName",
":",
"environment",
"||",
"'Production'",
",",
"appVersion",
":",
"ver... | Initialize Google Analytics if analytics id exists and environment is
production | [
"Initialize",
"Google",
"Analytics",
"if",
"analytics",
"id",
"exists",
"and",
"environment",
"is",
"production"
] | 8f044b05da7a034018a6384b081df9d380ac22dd | https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/analytics.js#L9-L17 | train |
prescottprue/generator-react-firebase | examples/redux-firestore/src/utils/analytics.js | setGAUser | function setGAUser(auth) {
if (auth && auth.uid) {
ReactGA.set({ userId: auth.uid })
}
} | javascript | function setGAUser(auth) {
if (auth && auth.uid) {
ReactGA.set({ userId: auth.uid })
}
} | [
"function",
"setGAUser",
"(",
"auth",
")",
"{",
"if",
"(",
"auth",
"&&",
"auth",
".",
"uid",
")",
"{",
"ReactGA",
".",
"set",
"(",
"{",
"userId",
":",
"auth",
".",
"uid",
"}",
")",
"}",
"}"
] | Set user auth data within Google Analytics
@param {Object} auth - Authentication data
@param {String} auth.uid - User's id | [
"Set",
"user",
"auth",
"data",
"within",
"Google",
"Analytics"
] | 8f044b05da7a034018a6384b081df9d380ac22dd | https://github.com/prescottprue/generator-react-firebase/blob/8f044b05da7a034018a6384b081df9d380ac22dd/examples/redux-firestore/src/utils/analytics.js#L36-L40 | train |
ai/audio-recorder-polyfill | index.js | MediaRecorder | function MediaRecorder (stream) {
/**
* The `MediaStream` passed into the constructor.
* @type {MediaStream}
*/
this.stream = stream
/**
* The current state of recording process.
* @type {"inactive"|"recording"|"paused"}
*/
this.state = 'inactive'
this.em = document.createDocumentFragment(... | javascript | function MediaRecorder (stream) {
/**
* The `MediaStream` passed into the constructor.
* @type {MediaStream}
*/
this.stream = stream
/**
* The current state of recording process.
* @type {"inactive"|"recording"|"paused"}
*/
this.state = 'inactive'
this.em = document.createDocumentFragment(... | [
"function",
"MediaRecorder",
"(",
"stream",
")",
"{",
"/**\n * The `MediaStream` passed into the constructor.\n * @type {MediaStream}\n */",
"this",
".",
"stream",
"=",
"stream",
"/**\n * The current state of recording process.\n * @type {\"inactive\"|\"recording\"|\"paused\"}\n ... | Audio Recorder with MediaRecorder API.
@param {MediaStream} stream The audio stream to record.
@example
navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
var recorder = new MediaRecorder(stream)
})
@class | [
"Audio",
"Recorder",
"with",
"MediaRecorder",
"API",
"."
] | 9025a1d0003b0ade09de42a7ea682bf20b5c0224 | https://github.com/ai/audio-recorder-polyfill/blob/9025a1d0003b0ade09de42a7ea682bf20b5c0224/index.js#L32-L57 | train |
ai/audio-recorder-polyfill | index.js | start | function start (timeslice) {
if (this.state !== 'inactive') {
return this.em.dispatchEvent(error('start'))
}
this.state = 'recording'
if (!context) {
context = new AudioContext()
}
this.clone = this.stream.clone()
var input = context.createMediaStreamSource(this.clone)
if ... | javascript | function start (timeslice) {
if (this.state !== 'inactive') {
return this.em.dispatchEvent(error('start'))
}
this.state = 'recording'
if (!context) {
context = new AudioContext()
}
this.clone = this.stream.clone()
var input = context.createMediaStreamSource(this.clone)
if ... | [
"function",
"start",
"(",
"timeslice",
")",
"{",
"if",
"(",
"this",
".",
"state",
"!==",
"'inactive'",
")",
"{",
"return",
"this",
".",
"em",
".",
"dispatchEvent",
"(",
"error",
"(",
"'start'",
")",
")",
"}",
"this",
".",
"state",
"=",
"'recording'",
... | Begins recording media.
@param {number} [timeslice] The milliseconds to record into each `Blob`.
If this parameter isn’t included, single `Blob`
will be recorded.
@return {undefined}
@example
recordButton.addEventListener('click', function () {
recorder.start()
}) | [
"Begins",
"recording",
"media",
"."
] | 9025a1d0003b0ade09de42a7ea682bf20b5c0224 | https://github.com/ai/audio-recorder-polyfill/blob/9025a1d0003b0ade09de42a7ea682bf20b5c0224/index.js#L80-L118 | train |
ai/audio-recorder-polyfill | index.js | stop | function stop () {
if (this.state === 'inactive') {
return this.em.dispatchEvent(error('stop'))
}
this.requestData()
this.state = 'inactive'
this.clone.getTracks().forEach(function (track) {
track.stop()
})
return clearInterval(this.slicing)
} | javascript | function stop () {
if (this.state === 'inactive') {
return this.em.dispatchEvent(error('stop'))
}
this.requestData()
this.state = 'inactive'
this.clone.getTracks().forEach(function (track) {
track.stop()
})
return clearInterval(this.slicing)
} | [
"function",
"stop",
"(",
")",
"{",
"if",
"(",
"this",
".",
"state",
"===",
"'inactive'",
")",
"{",
"return",
"this",
".",
"em",
".",
"dispatchEvent",
"(",
"error",
"(",
"'stop'",
")",
")",
"}",
"this",
".",
"requestData",
"(",
")",
"this",
".",
"st... | Stop media capture and raise `dataavailable` event with recorded data.
@return {undefined}
@example
finishButton.addEventListener('click', function () {
recorder.stop()
}) | [
"Stop",
"media",
"capture",
"and",
"raise",
"dataavailable",
"event",
"with",
"recorded",
"data",
"."
] | 9025a1d0003b0ade09de42a7ea682bf20b5c0224 | https://github.com/ai/audio-recorder-polyfill/blob/9025a1d0003b0ade09de42a7ea682bf20b5c0224/index.js#L130-L141 | train |
jaggedsoft/node-binance-api | examples/balances-and-exchangeInfo.js | balance | function balance() {
binance.balance((error, balances) => {
if ( error ) console.error(error);
let btc = 0.00;
for ( let asset in balances ) {
let obj = balances[asset];
obj.available = parseFloat(obj.available);
//if ( !obj.available ) continue;
obj.onOrder = parseFloat(obj.onOrder);
obj.btcValue... | javascript | function balance() {
binance.balance((error, balances) => {
if ( error ) console.error(error);
let btc = 0.00;
for ( let asset in balances ) {
let obj = balances[asset];
obj.available = parseFloat(obj.available);
//if ( !obj.available ) continue;
obj.onOrder = parseFloat(obj.onOrder);
obj.btcValue... | [
"function",
"balance",
"(",
")",
"{",
"binance",
".",
"balance",
"(",
"(",
"error",
",",
"balances",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"console",
".",
"error",
"(",
"error",
")",
";",
"let",
"btc",
"=",
"0.00",
";",
"for",
"(",
"let",
"ass... | Get your balances | [
"Get",
"your",
"balances"
] | 1d6c9e4c19b7cab928e462c12a7dcdd0fbe8ff71 | https://github.com/jaggedsoft/node-binance-api/blob/1d6c9e4c19b7cab928e462c12a7dcdd0fbe8ff71/examples/balances-and-exchangeInfo.js#L47-L71 | train |
microstates/microstates.js | src/reflection.js | getAllPropertyDescriptors | function getAllPropertyDescriptors(object) {
if (object === Object.prototype) {
return {};
} else {
let prototype = getPrototypeOf(object);
return assign(getAllPropertyDescriptors(prototype), getOwnPropertyDescriptors(object));
}
} | javascript | function getAllPropertyDescriptors(object) {
if (object === Object.prototype) {
return {};
} else {
let prototype = getPrototypeOf(object);
return assign(getAllPropertyDescriptors(prototype), getOwnPropertyDescriptors(object));
}
} | [
"function",
"getAllPropertyDescriptors",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"===",
"Object",
".",
"prototype",
")",
"{",
"return",
"{",
"}",
";",
"}",
"else",
"{",
"let",
"prototype",
"=",
"getPrototypeOf",
"(",
"object",
")",
";",
"return",
"... | As opposed to `getOwnPropertyDescriptors` which only gets the
descriptors on a single object, `getAllPropertydescriptors` walks
the entire prototype chain starting at `prototype` and gather all
descriptors that are accessible to this object. | [
"As",
"opposed",
"to",
"getOwnPropertyDescriptors",
"which",
"only",
"gets",
"the",
"descriptors",
"on",
"a",
"single",
"object",
"getAllPropertydescriptors",
"walks",
"the",
"entire",
"prototype",
"chain",
"starting",
"at",
"prototype",
"and",
"gather",
"all",
"des... | cd4114be8d9c26f4e68b520adc1380d26c9ba38a | https://github.com/microstates/microstates.js/blob/cd4114be8d9c26f4e68b520adc1380d26c9ba38a/src/reflection.js#L17-L24 | train |
FormidableLabs/rapscallion | src/consumers/node-stream.js | toNodeStream | function toNodeStream (renderer) {
let sourceIsReady = true;
const read = () => {
// If source is not ready, defer any reads until the promise resolves.
if (!sourceIsReady) { return false; }
sourceIsReady = false;
const pull = pullBatch(renderer, stream);
return pull.then(result => {
so... | javascript | function toNodeStream (renderer) {
let sourceIsReady = true;
const read = () => {
// If source is not ready, defer any reads until the promise resolves.
if (!sourceIsReady) { return false; }
sourceIsReady = false;
const pull = pullBatch(renderer, stream);
return pull.then(result => {
so... | [
"function",
"toNodeStream",
"(",
"renderer",
")",
"{",
"let",
"sourceIsReady",
"=",
"true",
";",
"const",
"read",
"=",
"(",
")",
"=>",
"{",
"// If source is not ready, defer any reads until the promise resolves.",
"if",
"(",
"!",
"sourceIsReady",
")",
"{",
"return",... | Consumes the provided sequence and pushes onto a readable Node stream.
@param {Renderer} renderer The Renderer from which to pull next-vals.
@return {Readable} A readable Node stream. | [
"Consumes",
"the",
"provided",
"sequence",
"and",
"pushes",
"onto",
"a",
"readable",
"Node",
"stream",
"."
] | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/consumers/node-stream.js#L14-L42 | train |
FormidableLabs/rapscallion | src/render/traverse.js | evalComponent | function evalComponent (seq, node, context) {
const Component = node.type;
const componentContext = getContext(Component, context);
const instance = constructComponent(Component, node.props, componentContext);
const renderedElement = renderComponentInstance(instance, node.props, componentContext);
const chi... | javascript | function evalComponent (seq, node, context) {
const Component = node.type;
const componentContext = getContext(Component, context);
const instance = constructComponent(Component, node.props, componentContext);
const renderedElement = renderComponentInstance(instance, node.props, componentContext);
const chi... | [
"function",
"evalComponent",
"(",
"seq",
",",
"node",
",",
"context",
")",
"{",
"const",
"Component",
"=",
"node",
".",
"type",
";",
"const",
"componentContext",
"=",
"getContext",
"(",
"Component",
",",
"context",
")",
";",
"const",
"instance",
"=",
"cons... | Prior to being rendered, React components are represented in the same
way as true HTML DOM elements. This function evaluates the component
and traverses through its rendered elements.
@param {Sequence} seq Sequence that receives HTML segments.
@param {VDOM} node VOM node (of a component).
@pa... | [
"Prior",
"to",
"being",
"rendered",
"React",
"components",
"are",
"represented",
"in",
"the",
"same",
"way",
"as",
"true",
"HTML",
"DOM",
"elements",
".",
"This",
"function",
"evaluates",
"the",
"component",
"and",
"traverses",
"through",
"its",
"rendered",
"e... | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/traverse.js#L121-L135 | train |
FormidableLabs/rapscallion | src/render/traverse.js | traverse | function traverse ({ seq, node, context, numChildren, parent }) {
if (node === undefined || node === true) {
return;
}
if (node === false) {
if (parent && isFunction(parent.type)) {
emitEmpty(seq);
return;
} else {
return;
}
}
if (node === null) {
emitEmpty(seq);
re... | javascript | function traverse ({ seq, node, context, numChildren, parent }) {
if (node === undefined || node === true) {
return;
}
if (node === false) {
if (parent && isFunction(parent.type)) {
emitEmpty(seq);
return;
} else {
return;
}
}
if (node === null) {
emitEmpty(seq);
re... | [
"function",
"traverse",
"(",
"{",
"seq",
",",
"node",
",",
"context",
",",
"numChildren",
",",
"parent",
"}",
")",
"{",
"if",
"(",
"node",
"===",
"undefined",
"||",
"node",
"===",
"true",
")",
"{",
"return",
";",
"}",
"if",
"(",
"node",
"===",
"fal... | This function will recursively traverse the VDOM tree, emitting HTML segments
to the provided sequence.
@param {Sequence} seq Sequence that receives HTML segments.
@param {VDOM} node Root VDOM node.
@param {Object} context React context.
@param {Number} numChildren... | [
"This",
"function",
"will",
"recursively",
"traverse",
"the",
"VDOM",
"tree",
"emitting",
"HTML",
"segments",
"to",
"the",
"provided",
"sequence",
"."
] | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/traverse.js#L247-L304 | train |
FormidableLabs/rapscallion | src/render/state.js | syncSetState | function syncSetState (newState) {
// Mutation is faster and should be safe here.
this.state = assign(
this.state,
isFunction(newState) ?
newState(this.state, this.props) :
newState
);
} | javascript | function syncSetState (newState) {
// Mutation is faster and should be safe here.
this.state = assign(
this.state,
isFunction(newState) ?
newState(this.state, this.props) :
newState
);
} | [
"function",
"syncSetState",
"(",
"newState",
")",
"{",
"// Mutation is faster and should be safe here.",
"this",
".",
"state",
"=",
"assign",
"(",
"this",
".",
"state",
",",
"isFunction",
"(",
"newState",
")",
"?",
"newState",
"(",
"this",
".",
"state",
",",
"... | A synchronous replacement for React's `setState` method.
@param {Function|Object} newState An object containing new keys/values
or a function that will provide the same.
@returns {undefined} No return value. | [
"A",
"synchronous",
"replacement",
"for",
"React",
"s",
"setState",
"method",
"."
] | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/state.js#L16-L24 | train |
FormidableLabs/rapscallion | src/consumers/promise.js | toPromise | function toPromise (renderer) {
// this.sequence, this.batchSize, this.dataReactAttrs
const buffer = {
value: [],
push (segment) { this.value.push(segment); }
};
return new Promise((resolve, reject) =>
setImmediate(
asyncBatch,
renderer,
buffer,
resolve,
reject
)
... | javascript | function toPromise (renderer) {
// this.sequence, this.batchSize, this.dataReactAttrs
const buffer = {
value: [],
push (segment) { this.value.push(segment); }
};
return new Promise((resolve, reject) =>
setImmediate(
asyncBatch,
renderer,
buffer,
resolve,
reject
)
... | [
"function",
"toPromise",
"(",
"renderer",
")",
"{",
"// this.sequence, this.batchSize, this.dataReactAttrs",
"const",
"buffer",
"=",
"{",
"value",
":",
"[",
"]",
",",
"push",
"(",
"segment",
")",
"{",
"this",
".",
"value",
".",
"push",
"(",
"segment",
")",
"... | Consumes the provided sequence and returns a promise with the concatenation of all
sequence segments.
@param {Renderer} renderer The Renderer from which to pull next-vals.
@return {Promise} A promise resolving to the HTML string. | [
"Consumes",
"the",
"provided",
"sequence",
"and",
"returns",
"a",
"promise",
"with",
"the",
"concatenation",
"of",
"all",
"sequence",
"segments",
"."
] | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/consumers/promise.js#L46-L75 | train |
FormidableLabs/rapscallion | src/render/context.js | getChildContext | function getChildContext (componentPrototype, instance, context) {
if (componentPrototype.childContextTypes) {
return assign(Object.create(null), context, instance.getChildContext());
}
return context;
} | javascript | function getChildContext (componentPrototype, instance, context) {
if (componentPrototype.childContextTypes) {
return assign(Object.create(null), context, instance.getChildContext());
}
return context;
} | [
"function",
"getChildContext",
"(",
"componentPrototype",
",",
"instance",
",",
"context",
")",
"{",
"if",
"(",
"componentPrototype",
".",
"childContextTypes",
")",
"{",
"return",
"assign",
"(",
"Object",
".",
"create",
"(",
"null",
")",
",",
"context",
",",
... | Using a component prototype's `childContextTypes`, generate an
object that will merged into the master traversal context for
that component's subtree.
@param {Component} componentPrototype The component prototype.
@param {component} instance Component instance.
@param {Object} context ... | [
"Using",
"a",
"component",
"prototype",
"s",
"childContextTypes",
"generate",
"an",
"object",
"that",
"will",
"merged",
"into",
"the",
"master",
"traversal",
"context",
"for",
"that",
"component",
"s",
"subtree",
"."
] | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/context.js#L22-L27 | train |
FormidableLabs/rapscallion | src/render/context.js | getContext | function getContext (componentPrototype, context) {
if (componentPrototype.contextTypes) {
const contextTypes = componentPrototype.contextTypes;
return keys(context).reduce(
(memo, contextKey) => {
if (contextKey in contextTypes) {
memo[contextKey] = context[contextKey];
}
... | javascript | function getContext (componentPrototype, context) {
if (componentPrototype.contextTypes) {
const contextTypes = componentPrototype.contextTypes;
return keys(context).reduce(
(memo, contextKey) => {
if (contextKey in contextTypes) {
memo[contextKey] = context[contextKey];
}
... | [
"function",
"getContext",
"(",
"componentPrototype",
",",
"context",
")",
"{",
"if",
"(",
"componentPrototype",
".",
"contextTypes",
")",
"{",
"const",
"contextTypes",
"=",
"componentPrototype",
".",
"contextTypes",
";",
"return",
"keys",
"(",
"context",
")",
".... | Using a component prototype's `contextTypes`, generate an object that
will be used as React context for a component instance.
@param {Component} componentPrototype The component prototype.
@param {Object} context The master context propagating through
traversal.
@return {Object} ... | [
"Using",
"a",
"component",
"prototype",
"s",
"contextTypes",
"generate",
"an",
"object",
"that",
"will",
"be",
"used",
"as",
"React",
"context",
"for",
"a",
"component",
"instance",
"."
] | 20a8f67778dbc9d224588ee718cb962ddbd71f48 | https://github.com/FormidableLabs/rapscallion/blob/20a8f67778dbc9d224588ee718cb962ddbd71f48/src/render/context.js#L39-L53 | train |
geowarin/friendly-errors-webpack-plugin | src/core/transformErrors.js | processErrors | function processErrors (errors, transformers) {
const transform = (error, transformer) => transformer(error);
const applyTransformations = (error) => transformers.reduce(transform, error);
return errors.map(extractError).map(applyTransformations);
} | javascript | function processErrors (errors, transformers) {
const transform = (error, transformer) => transformer(error);
const applyTransformations = (error) => transformers.reduce(transform, error);
return errors.map(extractError).map(applyTransformations);
} | [
"function",
"processErrors",
"(",
"errors",
",",
"transformers",
")",
"{",
"const",
"transform",
"=",
"(",
"error",
",",
"transformer",
")",
"=>",
"transformer",
"(",
"error",
")",
";",
"const",
"applyTransformations",
"=",
"(",
"error",
")",
"=>",
"transfor... | Applies all transformers to all errors and returns "annotated"
errors.
Each transformer should have the following signature WebpackError => AnnotatedError
A WebpackError has the following fields:
- message
- file
- origin
- name
- severity
- webpackError (original error)
An AnnotatedError should be an extension (Obj... | [
"Applies",
"all",
"transformers",
"to",
"all",
"errors",
"and",
"returns",
"annotated",
"errors",
"."
] | e02907b855288bd91e369b21714bdc2b6417d82b | https://github.com/geowarin/friendly-errors-webpack-plugin/blob/e02907b855288bd91e369b21714bdc2b6417d82b/src/core/transformErrors.js#L27-L32 | train |
geowarin/friendly-errors-webpack-plugin | src/formatters/defaultError.js | format | function format(errors, type) {
return errors
.filter(isDefaultError)
.reduce((accum, error) => (
accum.concat(displayError(type, error))
), []);
} | javascript | function format(errors, type) {
return errors
.filter(isDefaultError)
.reduce((accum, error) => (
accum.concat(displayError(type, error))
), []);
} | [
"function",
"format",
"(",
"errors",
",",
"type",
")",
"{",
"return",
"errors",
".",
"filter",
"(",
"isDefaultError",
")",
".",
"reduce",
"(",
"(",
"accum",
",",
"error",
")",
"=>",
"(",
"accum",
".",
"concat",
"(",
"displayError",
"(",
"type",
",",
... | Format errors without a type | [
"Format",
"errors",
"without",
"a",
"type"
] | e02907b855288bd91e369b21714bdc2b6417d82b | https://github.com/geowarin/friendly-errors-webpack-plugin/blob/e02907b855288bd91e369b21714bdc2b6417d82b/src/formatters/defaultError.js#L35-L41 | train |
geowarin/friendly-errors-webpack-plugin | src/core/formatErrors.js | formatErrors | function formatErrors(errors, formatters, errorType) {
const format = (formatter) => formatter(errors, errorType) || [];
const flatten = (accum, curr) => accum.concat(curr);
return formatters.map(format).reduce(flatten, [])
} | javascript | function formatErrors(errors, formatters, errorType) {
const format = (formatter) => formatter(errors, errorType) || [];
const flatten = (accum, curr) => accum.concat(curr);
return formatters.map(format).reduce(flatten, [])
} | [
"function",
"formatErrors",
"(",
"errors",
",",
"formatters",
",",
"errorType",
")",
"{",
"const",
"format",
"=",
"(",
"formatter",
")",
"=>",
"formatter",
"(",
"errors",
",",
"errorType",
")",
"||",
"[",
"]",
";",
"const",
"flatten",
"=",
"(",
"accum",
... | Applies formatters to all AnnotatedErrors.
A formatter has the following signature: FormattedError => Array<String>.
It takes a formatted error produced by a transformer and returns a list
of log statements to print. | [
"Applies",
"formatters",
"to",
"all",
"AnnotatedErrors",
"."
] | e02907b855288bd91e369b21714bdc2b6417d82b | https://github.com/geowarin/friendly-errors-webpack-plugin/blob/e02907b855288bd91e369b21714bdc2b6417d82b/src/core/formatErrors.js#L11-L16 | train |
creativelive/appear | lib/appearlazy.js | doReveal | function doReveal(el) {
var orig = el.getAttribute('src') || false;
el.addEventListener('error', function handler(e) {
// on error put back the original image if available (usually a placeholder)
console.log('error loading image', e);
if (orig) {
el.setAttribute('src', ori... | javascript | function doReveal(el) {
var orig = el.getAttribute('src') || false;
el.addEventListener('error', function handler(e) {
// on error put back the original image if available (usually a placeholder)
console.log('error loading image', e);
if (orig) {
el.setAttribute('src', ori... | [
"function",
"doReveal",
"(",
"el",
")",
"{",
"var",
"orig",
"=",
"el",
".",
"getAttribute",
"(",
"'src'",
")",
"||",
"false",
";",
"el",
".",
"addEventListener",
"(",
"'error'",
",",
"function",
"handler",
"(",
"e",
")",
"{",
"// on error put back the orig... | set the image src or background attribute | [
"set",
"the",
"image",
"src",
"or",
"background",
"attribute"
] | 4ae92e6f7ccbad0a00431ddec419b25ca3de2927 | https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appearlazy.js#L16-L40 | train |
creativelive/appear | lib/appearlazy.js | reveal | function reveal(el) {
if (el.hasChildNodes()) {
// dealing with a container try and find children
var els = el.querySelectorAll('[data-src], [data-bkg]');
var elsl = els.length;
if (elsl === 0) {
// node has children, but none have the attributes, so reveal
// t... | javascript | function reveal(el) {
if (el.hasChildNodes()) {
// dealing with a container try and find children
var els = el.querySelectorAll('[data-src], [data-bkg]');
var elsl = els.length;
if (elsl === 0) {
// node has children, but none have the attributes, so reveal
// t... | [
"function",
"reveal",
"(",
"el",
")",
"{",
"if",
"(",
"el",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"// dealing with a container try and find children",
"var",
"els",
"=",
"el",
".",
"querySelectorAll",
"(",
"'[data-src], [data-bkg]'",
")",
";",
"var",
"elsl",... | find what element to work with, as we support containers of images | [
"find",
"what",
"element",
"to",
"work",
"with",
"as",
"we",
"support",
"containers",
"of",
"images"
] | 4ae92e6f7ccbad0a00431ddec419b25ca3de2927 | https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appearlazy.js#L43-L60 | train |
creativelive/appear | lib/appearlazy.js | init | function init() {
// find all elements with the class "appear"
var els = document.getElementsByClassName('appear');
var elsl = els.length;
// put html elements into an array object to work with
for (var i = 0; i < elsl; i += 1) {
// some images are revealed on a simple... | javascript | function init() {
// find all elements with the class "appear"
var els = document.getElementsByClassName('appear');
var elsl = els.length;
// put html elements into an array object to work with
for (var i = 0; i < elsl; i += 1) {
// some images are revealed on a simple... | [
"function",
"init",
"(",
")",
"{",
"// find all elements with the class \"appear\"",
"var",
"els",
"=",
"document",
".",
"getElementsByClassName",
"(",
"'appear'",
")",
";",
"var",
"elsl",
"=",
"els",
".",
"length",
";",
"// put html elements into an array object to wo... | function executed when dom is interactive | [
"function",
"executed",
"when",
"dom",
"is",
"interactive"
] | 4ae92e6f7ccbad0a00431ddec419b25ca3de2927 | https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appearlazy.js#L71-L87 | train |
creativelive/appear | lib/appear.js | debounce | function debounce(fn, delay) {
return function () {
var self = this, args = arguments;
clearTimeout(timer);
console.log('debounce()');
timer = setTimeout(function () {
fn.apply(self, args);
}, delay);
};
} | javascript | function debounce(fn, delay) {
return function () {
var self = this, args = arguments;
clearTimeout(timer);
console.log('debounce()');
timer = setTimeout(function () {
fn.apply(self, args);
}, delay);
};
} | [
"function",
"debounce",
"(",
"fn",
",",
"delay",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"args",
"=",
"arguments",
";",
"clearTimeout",
"(",
"timer",
")",
";",
"console",
".",
"log",
"(",
"'debounce()'",
")",
"... | handle debouncing a function for better performance on scroll | [
"handle",
"debouncing",
"a",
"function",
"for",
"better",
"performance",
"on",
"scroll"
] | 4ae92e6f7ccbad0a00431ddec419b25ca3de2927 | https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appear.js#L40-L49 | train |
creativelive/appear | lib/appear.js | checkAppear | function checkAppear() {
if(scroll.delta < opts.delta.speed) {
if(!deltaSet) {
deltaSet = true;
doCheckAppear();
setTimeout(function(){
deltaSet = false;
}, opts.delta.timeout);
}
}
(debounce(function() {
... | javascript | function checkAppear() {
if(scroll.delta < opts.delta.speed) {
if(!deltaSet) {
deltaSet = true;
doCheckAppear();
setTimeout(function(){
deltaSet = false;
}, opts.delta.timeout);
}
}
(debounce(function() {
... | [
"function",
"checkAppear",
"(",
")",
"{",
"if",
"(",
"scroll",
".",
"delta",
"<",
"opts",
".",
"delta",
".",
"speed",
")",
"{",
"if",
"(",
"!",
"deltaSet",
")",
"{",
"deltaSet",
"=",
"true",
";",
"doCheckAppear",
"(",
")",
";",
"setTimeout",
"(",
"... | called on scroll and resize event, so debounce the actual function that does the heavy work of determining if an item is viewable and then "appearing" it | [
"called",
"on",
"scroll",
"and",
"resize",
"event",
"so",
"debounce",
"the",
"actual",
"function",
"that",
"does",
"the",
"heavy",
"work",
"of",
"determining",
"if",
"an",
"item",
"is",
"viewable",
"and",
"then",
"appearing",
"it"
] | 4ae92e6f7ccbad0a00431ddec419b25ca3de2927 | https://github.com/creativelive/appear/blob/4ae92e6f7ccbad0a00431ddec419b25ca3de2927/lib/appear.js#L53-L66 | train |
jriecken/sat-js | examples/examples.js | poly2path | function poly2path(polygon) {
var pos = polygon.pos;
var points = polygon.calcPoints;
var result = 'M' + pos.x + ' ' + pos.y;
result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
for (var i = 1; i < points.length; i++) {
var point = points[i];
result += 'L' + (pos.x + point.x) + ' ' + ... | javascript | function poly2path(polygon) {
var pos = polygon.pos;
var points = polygon.calcPoints;
var result = 'M' + pos.x + ' ' + pos.y;
result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
for (var i = 1; i < points.length; i++) {
var point = points[i];
result += 'L' + (pos.x + point.x) + ' ' + ... | [
"function",
"poly2path",
"(",
"polygon",
")",
"{",
"var",
"pos",
"=",
"polygon",
".",
"pos",
";",
"var",
"points",
"=",
"polygon",
".",
"calcPoints",
";",
"var",
"result",
"=",
"'M'",
"+",
"pos",
".",
"x",
"+",
"' '",
"+",
"pos",
".",
"y",
";",
"... | Converts a SAT.Polygon into a SVG path string. | [
"Converts",
"a",
"SAT",
".",
"Polygon",
"into",
"a",
"SVG",
"path",
"string",
"."
] | 4e06e0a81ae38d6630469d94beb1a46d7b5f74bb | https://github.com/jriecken/sat-js/blob/4e06e0a81ae38d6630469d94beb1a46d7b5f74bb/examples/examples.js#L8-L19 | train |
jriecken/sat-js | examples/examples.js | moveDrag | function moveDrag(entity, world) {
return function (dx, dy) {
// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.
entity.data.pos.x = this.ox + dx;
entity.data.pos.y = this.oy + dy;
world.simulate();
};
} | javascript | function moveDrag(entity, world) {
return function (dx, dy) {
// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.
entity.data.pos.x = this.ox + dx;
entity.data.pos.y = this.oy + dy;
world.simulate();
};
} | [
"function",
"moveDrag",
"(",
"entity",
",",
"world",
")",
"{",
"return",
"function",
"(",
"dx",
",",
"dy",
")",
"{",
"// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.",
"entity",
".",
"data",
".",
"po... | Create a Raphael move drag handler for specified entity | [
"Create",
"a",
"Raphael",
"move",
"drag",
"handler",
"for",
"specified",
"entity"
] | 4e06e0a81ae38d6630469d94beb1a46d7b5f74bb | https://github.com/jriecken/sat-js/blob/4e06e0a81ae38d6630469d94beb1a46d7b5f74bb/examples/examples.js#L29-L36 | train |
jriecken/sat-js | examples/examples.js | function () {
if (this.data instanceof SAT.Circle) {
this.displayAttrs.cx = this.data.pos.x;
this.displayAttrs.cy = this.data.pos.y;
this.displayAttrs.r = this.data.r;
} else {
this.displayAttrs.path = poly2path(this.data);
}
this.display.attr(this.displayAttrs);
} | javascript | function () {
if (this.data instanceof SAT.Circle) {
this.displayAttrs.cx = this.data.pos.x;
this.displayAttrs.cy = this.data.pos.y;
this.displayAttrs.r = this.data.r;
} else {
this.displayAttrs.path = poly2path(this.data);
}
this.display.attr(this.displayAttrs);
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"data",
"instanceof",
"SAT",
".",
"Circle",
")",
"{",
"this",
".",
"displayAttrs",
".",
"cx",
"=",
"this",
".",
"data",
".",
"pos",
".",
"x",
";",
"this",
".",
"displayAttrs",
".",
"cy",
"=",
"th... | Call this to update the display after changing the underlying data. | [
"Call",
"this",
"to",
"update",
"the",
"display",
"after",
"changing",
"the",
"underlying",
"data",
"."
] | 4e06e0a81ae38d6630469d94beb1a46d7b5f74bb | https://github.com/jriecken/sat-js/blob/4e06e0a81ae38d6630469d94beb1a46d7b5f74bb/examples/examples.js#L73-L82 | train | |
poppinss/indicative | src/core/starToIndex.js | starToIndex | function starToIndex (pairs, data, i, out) {
if (!data) {
return []
}
i = i || 0
let curr = pairs[i++]
const next = pairs[i]
/**
* When out is not defined, then start
* with the current node
*/
if (!out) {
out = [curr]
curr = ''
}
/**
* Keep on adding to the out array. The ... | javascript | function starToIndex (pairs, data, i, out) {
if (!data) {
return []
}
i = i || 0
let curr = pairs[i++]
const next = pairs[i]
/**
* When out is not defined, then start
* with the current node
*/
if (!out) {
out = [curr]
curr = ''
}
/**
* Keep on adding to the out array. The ... | [
"function",
"starToIndex",
"(",
"pairs",
",",
"data",
",",
"i",
",",
"out",
")",
"{",
"if",
"(",
"!",
"data",
")",
"{",
"return",
"[",
"]",
"}",
"i",
"=",
"i",
"||",
"0",
"let",
"curr",
"=",
"pairs",
"[",
"i",
"++",
"]",
"const",
"next",
"=",... | This method loops over an array and build properties based upon
values available inside the data object.
This method is supposed to never throw any exceptions, and instead
skip a property when data or pairs are not in right format.
@method starToIndex
@param {Array} pairs
@param {Object} data
@param {Number} i
@par... | [
"This",
"method",
"loops",
"over",
"an",
"array",
"and",
"build",
"properties",
"based",
"upon",
"values",
"available",
"inside",
"the",
"data",
"object",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/starToIndex.js#L35-L84 | train |
poppinss/indicative | src/core/pSeries.js | onRejected | function onRejected (error) {
return {
fullFilled: false,
rejected: true,
value: null,
reason: error
}
} | javascript | function onRejected (error) {
return {
fullFilled: false,
rejected: true,
value: null,
reason: error
}
} | [
"function",
"onRejected",
"(",
"error",
")",
"{",
"return",
"{",
"fullFilled",
":",
"false",
",",
"rejected",
":",
"true",
",",
"value",
":",
"null",
",",
"reason",
":",
"error",
"}",
"}"
] | Returns an object containing enough info whether
the promises was rejected or not.
@method onRejected
@param {Object} error
@returns {Object} | [
"Returns",
"an",
"object",
"containing",
"enough",
"info",
"whether",
"the",
"promises",
"was",
"rejected",
"or",
"not",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/pSeries.js#L41-L48 | train |
poppinss/indicative | src/core/pSeries.js | pSeries | function pSeries (iterable, bail) {
const result = []
const iterableLength = iterable.length
function noop (index, bail) {
/**
* End of promises
*/
if (index >= iterableLength) {
return Promise.resolve(result)
}
return iterable[index]
.then((output) => {
result.push... | javascript | function pSeries (iterable, bail) {
const result = []
const iterableLength = iterable.length
function noop (index, bail) {
/**
* End of promises
*/
if (index >= iterableLength) {
return Promise.resolve(result)
}
return iterable[index]
.then((output) => {
result.push... | [
"function",
"pSeries",
"(",
"iterable",
",",
"bail",
")",
"{",
"const",
"result",
"=",
"[",
"]",
"const",
"iterableLength",
"=",
"iterable",
".",
"length",
"function",
"noop",
"(",
"index",
",",
"bail",
")",
"{",
"/**\n * End of promises\n */",
"if",
... | Here we run an array of promises in sequence until the last
promise is finished.
When `bail=true`, it will break the chain when first promise returns
the error/exception.
## Why serial?
Since the validations have to be executed one after the other, the
promises execution has to be in sequence
## Why wait for all pro... | [
"Here",
"we",
"run",
"an",
"array",
"of",
"promises",
"in",
"sequence",
"until",
"the",
"last",
"promise",
"is",
"finished",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/pSeries.js#L99-L136 | train |
poppinss/indicative | bin/qunit.js | start | async function start () {
let exitCode = 0
const port = process.env.PORT || 3000
console.log(chalk`{magenta creating app bundle}`)
/**
* Creating rollup bundle by bundling `test/qunit/index.js` file.
*/
const bundle = await rollup.rollup({
input: path.join(__dirname, '../test', 'qunit', 'index'),
... | javascript | async function start () {
let exitCode = 0
const port = process.env.PORT || 3000
console.log(chalk`{magenta creating app bundle}`)
/**
* Creating rollup bundle by bundling `test/qunit/index.js` file.
*/
const bundle = await rollup.rollup({
input: path.join(__dirname, '../test', 'qunit', 'index'),
... | [
"async",
"function",
"start",
"(",
")",
"{",
"let",
"exitCode",
"=",
"0",
"const",
"port",
"=",
"process",
".",
"env",
".",
"PORT",
"||",
"3000",
"console",
".",
"log",
"(",
"chalk",
"`",
"`",
")",
"/**\n * Creating rollup bundle by bundling `test/qunit/inde... | Start of the process
@method start | [
"Start",
"of",
"the",
"process"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/qunit.js#L79-L165 | train |
poppinss/indicative | src/core/configure.js | setConfig | function setConfig (options) {
Object.keys(options).forEach((option) => {
if (config[option] !== undefined) {
config[option] = options[option]
}
})
} | javascript | function setConfig (options) {
Object.keys(options).forEach((option) => {
if (config[option] !== undefined) {
config[option] = options[option]
}
})
} | [
"function",
"setConfig",
"(",
"options",
")",
"{",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"forEach",
"(",
"(",
"option",
")",
"=>",
"{",
"if",
"(",
"config",
"[",
"option",
"]",
"!==",
"undefined",
")",
"{",
"config",
"[",
"option",
"]",
... | Override configuration values
@method setConfig
@param {Object} | [
"Override",
"configuration",
"values"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/configure.js#L21-L27 | train |
poppinss/indicative | src/core/validator.js | validationFn | function validationFn (validations, {name, args}, field, data, messages, formatter) {
return new PLazy((resolve, reject) => {
const camelizedName = snakeToCamelCase(name)
const validation = validations[camelizedName]
if (typeof (validation) !== 'function') {
const error = new Error(`${camelizedName... | javascript | function validationFn (validations, {name, args}, field, data, messages, formatter) {
return new PLazy((resolve, reject) => {
const camelizedName = snakeToCamelCase(name)
const validation = validations[camelizedName]
if (typeof (validation) !== 'function') {
const error = new Error(`${camelizedName... | [
"function",
"validationFn",
"(",
"validations",
",",
"{",
"name",
",",
"args",
"}",
",",
"field",
",",
"data",
",",
"messages",
",",
"formatter",
")",
"{",
"return",
"new",
"PLazy",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"camelize... | Returns a lazy promise which runs the validation on a field
for a given rule. This method will register promise
rejections with the formatter.
@method validationFn
@param {Object} validations
@param {Object} rule
@property {String} rule.name
@property {Array} rule.args
@param {String} field
@param {Objec... | [
"Returns",
"a",
"lazy",
"promise",
"which",
"runs",
"the",
"validation",
"on",
"a",
"field",
"for",
"a",
"given",
"rule",
".",
"This",
"method",
"will",
"register",
"promise",
"rejections",
"with",
"the",
"formatter",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/validator.js#L38-L57 | train |
poppinss/indicative | src/core/validator.js | getValidationsStack | function getValidationsStack (validations, fields, data, messages, formatter) {
return Object
.keys(fields)
.reduce((flatValidations, field) => {
fields[field].map((rule) => {
flatValidations.push(validationFn(validations, rule, field, data, messages, formatter))
})
return flatValida... | javascript | function getValidationsStack (validations, fields, data, messages, formatter) {
return Object
.keys(fields)
.reduce((flatValidations, field) => {
fields[field].map((rule) => {
flatValidations.push(validationFn(validations, rule, field, data, messages, formatter))
})
return flatValida... | [
"function",
"getValidationsStack",
"(",
"validations",
",",
"fields",
",",
"data",
",",
"messages",
",",
"formatter",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"fields",
")",
".",
"reduce",
"(",
"(",
"flatValidations",
",",
"field",
")",
"=>",
"{",
... | This method loops over the fields and returns a flat stack of
validations for each field and multiple rules on that field.
Also all validation methods are wrapped inside a Lazy promise,
so they are executed when `.then` or `.catch` is called on
them.
@method getValidationsStack
@param {Object} validations - Object... | [
"This",
"method",
"loops",
"over",
"the",
"fields",
"and",
"returns",
"a",
"flat",
"stack",
"of",
"validations",
"for",
"each",
"field",
"and",
"multiple",
"rules",
"on",
"that",
"field",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/validator.js#L77-L86 | train |
poppinss/indicative | src/core/validator.js | validate | function validate (validations, bail, data, fields, messages, formatter) {
return new Promise((resolve, reject) => {
messages = messages || {}
/**
* This is expanded form of fields and rules
* applied on them
*/
const parsedFields = parse(fields, data)
/**
* A flat validations st... | javascript | function validate (validations, bail, data, fields, messages, formatter) {
return new Promise((resolve, reject) => {
messages = messages || {}
/**
* This is expanded form of fields and rules
* applied on them
*/
const parsedFields = parse(fields, data)
/**
* A flat validations st... | [
"function",
"validate",
"(",
"validations",
",",
"bail",
",",
"data",
",",
"fields",
",",
"messages",
",",
"formatter",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"messages",
"=",
"messages",
"||",
"{",
"}... | Run `validations` on `data` using rules defined on `fields`.
@method validate
@param {Object} validations - Object of available validations
@param {Boolean} bail - Whether to bail on first error or not
@param {Object} data - Data to validate
@param {Object} fields - Fields and their rules
@p... | [
"Run",
"validations",
"on",
"data",
"using",
"rules",
"defined",
"on",
"fields",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/validator.js#L102-L126 | train |
poppinss/indicative | src/core/sanitizor.js | sanitizeField | function sanitizeField (sanitizations, value, rules) {
let result = value
rules.forEach((rule) => {
const ruleFn = snakeToCamelCase(rule.name)
if (typeof (sanitizations[ruleFn]) !== 'function') {
throw new Error(`${ruleFn} is not a sanitization method`)
}
result = sanitizations[ruleFn](result... | javascript | function sanitizeField (sanitizations, value, rules) {
let result = value
rules.forEach((rule) => {
const ruleFn = snakeToCamelCase(rule.name)
if (typeof (sanitizations[ruleFn]) !== 'function') {
throw new Error(`${ruleFn} is not a sanitization method`)
}
result = sanitizations[ruleFn](result... | [
"function",
"sanitizeField",
"(",
"sanitizations",
",",
"value",
",",
"rules",
")",
"{",
"let",
"result",
"=",
"value",
"rules",
".",
"forEach",
"(",
"(",
"rule",
")",
"=>",
"{",
"const",
"ruleFn",
"=",
"snakeToCamelCase",
"(",
"rule",
".",
"name",
")",
... | Runs a bunch of sanitization rules on a given value
@method sanitizeField
@param {Object} sanitizations
@param {Mixed} value
@param {Array} rules
@return {Mixed}
@throws {Exception} If sanitization rule doesnt exists | [
"Runs",
"a",
"bunch",
"of",
"sanitization",
"rules",
"on",
"a",
"given",
"value"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/sanitizor.js#L93-L105 | train |
poppinss/indicative | bin/inlineDocs.js | getFiles | function getFiles (location, filterFn) {
return new Promise((resolve, reject) => {
const files = []
klaw(location)
.on('data', (item) => {
if (!item.stats.isDirectory() && filterFn(item)) {
files.push(item.path)
}
})
.on('end', () => resolve(files))
.on('error', reject)
}... | javascript | function getFiles (location, filterFn) {
return new Promise((resolve, reject) => {
const files = []
klaw(location)
.on('data', (item) => {
if (!item.stats.isDirectory() && filterFn(item)) {
files.push(item.path)
}
})
.on('end', () => resolve(files))
.on('error', reject)
}... | [
"function",
"getFiles",
"(",
"location",
",",
"filterFn",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"files",
"=",
"[",
"]",
"klaw",
"(",
"location",
")",
".",
"on",
"(",
"'data'",
",",
"(",
"... | Walks over a location and reads all .js files
@method getFiles
@param {String} location
@param {Function} filterFn
@return {Array} | [
"Walks",
"over",
"a",
"location",
"and",
"reads",
"all",
".",
"js",
"files"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L50-L62 | train |
poppinss/indicative | bin/inlineDocs.js | readFiles | async function readFiles (locations) {
return Promise.all(locations.map((location) => {
return fs.readFile(location, 'utf-8')
}))
} | javascript | async function readFiles (locations) {
return Promise.all(locations.map((location) => {
return fs.readFile(location, 'utf-8')
}))
} | [
"async",
"function",
"readFiles",
"(",
"locations",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"locations",
".",
"map",
"(",
"(",
"location",
")",
"=>",
"{",
"return",
"fs",
".",
"readFile",
"(",
"location",
",",
"'utf-8'",
")",
"}",
")",
")",
"... | Returns an array of files in parallel
@method readFiles
@param {Array} locations
@return {Array} | [
"Returns",
"an",
"array",
"of",
"files",
"in",
"parallel"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L73-L77 | train |
poppinss/indicative | bin/inlineDocs.js | extractComments | function extractComments (contents) {
let context = 'idle'
const lines = []
contents.split('\n').forEach((line) => {
if (line.trim() === '/**') {
context = 'in'
return
}
if (line.trim() === '*/') {
context = 'out'
return
}
if (context === 'in') {
lines.push(line... | javascript | function extractComments (contents) {
let context = 'idle'
const lines = []
contents.split('\n').forEach((line) => {
if (line.trim() === '/**') {
context = 'in'
return
}
if (line.trim() === '*/') {
context = 'out'
return
}
if (context === 'in') {
lines.push(line... | [
"function",
"extractComments",
"(",
"contents",
")",
"{",
"let",
"context",
"=",
"'idle'",
"const",
"lines",
"=",
"[",
"]",
"contents",
".",
"split",
"(",
"'\\n'",
")",
".",
"forEach",
"(",
"(",
"line",
")",
"=>",
"{",
"if",
"(",
"line",
".",
"trim",... | Extract comments from the top of the file. Also this method
assumes, each block of content has only one top of comments
section.
@method extractComments
@param {String} contents
@return {String} | [
"Extract",
"comments",
"from",
"the",
"top",
"of",
"the",
"file",
".",
"Also",
"this",
"method",
"assumes",
"each",
"block",
"of",
"content",
"has",
"only",
"one",
"top",
"of",
"comments",
"section",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L90-L109 | train |
poppinss/indicative | bin/inlineDocs.js | writeDocs | async function writeDocs (basePath, nodes) {
Promise.all(nodes.map((node) => {
const location = path.join(basePath, node.location.replace(srcPath, '').replace(/\.js$/, '.adoc'))
return fs.outputFile(location, node.comments)
}))
} | javascript | async function writeDocs (basePath, nodes) {
Promise.all(nodes.map((node) => {
const location = path.join(basePath, node.location.replace(srcPath, '').replace(/\.js$/, '.adoc'))
return fs.outputFile(location, node.comments)
}))
} | [
"async",
"function",
"writeDocs",
"(",
"basePath",
",",
"nodes",
")",
"{",
"Promise",
".",
"all",
"(",
"nodes",
".",
"map",
"(",
"(",
"node",
")",
"=>",
"{",
"const",
"location",
"=",
"path",
".",
"join",
"(",
"basePath",
",",
"node",
".",
"location"... | Writes all docs to their respective files
@method writeDocs
@param {String} basePath
@param {Array} nodes
@return {void} | [
"Writes",
"all",
"docs",
"to",
"their",
"respective",
"files"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L121-L126 | train |
poppinss/indicative | bin/inlineDocs.js | srcToDocs | async function srcToDocs (dir) {
const location = path.join(srcPath, dir)
const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js'))
const filesContents = await readFiles(srcFiles)
const filesComments = srcFiles.map((location, index) => {
const fnName =... | javascript | async function srcToDocs (dir) {
const location = path.join(srcPath, dir)
const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js'))
const filesContents = await readFiles(srcFiles)
const filesComments = srcFiles.map((location, index) => {
const fnName =... | [
"async",
"function",
"srcToDocs",
"(",
"dir",
")",
"{",
"const",
"location",
"=",
"path",
".",
"join",
"(",
"srcPath",
",",
"dir",
")",
"const",
"srcFiles",
"=",
"await",
"getFiles",
"(",
"location",
",",
"(",
"item",
")",
"=>",
"item",
".",
"path",
... | Converts all source files inside a directory to `.adoc`
files inside docs directory
@method srcToDocs
@param {String} dir
@return {void} | [
"Converts",
"all",
"source",
"files",
"inside",
"a",
"directory",
"to",
".",
"adoc",
"files",
"inside",
"docs",
"directory"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/inlineDocs.js#L138-L149 | train |
poppinss/indicative | src/core/parse.js | parseRules | function parseRules (fields, data) {
data = data || {}
return Object.keys(fields).reduce((result, field) => {
let rules = fields[field]
/**
* Strings are passed to haye for further processing
* and if rules are not an array or a string, then
* we should blow.
*/
if (typeof (rules) ... | javascript | function parseRules (fields, data) {
data = data || {}
return Object.keys(fields).reduce((result, field) => {
let rules = fields[field]
/**
* Strings are passed to haye for further processing
* and if rules are not an array or a string, then
* we should blow.
*/
if (typeof (rules) ... | [
"function",
"parseRules",
"(",
"fields",
",",
"data",
")",
"{",
"data",
"=",
"data",
"||",
"{",
"}",
"return",
"Object",
".",
"keys",
"(",
"fields",
")",
".",
"reduce",
"(",
"(",
"result",
",",
"field",
")",
"=>",
"{",
"let",
"rules",
"=",
"fields"... | This method parses the rules object into a new object with
expanded field names and transformed rules.
### Expanding fields
One can define `*` expression to denote an array of fields
to be validated.
The `*` expression is expanded based upon the available data.
For example
```js
const rules = {
'users.*.username': r... | [
"This",
"method",
"parses",
"the",
"rules",
"object",
"into",
"a",
"new",
"object",
"with",
"expanded",
"field",
"names",
"and",
"transformed",
"rules",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/parse.js#L59-L90 | train |
poppinss/indicative | bin/sauceLabs.js | function (route, body, method = 'post') {
return got(`https://saucelabs.com/rest/v1/${process.env.SAUCE_USERNAME}/${route}`, {
method,
json: true,
body,
headers: {
Authorization: `Basic ${getCredentials()}`
}
}).then((response) => {
return response.body
}).catch((error) => {
thro... | javascript | function (route, body, method = 'post') {
return got(`https://saucelabs.com/rest/v1/${process.env.SAUCE_USERNAME}/${route}`, {
method,
json: true,
body,
headers: {
Authorization: `Basic ${getCredentials()}`
}
}).then((response) => {
return response.body
}).catch((error) => {
thro... | [
"function",
"(",
"route",
",",
"body",
",",
"method",
"=",
"'post'",
")",
"{",
"return",
"got",
"(",
"`",
"${",
"process",
".",
"env",
".",
"SAUCE_USERNAME",
"}",
"${",
"route",
"}",
"`",
",",
"{",
"method",
",",
"json",
":",
"true",
",",
"body",
... | Makes an http request to sauceLabs
@method makeHttpRequest
@param {String} route
@param {Object} body
@param {String} [method = 'post']
@return {Promise} | [
"Makes",
"an",
"http",
"request",
"to",
"sauceLabs"
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/bin/sauceLabs.js#L37-L50 | train | |
poppinss/indicative | src/core/getMessage.js | getMessage | function getMessage (messages, field, validation, args) {
/**
* Since we allow array expression as `*`, we want all index of the
* current field to be replaced with `.*`, so that we get the
* right message.
*/
const originalField = field.replace(/\.\d/g, '.*')
const camelizedValidation = snakeToCamelC... | javascript | function getMessage (messages, field, validation, args) {
/**
* Since we allow array expression as `*`, we want all index of the
* current field to be replaced with `.*`, so that we get the
* right message.
*/
const originalField = field.replace(/\.\d/g, '.*')
const camelizedValidation = snakeToCamelC... | [
"function",
"getMessage",
"(",
"messages",
",",
"field",
",",
"validation",
",",
"args",
")",
"{",
"/**\n * Since we allow array expression as `*`, we want all index of the\n * current field to be replaced with `.*`, so that we get the\n * right message.\n */",
"const",
"original... | Returns message for a given field and a validation rule. The priority is
defined as follows in order from top to bottom.
1. Message for `field.validation`
2. Message for validation
3. Default message
### Templating
Support dynamic placeholders in messages as shown below.
```
{{ validation }} validation failed on {{ ... | [
"Returns",
"message",
"for",
"a",
"given",
"field",
"and",
"a",
"validation",
"rule",
".",
"The",
"priority",
"is",
"defined",
"as",
"follows",
"in",
"order",
"from",
"top",
"to",
"bottom",
"."
] | bb3e149ced03e8e0c51e5169e1e2a7282b956d9a | https://github.com/poppinss/indicative/blob/bb3e149ced03e8e0c51e5169e1e2a7282b956d9a/src/core/getMessage.js#L52-L70 | train |
brehaut/color-js | color.js | function(bytes) {
bytes = bytes || 2;
var max = Math.pow(16, bytes) - 1;
var css = [
"#",
pad(Math.round(this.red * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.green * max).toString(16).toUpperCase(), bytes),
... | javascript | function(bytes) {
bytes = bytes || 2;
var max = Math.pow(16, bytes) - 1;
var css = [
"#",
pad(Math.round(this.red * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.green * max).toString(16).toUpperCase(), bytes),
... | [
"function",
"(",
"bytes",
")",
"{",
"bytes",
"=",
"bytes",
"||",
"2",
";",
"var",
"max",
"=",
"Math",
".",
"pow",
"(",
"16",
",",
"bytes",
")",
"-",
"1",
";",
"var",
"css",
"=",
"[",
"\"#\"",
",",
"pad",
"(",
"Math",
".",
"round",
"(",
"this"... | convert to a CSS string. defaults to two bytes a value | [
"convert",
"to",
"a",
"CSS",
"string",
".",
"defaults",
"to",
"two",
"bytes",
"a",
"value"
] | 23fc53428d972efb9f1f365781d8ba0407ae7213 | https://github.com/brehaut/color-js/blob/23fc53428d972efb9f1f365781d8ba0407ae7213/color.js#L412-L424 | train |
Subsets and Splits
SQL Console for semeru/code-text-javascript
Retrieves 20,000 non-null code samples labeled as JavaScript, providing a basic overview of the dataset.