id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
40,400 | noderaider/repackage | jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js | inShadow | function inShadow(key) {
var path = this;
do {
if (path.isFunction()) {
var shadow = path.node.shadow;
if (shadow) {
// this is because sometimes we may have a `shadow` value of:
//
// { this: false }
//
// we need to catch this case if `inShadow` has been passed a `key`
if (!key || shadow[key] !== false) {
return path;
}
} else if (path.isArrowFunctionExpression()) {
return path;
}
// normal function, we've found our function context
return null;
}
} while (path = path.parentPath);
return null;
} | javascript | function inShadow(key) {
var path = this;
do {
if (path.isFunction()) {
var shadow = path.node.shadow;
if (shadow) {
// this is because sometimes we may have a `shadow` value of:
//
// { this: false }
//
// we need to catch this case if `inShadow` has been passed a `key`
if (!key || shadow[key] !== false) {
return path;
}
} else if (path.isArrowFunctionExpression()) {
return path;
}
// normal function, we've found our function context
return null;
}
} while (path = path.parentPath);
return null;
} | [
"function",
"inShadow",
"(",
"key",
")",
"{",
"var",
"path",
"=",
"this",
";",
"do",
"{",
"if",
"(",
"path",
".",
"isFunction",
"(",
")",
")",
"{",
"var",
"shadow",
"=",
"path",
".",
"node",
".",
"shadow",
";",
"if",
"(",
"shadow",
")",
"{",
"// this is because sometimes we may have a `shadow` value of:",
"//",
"// { this: false }",
"//",
"// we need to catch this case if `inShadow` has been passed a `key`",
"if",
"(",
"!",
"key",
"||",
"shadow",
"[",
"key",
"]",
"!==",
"false",
")",
"{",
"return",
"path",
";",
"}",
"}",
"else",
"if",
"(",
"path",
".",
"isArrowFunctionExpression",
"(",
")",
")",
"{",
"return",
"path",
";",
"}",
"// normal function, we've found our function context",
"return",
"null",
";",
"}",
"}",
"while",
"(",
"path",
"=",
"path",
".",
"parentPath",
")",
";",
"return",
"null",
";",
"}"
]
| Check if we're inside a shadowed function. | [
"Check",
"if",
"we",
"re",
"inside",
"a",
"shadowed",
"function",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js#L223-L246 |
40,401 | Kronos-Integration/kronos-interceptor-line-header | src/line-header.js | getRealHeaderCheck | function getRealHeaderCheck(expectedHeader, caseSensitive, fieldNames) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
// the header must have all the expected columns but may have more
return _getRealHeader(expectedHeader, actualHeader, fieldNames);
};
} | javascript | function getRealHeaderCheck(expectedHeader, caseSensitive, fieldNames) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
// the header must have all the expected columns but may have more
return _getRealHeader(expectedHeader, actualHeader, fieldNames);
};
} | [
"function",
"getRealHeaderCheck",
"(",
"expectedHeader",
",",
"caseSensitive",
",",
"fieldNames",
")",
"{",
"return",
"function",
"(",
"content",
")",
"{",
"let",
"actualHeader",
";",
"if",
"(",
"caseSensitive",
")",
"{",
"actualHeader",
"=",
"content",
";",
"}",
"else",
"{",
"actualHeader",
"=",
"arrayToUpperCase",
"(",
"content",
")",
";",
"expectedHeader",
"=",
"arrayToUpperCase",
"(",
"expectedHeader",
")",
";",
"}",
"// the header must have all the expected columns but may have more",
"return",
"_getRealHeader",
"(",
"expectedHeader",
",",
"actualHeader",
",",
"fieldNames",
")",
";",
"}",
";",
"}"
]
| Creates a check which will match the future columns names to there real position
@param expectedHeader The expected header
@param caseSensitive Is the header case sensitive
@param fieldNames The fieldNames to use for each field.
@return fieldMap This maps the fieldNames to the position in the array. | [
"Creates",
"a",
"check",
"which",
"will",
"match",
"the",
"future",
"columns",
"names",
"to",
"there",
"real",
"position"
]
| 4baadc7782b94986abf947267a79d7328aebba18 | https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L158-L172 |
40,402 | Kronos-Integration/kronos-interceptor-line-header | src/line-header.js | getStrictCheck | function getStrictCheck(expectedHeader, caseSensitive, severity) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
if (expectedHeader.length !== actualHeader.length) {
// If the length is different, it could not be the same
return {
errorCode: 'CHECK_HEADER_NO_STRICT_MATCH',
severity: severity,
message: 'The expected header [' + expectedHeader +
'] has a different column count to the actual header [' + actualHeader +
']'
};
} else {
// no we need to compare field by field because the expected array could be an array of arrays
// The expected header may contain alternative names for one column.
for (let i = 0; i < expectedHeader.length; i++) {
let match = false;
const actualVal = actualHeader[i];
let expectedVal = expectedHeader[i];
if (Array.isArray(expectedVal)) {
for (let j = 0; j < expectedVal.length; j++) {
if (actualVal === expectedVal[j]) {
match = true;
}
}
} else {
if (actualVal === expectedVal) {
match = true;
}
}
if (!match) {
return {
errorCode: 'CHECK_HEADER_NO_STRICT_MATCH',
severity: severity,
message: 'The expected header [' + expectedHeader +
'] does not match the actual header [' +
actualHeader +
']'
};
}
}
}
};
} | javascript | function getStrictCheck(expectedHeader, caseSensitive, severity) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
if (expectedHeader.length !== actualHeader.length) {
// If the length is different, it could not be the same
return {
errorCode: 'CHECK_HEADER_NO_STRICT_MATCH',
severity: severity,
message: 'The expected header [' + expectedHeader +
'] has a different column count to the actual header [' + actualHeader +
']'
};
} else {
// no we need to compare field by field because the expected array could be an array of arrays
// The expected header may contain alternative names for one column.
for (let i = 0; i < expectedHeader.length; i++) {
let match = false;
const actualVal = actualHeader[i];
let expectedVal = expectedHeader[i];
if (Array.isArray(expectedVal)) {
for (let j = 0; j < expectedVal.length; j++) {
if (actualVal === expectedVal[j]) {
match = true;
}
}
} else {
if (actualVal === expectedVal) {
match = true;
}
}
if (!match) {
return {
errorCode: 'CHECK_HEADER_NO_STRICT_MATCH',
severity: severity,
message: 'The expected header [' + expectedHeader +
'] does not match the actual header [' +
actualHeader +
']'
};
}
}
}
};
} | [
"function",
"getStrictCheck",
"(",
"expectedHeader",
",",
"caseSensitive",
",",
"severity",
")",
"{",
"return",
"function",
"(",
"content",
")",
"{",
"let",
"actualHeader",
";",
"if",
"(",
"caseSensitive",
")",
"{",
"actualHeader",
"=",
"content",
";",
"}",
"else",
"{",
"actualHeader",
"=",
"arrayToUpperCase",
"(",
"content",
")",
";",
"expectedHeader",
"=",
"arrayToUpperCase",
"(",
"expectedHeader",
")",
";",
"}",
"if",
"(",
"expectedHeader",
".",
"length",
"!==",
"actualHeader",
".",
"length",
")",
"{",
"// If the length is different, it could not be the same",
"return",
"{",
"errorCode",
":",
"'CHECK_HEADER_NO_STRICT_MATCH'",
",",
"severity",
":",
"severity",
",",
"message",
":",
"'The expected header ['",
"+",
"expectedHeader",
"+",
"'] has a different column count to the actual header ['",
"+",
"actualHeader",
"+",
"']'",
"}",
";",
"}",
"else",
"{",
"// no we need to compare field by field because the expected array could be an array of arrays",
"// The expected header may contain alternative names for one column.",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"expectedHeader",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"match",
"=",
"false",
";",
"const",
"actualVal",
"=",
"actualHeader",
"[",
"i",
"]",
";",
"let",
"expectedVal",
"=",
"expectedHeader",
"[",
"i",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"expectedVal",
")",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"expectedVal",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"actualVal",
"===",
"expectedVal",
"[",
"j",
"]",
")",
"{",
"match",
"=",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"actualVal",
"===",
"expectedVal",
")",
"{",
"match",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"{",
"errorCode",
":",
"'CHECK_HEADER_NO_STRICT_MATCH'",
",",
"severity",
":",
"severity",
",",
"message",
":",
"'The expected header ['",
"+",
"expectedHeader",
"+",
"'] does not match the actual header ['",
"+",
"actualHeader",
"+",
"']'",
"}",
";",
"}",
"}",
"}",
"}",
";",
"}"
]
| returns the Strict header check
@param expectedHeader The expected header | [
"returns",
"the",
"Strict",
"header",
"check"
]
| 4baadc7782b94986abf947267a79d7328aebba18 | https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L277-L328 |
40,403 | Kronos-Integration/kronos-interceptor-line-header | src/line-header.js | getMissingColumnCheck | function getMissingColumnCheck(expectedHeader, caseSensitive, severity) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
// the header must have all the expected columns but may have more
let err = _missingColumns(expectedHeader, actualHeader);
if (err) {
return {
errorCode: 'CHECK_HEADER_MISSING_COLUMNS',
severity: severity,
message: 'The following columns are missing in the header: [' + err.join() + ']'
};
}
};
} | javascript | function getMissingColumnCheck(expectedHeader, caseSensitive, severity) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
// the header must have all the expected columns but may have more
let err = _missingColumns(expectedHeader, actualHeader);
if (err) {
return {
errorCode: 'CHECK_HEADER_MISSING_COLUMNS',
severity: severity,
message: 'The following columns are missing in the header: [' + err.join() + ']'
};
}
};
} | [
"function",
"getMissingColumnCheck",
"(",
"expectedHeader",
",",
"caseSensitive",
",",
"severity",
")",
"{",
"return",
"function",
"(",
"content",
")",
"{",
"let",
"actualHeader",
";",
"if",
"(",
"caseSensitive",
")",
"{",
"actualHeader",
"=",
"content",
";",
"}",
"else",
"{",
"actualHeader",
"=",
"arrayToUpperCase",
"(",
"content",
")",
";",
"expectedHeader",
"=",
"arrayToUpperCase",
"(",
"expectedHeader",
")",
";",
"}",
"// the header must have all the expected columns but may have more",
"let",
"err",
"=",
"_missingColumns",
"(",
"expectedHeader",
",",
"actualHeader",
")",
";",
"if",
"(",
"err",
")",
"{",
"return",
"{",
"errorCode",
":",
"'CHECK_HEADER_MISSING_COLUMNS'",
",",
"severity",
":",
"severity",
",",
"message",
":",
"'The following columns are missing in the header: ['",
"+",
"err",
".",
"join",
"(",
")",
"+",
"']'",
"}",
";",
"}",
"}",
";",
"}"
]
| Creates the missing column check
@param expectedHeader The expected header
@param caseSensitive Is the header case sensitive
@param severity The severity if the check fails | [
"Creates",
"the",
"missing",
"column",
"check"
]
| 4baadc7782b94986abf947267a79d7328aebba18 | https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L420-L441 |
40,404 | Kronos-Integration/kronos-interceptor-line-header | src/line-header.js | getMandatoryColumnCheck | function getMandatoryColumnCheck(mandatoryColumns, severity) {
/**
* @param the coluns found and matched.
*/
return function (foundColumns) {
// the header must have all the expected columns but may have more
let err = _missingColumns(mandatoryColumns, foundColumns);
if (err) {
return {
errorCode: 'CHECK_HEADER_MANDATORY_COLUMNS',
severity: severity,
message: 'The following columns are missing in the header and are mandatory: [' + err.join() + ']'
};
}
};
} | javascript | function getMandatoryColumnCheck(mandatoryColumns, severity) {
/**
* @param the coluns found and matched.
*/
return function (foundColumns) {
// the header must have all the expected columns but may have more
let err = _missingColumns(mandatoryColumns, foundColumns);
if (err) {
return {
errorCode: 'CHECK_HEADER_MANDATORY_COLUMNS',
severity: severity,
message: 'The following columns are missing in the header and are mandatory: [' + err.join() + ']'
};
}
};
} | [
"function",
"getMandatoryColumnCheck",
"(",
"mandatoryColumns",
",",
"severity",
")",
"{",
"/**\n\t * @param the coluns found and matched.\n\t */",
"return",
"function",
"(",
"foundColumns",
")",
"{",
"// the header must have all the expected columns but may have more",
"let",
"err",
"=",
"_missingColumns",
"(",
"mandatoryColumns",
",",
"foundColumns",
")",
";",
"if",
"(",
"err",
")",
"{",
"return",
"{",
"errorCode",
":",
"'CHECK_HEADER_MANDATORY_COLUMNS'",
",",
"severity",
":",
"severity",
",",
"message",
":",
"'The following columns are missing in the header and are mandatory: ['",
"+",
"err",
".",
"join",
"(",
")",
"+",
"']'",
"}",
";",
"}",
"}",
";",
"}"
]
| Creates the mandatory column check. This is every time case sensitive as we used the associated column names.
@param mandatoryColumns The mandatory columns. BUT these are the associated fieldnames, not the original column names
@param severity The severity if the check fails | [
"Creates",
"the",
"mandatory",
"column",
"check",
".",
"This",
"is",
"every",
"time",
"case",
"sensitive",
"as",
"we",
"used",
"the",
"associated",
"column",
"names",
"."
]
| 4baadc7782b94986abf947267a79d7328aebba18 | https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L449-L466 |
40,405 | panta82/readdir-plus | lib/vars.js | ReaddirPlusFile | function ReaddirPlusFile(source) {
/**
* File name. Eg. "file.txt"
* @type {string}
*/
this.name = null;
/**
* Full path. Eg. "/home/myname/path/to/directory/subdir/file.txt"
* @type {string}
*/
this.path = null;
/**
* Relative path, based on the directory you submitted to readdir. Eg. "subdir/file.txt"
* @type {string}
*/
this.relativePath = null;
/**
* File name without extension. Eg. "file"
* @type {string}
*/
this.basename = null;
/**
* Extension with leading dot. Eg. ".txt"
* @type {string}
*/
this.extension = null;
/**
* One of vars.FILE_TYPES
* @type {FILE_TYPES}
*/
this.type = null;
/**
* File or directory stats
* @type {fs.Stats}
*/
this.stat = null;
Object.assign(this, source);
} | javascript | function ReaddirPlusFile(source) {
/**
* File name. Eg. "file.txt"
* @type {string}
*/
this.name = null;
/**
* Full path. Eg. "/home/myname/path/to/directory/subdir/file.txt"
* @type {string}
*/
this.path = null;
/**
* Relative path, based on the directory you submitted to readdir. Eg. "subdir/file.txt"
* @type {string}
*/
this.relativePath = null;
/**
* File name without extension. Eg. "file"
* @type {string}
*/
this.basename = null;
/**
* Extension with leading dot. Eg. ".txt"
* @type {string}
*/
this.extension = null;
/**
* One of vars.FILE_TYPES
* @type {FILE_TYPES}
*/
this.type = null;
/**
* File or directory stats
* @type {fs.Stats}
*/
this.stat = null;
Object.assign(this, source);
} | [
"function",
"ReaddirPlusFile",
"(",
"source",
")",
"{",
"/**\n\t * File name. Eg. \"file.txt\"\n\t * @type {string}\n\t */",
"this",
".",
"name",
"=",
"null",
";",
"/**\n\t * Full path. Eg. \"/home/myname/path/to/directory/subdir/file.txt\"\n\t * @type {string}\n\t */",
"this",
".",
"path",
"=",
"null",
";",
"/**\n\t * Relative path, based on the directory you submitted to readdir. Eg. \"subdir/file.txt\"\n\t * @type {string}\n\t */",
"this",
".",
"relativePath",
"=",
"null",
";",
"/**\n\t * File name without extension. Eg. \"file\"\n\t * @type {string}\n\t */",
"this",
".",
"basename",
"=",
"null",
";",
"/**\n\t * Extension with leading dot. Eg. \".txt\"\n\t * @type {string}\n\t */",
"this",
".",
"extension",
"=",
"null",
";",
"/**\n\t * One of vars.FILE_TYPES\n\t * @type {FILE_TYPES}\n\t */",
"this",
".",
"type",
"=",
"null",
";",
"/**\n\t * File or directory stats\n\t * @type {fs.Stats}\n\t */",
"this",
".",
"stat",
"=",
"null",
";",
"Object",
".",
"assign",
"(",
"this",
",",
"source",
")",
";",
"}"
]
| File data returned by readdirPlus
@param source | [
"File",
"data",
"returned",
"by",
"readdirPlus"
]
| a3c0dc9356ebbcdfebf7565286709984b0770720 | https://github.com/panta82/readdir-plus/blob/a3c0dc9356ebbcdfebf7565286709984b0770720/lib/vars.js#L225-L269 |
40,406 | jonschlinkert/to-exports | index.js | toExports | function toExports(dir, patterns, recurse, options, fn) {
if (arguments.length === 1 && !isGlob(dir)) {
var key = 'toExports:' + dir;
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var result = lookup(dir, false, {}).reduce(function (res, fp) {
if (filter(fp, fn)) {
res[basename(fp)] = read(fp, fn);
}
return res;
}, {});
return (cache[key] = result);
}
return explode.apply(explode, arguments);
} | javascript | function toExports(dir, patterns, recurse, options, fn) {
if (arguments.length === 1 && !isGlob(dir)) {
var key = 'toExports:' + dir;
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var result = lookup(dir, false, {}).reduce(function (res, fp) {
if (filter(fp, fn)) {
res[basename(fp)] = read(fp, fn);
}
return res;
}, {});
return (cache[key] = result);
}
return explode.apply(explode, arguments);
} | [
"function",
"toExports",
"(",
"dir",
",",
"patterns",
",",
"recurse",
",",
"options",
",",
"fn",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
"&&",
"!",
"isGlob",
"(",
"dir",
")",
")",
"{",
"var",
"key",
"=",
"'toExports:'",
"+",
"dir",
";",
"if",
"(",
"cache",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"cache",
"[",
"key",
"]",
";",
"}",
"var",
"result",
"=",
"lookup",
"(",
"dir",
",",
"false",
",",
"{",
"}",
")",
".",
"reduce",
"(",
"function",
"(",
"res",
",",
"fp",
")",
"{",
"if",
"(",
"filter",
"(",
"fp",
",",
"fn",
")",
")",
"{",
"res",
"[",
"basename",
"(",
"fp",
")",
"]",
"=",
"read",
"(",
"fp",
",",
"fn",
")",
";",
"}",
"return",
"res",
";",
"}",
",",
"{",
"}",
")",
";",
"return",
"(",
"cache",
"[",
"key",
"]",
"=",
"result",
")",
";",
"}",
"return",
"explode",
".",
"apply",
"(",
"explode",
",",
"arguments",
")",
";",
"}"
]
| Export files from the give `directory` filtering the
results with
@param {String} `directory` Use `__dirname` for the immediate directory.
@param {String|Array} `patterns` Glob patterns to use for matching.
@param {Boolean} `recurse` Pass `true` to recurse deeper than the current directory.
@param {String} `options`
@param {Function} `fn` Callback for filtering.
@return {String} | [
"Export",
"files",
"from",
"the",
"give",
"directory",
"filtering",
"the",
"results",
"with"
]
| 93471d63094718ca5fd32d99a9abada8008f1d73 | https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L36-L53 |
40,407 | jonschlinkert/to-exports | index.js | lookup | function lookup(dir, recurse) {
if (typeof dir !== 'string') {
throw new Error('export-files expects a string as the first argument.');
}
var key = 'lookup:' + dir + ('' + recurse);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var files = fs.readdirSync(dir);
var len = files.length;
var res = [];
if (recurse === false) return map(files, resolve(dir));
while (len--) {
var fp = path.resolve(dir, files[len]);
if (isDir(fp)) {
res.push.apply(res, lookup(fp, recurse));
} else {
res.push(fp);
}
}
return (cache[key] = res);
} | javascript | function lookup(dir, recurse) {
if (typeof dir !== 'string') {
throw new Error('export-files expects a string as the first argument.');
}
var key = 'lookup:' + dir + ('' + recurse);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var files = fs.readdirSync(dir);
var len = files.length;
var res = [];
if (recurse === false) return map(files, resolve(dir));
while (len--) {
var fp = path.resolve(dir, files[len]);
if (isDir(fp)) {
res.push.apply(res, lookup(fp, recurse));
} else {
res.push(fp);
}
}
return (cache[key] = res);
} | [
"function",
"lookup",
"(",
"dir",
",",
"recurse",
")",
"{",
"if",
"(",
"typeof",
"dir",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'export-files expects a string as the first argument.'",
")",
";",
"}",
"var",
"key",
"=",
"'lookup:'",
"+",
"dir",
"+",
"(",
"''",
"+",
"recurse",
")",
";",
"if",
"(",
"cache",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"cache",
"[",
"key",
"]",
";",
"}",
"var",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
";",
"var",
"len",
"=",
"files",
".",
"length",
";",
"var",
"res",
"=",
"[",
"]",
";",
"if",
"(",
"recurse",
"===",
"false",
")",
"return",
"map",
"(",
"files",
",",
"resolve",
"(",
"dir",
")",
")",
";",
"while",
"(",
"len",
"--",
")",
"{",
"var",
"fp",
"=",
"path",
".",
"resolve",
"(",
"dir",
",",
"files",
"[",
"len",
"]",
")",
";",
"if",
"(",
"isDir",
"(",
"fp",
")",
")",
"{",
"res",
".",
"push",
".",
"apply",
"(",
"res",
",",
"lookup",
"(",
"fp",
",",
"recurse",
")",
")",
";",
"}",
"else",
"{",
"res",
".",
"push",
"(",
"fp",
")",
";",
"}",
"}",
"return",
"(",
"cache",
"[",
"key",
"]",
"=",
"res",
")",
";",
"}"
]
| Recursively read directories, starting with the given `dir`.
@param {String} `dir`
@param {Boolean} `recurse` Should the function recurse?
@return {Array} Returns an array of files. | [
"Recursively",
"read",
"directories",
"starting",
"with",
"the",
"given",
"dir",
"."
]
| 93471d63094718ca5fd32d99a9abada8008f1d73 | https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L94-L119 |
40,408 | jonschlinkert/to-exports | index.js | renameKey | function renameKey(fp, opts) {
if (opts && opts.renameKey) {
return opts.renameKey(fp, opts);
}
return basename(fp);
} | javascript | function renameKey(fp, opts) {
if (opts && opts.renameKey) {
return opts.renameKey(fp, opts);
}
return basename(fp);
} | [
"function",
"renameKey",
"(",
"fp",
",",
"opts",
")",
"{",
"if",
"(",
"opts",
"&&",
"opts",
".",
"renameKey",
")",
"{",
"return",
"opts",
".",
"renameKey",
"(",
"fp",
",",
"opts",
")",
";",
"}",
"return",
"basename",
"(",
"fp",
")",
";",
"}"
]
| Rename object keys with a custom function.
If no function is passed, the basname is
returned. | [
"Rename",
"object",
"keys",
"with",
"a",
"custom",
"function",
".",
"If",
"no",
"function",
"is",
"passed",
"the",
"basname",
"is",
"returned",
"."
]
| 93471d63094718ca5fd32d99a9abada8008f1d73 | https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L127-L132 |
40,409 | jonschlinkert/to-exports | index.js | read | function read(fp, opts, fn) {
opts = opts || {};
opts.encoding = opts.encoding || 'utf8';
if (opts.read) {
return opts.read(fp, opts);
} else if (fn) {
return fn(fp, opts);
}
if (endsWith(fp, '.js')) {
return tryRequire(fp);
} else {
var str = tryCatch(fs.readFileSync, fp, opts);
if (endsWith(fp, '.json')) {
return tryCatch(JSON.parse, str);
}
return str;
}
} | javascript | function read(fp, opts, fn) {
opts = opts || {};
opts.encoding = opts.encoding || 'utf8';
if (opts.read) {
return opts.read(fp, opts);
} else if (fn) {
return fn(fp, opts);
}
if (endsWith(fp, '.js')) {
return tryRequire(fp);
} else {
var str = tryCatch(fs.readFileSync, fp, opts);
if (endsWith(fp, '.json')) {
return tryCatch(JSON.parse, str);
}
return str;
}
} | [
"function",
"read",
"(",
"fp",
",",
"opts",
",",
"fn",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"opts",
".",
"encoding",
"=",
"opts",
".",
"encoding",
"||",
"'utf8'",
";",
"if",
"(",
"opts",
".",
"read",
")",
"{",
"return",
"opts",
".",
"read",
"(",
"fp",
",",
"opts",
")",
";",
"}",
"else",
"if",
"(",
"fn",
")",
"{",
"return",
"fn",
"(",
"fp",
",",
"opts",
")",
";",
"}",
"if",
"(",
"endsWith",
"(",
"fp",
",",
"'.js'",
")",
")",
"{",
"return",
"tryRequire",
"(",
"fp",
")",
";",
"}",
"else",
"{",
"var",
"str",
"=",
"tryCatch",
"(",
"fs",
".",
"readFileSync",
",",
"fp",
",",
"opts",
")",
";",
"if",
"(",
"endsWith",
"(",
"fp",
",",
"'.json'",
")",
")",
"{",
"return",
"tryCatch",
"(",
"JSON",
".",
"parse",
",",
"str",
")",
";",
"}",
"return",
"str",
";",
"}",
"}"
]
| Read or require the given file with `opts` | [
"Read",
"or",
"require",
"the",
"given",
"file",
"with",
"opts"
]
| 93471d63094718ca5fd32d99a9abada8008f1d73 | https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L146-L165 |
40,410 | noderaider/repackage | jspm_packages/npm/[email protected]/lib/types/validators.js | isBinding | function isBinding(node, parent) {
var keys = _retrievers.getBindingIdentifiers.keys[parent.type];
if (keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = parent[key];
if (Array.isArray(val)) {
if (val.indexOf(node) >= 0) return true;
} else {
if (val === node) return true;
}
}
}
return false;
} | javascript | function isBinding(node, parent) {
var keys = _retrievers.getBindingIdentifiers.keys[parent.type];
if (keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = parent[key];
if (Array.isArray(val)) {
if (val.indexOf(node) >= 0) return true;
} else {
if (val === node) return true;
}
}
}
return false;
} | [
"function",
"isBinding",
"(",
"node",
",",
"parent",
")",
"{",
"var",
"keys",
"=",
"_retrievers",
".",
"getBindingIdentifiers",
".",
"keys",
"[",
"parent",
".",
"type",
"]",
";",
"if",
"(",
"keys",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"var",
"val",
"=",
"parent",
"[",
"key",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"if",
"(",
"val",
".",
"indexOf",
"(",
"node",
")",
">=",
"0",
")",
"return",
"true",
";",
"}",
"else",
"{",
"if",
"(",
"val",
"===",
"node",
")",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
]
| Check if the input `node` is a binding identifier. | [
"Check",
"if",
"the",
"input",
"node",
"is",
"a",
"binding",
"identifier",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L37-L52 |
40,411 | noderaider/repackage | jspm_packages/npm/[email protected]/lib/types/validators.js | isSpecifierDefault | function isSpecifierDefault(specifier) {
return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" });
} | javascript | function isSpecifierDefault(specifier) {
return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" });
} | [
"function",
"isSpecifierDefault",
"(",
"specifier",
")",
"{",
"return",
"t",
".",
"isImportDefaultSpecifier",
"(",
"specifier",
")",
"||",
"t",
".",
"isIdentifier",
"(",
"specifier",
".",
"imported",
"||",
"specifier",
".",
"exported",
",",
"{",
"name",
":",
"\"default\"",
"}",
")",
";",
"}"
]
| Check if the input `specifier` is a `default` import or export. | [
"Check",
"if",
"the",
"input",
"specifier",
"is",
"a",
"default",
"import",
"or",
"export",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L216-L218 |
40,412 | noderaider/repackage | jspm_packages/npm/[email protected]/lib/types/validators.js | isScope | function isScope(node, parent) {
if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
return false;
}
return t.isScopable(node);
} | javascript | function isScope(node, parent) {
if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
return false;
}
return t.isScopable(node);
} | [
"function",
"isScope",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"t",
".",
"isBlockStatement",
"(",
"node",
")",
"&&",
"t",
".",
"isFunction",
"(",
"parent",
",",
"{",
"body",
":",
"node",
"}",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"t",
".",
"isScopable",
"(",
"node",
")",
";",
"}"
]
| Check if the input `node` is a scope. | [
"Check",
"if",
"the",
"input",
"node",
"is",
"a",
"scope",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L224-L230 |
40,413 | noderaider/repackage | jspm_packages/npm/[email protected]/lib/types/validators.js | isImmutable | function isImmutable(node) {
if (t.isType(node.type, "Immutable")) return true;
if (t.isLiteral(node)) {
if (node.regex) {
// regexs are mutable
return false;
} else {
// immutable!
return true;
}
} else if (t.isIdentifier(node)) {
if (node.name === "undefined") {
// immutable!
return true;
} else {
// no idea...
return false;
}
}
return false;
} | javascript | function isImmutable(node) {
if (t.isType(node.type, "Immutable")) return true;
if (t.isLiteral(node)) {
if (node.regex) {
// regexs are mutable
return false;
} else {
// immutable!
return true;
}
} else if (t.isIdentifier(node)) {
if (node.name === "undefined") {
// immutable!
return true;
} else {
// no idea...
return false;
}
}
return false;
} | [
"function",
"isImmutable",
"(",
"node",
")",
"{",
"if",
"(",
"t",
".",
"isType",
"(",
"node",
".",
"type",
",",
"\"Immutable\"",
")",
")",
"return",
"true",
";",
"if",
"(",
"t",
".",
"isLiteral",
"(",
"node",
")",
")",
"{",
"if",
"(",
"node",
".",
"regex",
")",
"{",
"// regexs are mutable",
"return",
"false",
";",
"}",
"else",
"{",
"// immutable!",
"return",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"t",
".",
"isIdentifier",
"(",
"node",
")",
")",
"{",
"if",
"(",
"node",
".",
"name",
"===",
"\"undefined\"",
")",
"{",
"// immutable!",
"return",
"true",
";",
"}",
"else",
"{",
"// no idea...",
"return",
"false",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Check if the input `node` is definitely immutable. | [
"Check",
"if",
"the",
"input",
"node",
"is",
"definitely",
"immutable",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L236-L258 |
40,414 | kevoree/kevoree-js | tools/kevoree-kevscript/lib/KevScript.js | function (data, ctxModel, ctxVars) {
const options = xtend(this.options, { ctxVars, logger: this.logger });
const parser = new kevs.Parser();
const ast = parser.parse(data);
if (ast.type !== 'kevScript') {
const err = new Error('Unable to parse script');
err.parser = ast;
err.warnings = options.warnings || [];
return Promise.reject(err);
} else {
return interpreter(ast, ctxModel, options)
.then(({ error, warnings, model }) => {
if (error) {
error.warnings = warnings;
throw error;
} else {
return { model, warnings };
}
});
}
} | javascript | function (data, ctxModel, ctxVars) {
const options = xtend(this.options, { ctxVars, logger: this.logger });
const parser = new kevs.Parser();
const ast = parser.parse(data);
if (ast.type !== 'kevScript') {
const err = new Error('Unable to parse script');
err.parser = ast;
err.warnings = options.warnings || [];
return Promise.reject(err);
} else {
return interpreter(ast, ctxModel, options)
.then(({ error, warnings, model }) => {
if (error) {
error.warnings = warnings;
throw error;
} else {
return { model, warnings };
}
});
}
} | [
"function",
"(",
"data",
",",
"ctxModel",
",",
"ctxVars",
")",
"{",
"const",
"options",
"=",
"xtend",
"(",
"this",
".",
"options",
",",
"{",
"ctxVars",
",",
"logger",
":",
"this",
".",
"logger",
"}",
")",
";",
"const",
"parser",
"=",
"new",
"kevs",
".",
"Parser",
"(",
")",
";",
"const",
"ast",
"=",
"parser",
".",
"parse",
"(",
"data",
")",
";",
"if",
"(",
"ast",
".",
"type",
"!==",
"'kevScript'",
")",
"{",
"const",
"err",
"=",
"new",
"Error",
"(",
"'Unable to parse script'",
")",
";",
"err",
".",
"parser",
"=",
"ast",
";",
"err",
".",
"warnings",
"=",
"options",
".",
"warnings",
"||",
"[",
"]",
";",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"return",
"interpreter",
"(",
"ast",
",",
"ctxModel",
",",
"options",
")",
".",
"then",
"(",
"(",
"{",
"error",
",",
"warnings",
",",
"model",
"}",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"error",
".",
"warnings",
"=",
"warnings",
";",
"throw",
"error",
";",
"}",
"else",
"{",
"return",
"{",
"model",
",",
"warnings",
"}",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Parses given KevScript source-code in parameter 'data' and returns a ContainerRoot.
@param {String} data string
@param {Object|Function} [ctxModel] a model to "start" on (in order not to create a model from scratch)
@param {Object|Function} [ctxVars] context variables to be accessible from the KevScript
@returns {Promise<{ ContainerRoot, Array<Warning>}} promise
@throws Error on SyntaxError and on source code validity and such | [
"Parses",
"given",
"KevScript",
"source",
"-",
"code",
"in",
"parameter",
"data",
"and",
"returns",
"a",
"ContainerRoot",
"."
]
| 7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd | https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/KevScript.js#L36-L57 |
|
40,415 | sumeetdas/Meow | lib/utils.js | setPropertyVal | function setPropertyVal (pObj, pProp, pNewVal) {
if (typeof pProp === 'string') {
pProp = pProp || '';
pProp = pProp.split('.');
}
if (pProp.length > 1) {
var prop = pProp.shift();
pObj[prop] = (typeof pObj[prop] !== 'undefined'
|| typeof pObj[prop] !== 'null') ? pObj[prop] : {};
setPropertyVal(pObj[prop], pProp, pNewVal);
} else {
pObj[ pProp[0] ] = pNewVal;
}
} | javascript | function setPropertyVal (pObj, pProp, pNewVal) {
if (typeof pProp === 'string') {
pProp = pProp || '';
pProp = pProp.split('.');
}
if (pProp.length > 1) {
var prop = pProp.shift();
pObj[prop] = (typeof pObj[prop] !== 'undefined'
|| typeof pObj[prop] !== 'null') ? pObj[prop] : {};
setPropertyVal(pObj[prop], pProp, pNewVal);
} else {
pObj[ pProp[0] ] = pNewVal;
}
} | [
"function",
"setPropertyVal",
"(",
"pObj",
",",
"pProp",
",",
"pNewVal",
")",
"{",
"if",
"(",
"typeof",
"pProp",
"===",
"'string'",
")",
"{",
"pProp",
"=",
"pProp",
"||",
"''",
";",
"pProp",
"=",
"pProp",
".",
"split",
"(",
"'.'",
")",
";",
"}",
"if",
"(",
"pProp",
".",
"length",
">",
"1",
")",
"{",
"var",
"prop",
"=",
"pProp",
".",
"shift",
"(",
")",
";",
"pObj",
"[",
"prop",
"]",
"=",
"(",
"typeof",
"pObj",
"[",
"prop",
"]",
"!==",
"'undefined'",
"||",
"typeof",
"pObj",
"[",
"prop",
"]",
"!==",
"'null'",
")",
"?",
"pObj",
"[",
"prop",
"]",
":",
"{",
"}",
";",
"setPropertyVal",
"(",
"pObj",
"[",
"prop",
"]",
",",
"pProp",
",",
"pNewVal",
")",
";",
"}",
"else",
"{",
"pObj",
"[",
"pProp",
"[",
"0",
"]",
"]",
"=",
"pNewVal",
";",
"}",
"}"
]
| Utility method to set property value of an object by using the dot notation of the affected property
For instance, for the following object:
var someObject =
{
animals: {
cow: true,
cat: false
}
};
If we want to change the property val of 'cat', we can use this function to do so:
setPropertyVal (someObject, 'animals.cat', true);
@param pObj Object whose property value needs to be updated
@param pProp dot notation property value, e.g. 'animal.cat'
@param pNewVal new value with which the property @param pProp will be updated with | [
"Utility",
"method",
"to",
"set",
"property",
"value",
"of",
"an",
"object",
"by",
"using",
"the",
"dot",
"notation",
"of",
"the",
"affected",
"property"
]
| 965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9 | https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/utils.js#L32-L50 |
40,416 | sumeetdas/Meow | lib/utils.js | getMetaData | function getMetaData (data) {
if (typeof data !== 'string') {
throw new MeowError ('data is not a string');
}
data = data || '';
data = data.split('\n');
if (('' + data[0]).trim() !== '<!--') {
throw new MeowError ("Incorrect format : Missing '<!--' in the beginning of the file");
}
var index = 1, metaData = [], dataLen = data.length;
while (index < dataLen && ('' + data[index]).trim() !== '-->' ) {
metaData.push(data[index]);
index++;
}
if (index == dataLen) {
throw new MeowError ("Incorrect format : Missing closing '-->' for metadata comment");
}
metaData = metaData.join('\n');
metaData = yaml.parse(metaData);
if (!metaData.tags || typeof metaData.tags !== 'string')
{
metaData.tags = '';
}
metaData.tags = metaData.tags.split(',');
metaData.tags = _.map(metaData.tags, function (tag) { return tag.trim(); });
if (!metaData.keywords || typeof metaData.keywords !== 'string')
{
metaData.keywords = '';
}
metaData.keywords = metaData.keywords.split(',');
metaData.keywords = _.map(metaData.keywords, function (tag) { return tag.trim(); });
return metaData;
} | javascript | function getMetaData (data) {
if (typeof data !== 'string') {
throw new MeowError ('data is not a string');
}
data = data || '';
data = data.split('\n');
if (('' + data[0]).trim() !== '<!--') {
throw new MeowError ("Incorrect format : Missing '<!--' in the beginning of the file");
}
var index = 1, metaData = [], dataLen = data.length;
while (index < dataLen && ('' + data[index]).trim() !== '-->' ) {
metaData.push(data[index]);
index++;
}
if (index == dataLen) {
throw new MeowError ("Incorrect format : Missing closing '-->' for metadata comment");
}
metaData = metaData.join('\n');
metaData = yaml.parse(metaData);
if (!metaData.tags || typeof metaData.tags !== 'string')
{
metaData.tags = '';
}
metaData.tags = metaData.tags.split(',');
metaData.tags = _.map(metaData.tags, function (tag) { return tag.trim(); });
if (!metaData.keywords || typeof metaData.keywords !== 'string')
{
metaData.keywords = '';
}
metaData.keywords = metaData.keywords.split(',');
metaData.keywords = _.map(metaData.keywords, function (tag) { return tag.trim(); });
return metaData;
} | [
"function",
"getMetaData",
"(",
"data",
")",
"{",
"if",
"(",
"typeof",
"data",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"MeowError",
"(",
"'data is not a string'",
")",
";",
"}",
"data",
"=",
"data",
"||",
"''",
";",
"data",
"=",
"data",
".",
"split",
"(",
"'\\n'",
")",
";",
"if",
"(",
"(",
"''",
"+",
"data",
"[",
"0",
"]",
")",
".",
"trim",
"(",
")",
"!==",
"'<!--'",
")",
"{",
"throw",
"new",
"MeowError",
"(",
"\"Incorrect format : Missing '<!--' in the beginning of the file\"",
")",
";",
"}",
"var",
"index",
"=",
"1",
",",
"metaData",
"=",
"[",
"]",
",",
"dataLen",
"=",
"data",
".",
"length",
";",
"while",
"(",
"index",
"<",
"dataLen",
"&&",
"(",
"''",
"+",
"data",
"[",
"index",
"]",
")",
".",
"trim",
"(",
")",
"!==",
"'-->'",
")",
"{",
"metaData",
".",
"push",
"(",
"data",
"[",
"index",
"]",
")",
";",
"index",
"++",
";",
"}",
"if",
"(",
"index",
"==",
"dataLen",
")",
"{",
"throw",
"new",
"MeowError",
"(",
"\"Incorrect format : Missing closing '-->' for metadata comment\"",
")",
";",
"}",
"metaData",
"=",
"metaData",
".",
"join",
"(",
"'\\n'",
")",
";",
"metaData",
"=",
"yaml",
".",
"parse",
"(",
"metaData",
")",
";",
"if",
"(",
"!",
"metaData",
".",
"tags",
"||",
"typeof",
"metaData",
".",
"tags",
"!==",
"'string'",
")",
"{",
"metaData",
".",
"tags",
"=",
"''",
";",
"}",
"metaData",
".",
"tags",
"=",
"metaData",
".",
"tags",
".",
"split",
"(",
"','",
")",
";",
"metaData",
".",
"tags",
"=",
"_",
".",
"map",
"(",
"metaData",
".",
"tags",
",",
"function",
"(",
"tag",
")",
"{",
"return",
"tag",
".",
"trim",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"metaData",
".",
"keywords",
"||",
"typeof",
"metaData",
".",
"keywords",
"!==",
"'string'",
")",
"{",
"metaData",
".",
"keywords",
"=",
"''",
";",
"}",
"metaData",
".",
"keywords",
"=",
"metaData",
".",
"keywords",
".",
"split",
"(",
"','",
")",
";",
"metaData",
".",
"keywords",
"=",
"_",
".",
"map",
"(",
"metaData",
".",
"keywords",
",",
"function",
"(",
"tag",
")",
"{",
"return",
"tag",
".",
"trim",
"(",
")",
";",
"}",
")",
";",
"return",
"metaData",
";",
"}"
]
| Retrieves metadata for a given meow format blog post. This metadata will further be cached into 'posts'.
@param data The meow format blog post; must be a string
@returns {Object}
Typical format would be :
{
title: (title)
published-date: (published-date)
tags: [tagArray]
} | [
"Retrieves",
"metadata",
"for",
"a",
"given",
"meow",
"format",
"blog",
"post",
".",
"This",
"metadata",
"will",
"further",
"be",
"cached",
"into",
"posts",
"."
]
| 965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9 | https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/utils.js#L63-L103 |
40,417 | sumeetdas/Meow | lib/utils.js | generateSlug | function generateSlug (title) {
if (typeof title !== 'string') {
throw new MeowError ('title is not a string');
}
title = title || '';
title = title.toLocaleLowerCase().replace(/[\W]/g, '-').replace(/[\-]{2,}/g, '-');
return title;
} | javascript | function generateSlug (title) {
if (typeof title !== 'string') {
throw new MeowError ('title is not a string');
}
title = title || '';
title = title.toLocaleLowerCase().replace(/[\W]/g, '-').replace(/[\-]{2,}/g, '-');
return title;
} | [
"function",
"generateSlug",
"(",
"title",
")",
"{",
"if",
"(",
"typeof",
"title",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"MeowError",
"(",
"'title is not a string'",
")",
";",
"}",
"title",
"=",
"title",
"||",
"''",
";",
"title",
"=",
"title",
".",
"toLocaleLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"[\\W]",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"[\\-]{2,}",
"/",
"g",
",",
"'-'",
")",
";",
"return",
"title",
";",
"}"
]
| Generates slug for a given title
@param title
@returns {string} slug generated for @param title | [
"Generates",
"slug",
"for",
"a",
"given",
"title"
]
| 965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9 | https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/utils.js#L110-L117 |
40,418 | sumeetdas/Meow | lib/utils.js | sortPostsByPublishedDate | function sortPostsByPublishedDate (pPosts) {
if (! (pPosts instanceof Array) ) {
throw new MeowError ("pPosts is not an array");
}
pPosts.sort(function (pFirst, pSecond) {
pFirst = pFirst || {};
pSecond = pSecond || {};
var pFirstPublishedDate = pFirst['published-date'],
pSecondPublishedDate = pSecond['published-date'];
if (moment(pFirstPublishedDate).isAfter(pSecondPublishedDate)) {
return -1;
}
else if (moment(pFirstPublishedDate).isBefore(pSecondPublishedDate)) {
return 1;
}
else {
return pFirst.title.localeCompare(pSecond.title);
}
});
return pPosts;
} | javascript | function sortPostsByPublishedDate (pPosts) {
if (! (pPosts instanceof Array) ) {
throw new MeowError ("pPosts is not an array");
}
pPosts.sort(function (pFirst, pSecond) {
pFirst = pFirst || {};
pSecond = pSecond || {};
var pFirstPublishedDate = pFirst['published-date'],
pSecondPublishedDate = pSecond['published-date'];
if (moment(pFirstPublishedDate).isAfter(pSecondPublishedDate)) {
return -1;
}
else if (moment(pFirstPublishedDate).isBefore(pSecondPublishedDate)) {
return 1;
}
else {
return pFirst.title.localeCompare(pSecond.title);
}
});
return pPosts;
} | [
"function",
"sortPostsByPublishedDate",
"(",
"pPosts",
")",
"{",
"if",
"(",
"!",
"(",
"pPosts",
"instanceof",
"Array",
")",
")",
"{",
"throw",
"new",
"MeowError",
"(",
"\"pPosts is not an array\"",
")",
";",
"}",
"pPosts",
".",
"sort",
"(",
"function",
"(",
"pFirst",
",",
"pSecond",
")",
"{",
"pFirst",
"=",
"pFirst",
"||",
"{",
"}",
";",
"pSecond",
"=",
"pSecond",
"||",
"{",
"}",
";",
"var",
"pFirstPublishedDate",
"=",
"pFirst",
"[",
"'published-date'",
"]",
",",
"pSecondPublishedDate",
"=",
"pSecond",
"[",
"'published-date'",
"]",
";",
"if",
"(",
"moment",
"(",
"pFirstPublishedDate",
")",
".",
"isAfter",
"(",
"pSecondPublishedDate",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"moment",
"(",
"pFirstPublishedDate",
")",
".",
"isBefore",
"(",
"pSecondPublishedDate",
")",
")",
"{",
"return",
"1",
";",
"}",
"else",
"{",
"return",
"pFirst",
".",
"title",
".",
"localeCompare",
"(",
"pSecond",
".",
"title",
")",
";",
"}",
"}",
")",
";",
"return",
"pPosts",
";",
"}"
]
| This function will order the posts array according to its published date in descending order
@param pPosts object containing cached posts data filed under some category | [
"This",
"function",
"will",
"order",
"the",
"posts",
"array",
"according",
"to",
"its",
"published",
"date",
"in",
"descending",
"order"
]
| 965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9 | https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/utils.js#L123-L145 |
40,419 | sumeetdas/Meow | lib/utils.js | getFilePathRelativeToAppRoot | function getFilePathRelativeToAppRoot (pPath) {
// go to meow-blog directory
var projectBaseDirectory = path.resolve(__dirname, '..');
if (projectBaseDirectory.indexOf('node_modules') !== -1) {
// from meow-blog, go up to node_modules, then go to base directory
projectBaseDirectory = path.resolve(projectBaseDirectory, '..', '..');
}
return path.resolve(projectBaseDirectory, pPath);
} | javascript | function getFilePathRelativeToAppRoot (pPath) {
// go to meow-blog directory
var projectBaseDirectory = path.resolve(__dirname, '..');
if (projectBaseDirectory.indexOf('node_modules') !== -1) {
// from meow-blog, go up to node_modules, then go to base directory
projectBaseDirectory = path.resolve(projectBaseDirectory, '..', '..');
}
return path.resolve(projectBaseDirectory, pPath);
} | [
"function",
"getFilePathRelativeToAppRoot",
"(",
"pPath",
")",
"{",
"// go to meow-blog directory",
"var",
"projectBaseDirectory",
"=",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'..'",
")",
";",
"if",
"(",
"projectBaseDirectory",
".",
"indexOf",
"(",
"'node_modules'",
")",
"!==",
"-",
"1",
")",
"{",
"// from meow-blog, go up to node_modules, then go to base directory",
"projectBaseDirectory",
"=",
"path",
".",
"resolve",
"(",
"projectBaseDirectory",
",",
"'..'",
",",
"'..'",
")",
";",
"}",
"return",
"path",
".",
"resolve",
"(",
"projectBaseDirectory",
",",
"pPath",
")",
";",
"}"
]
| Get file path relative to app root
@param pPath | [
"Get",
"file",
"path",
"relative",
"to",
"app",
"root"
]
| 965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9 | https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/utils.js#L151-L161 |
40,420 | generate/generate-data | generator.js | set | function set(app, prop, val) {
var data = app.cache.data.project;
if (typeof val !== 'undefined') {
data[prop] = val;
} else if (typeof app.cache.data[prop] !== 'undefined') {
data[prop] = app.cache.data[prop];
}
} | javascript | function set(app, prop, val) {
var data = app.cache.data.project;
if (typeof val !== 'undefined') {
data[prop] = val;
} else if (typeof app.cache.data[prop] !== 'undefined') {
data[prop] = app.cache.data[prop];
}
} | [
"function",
"set",
"(",
"app",
",",
"prop",
",",
"val",
")",
"{",
"var",
"data",
"=",
"app",
".",
"cache",
".",
"data",
".",
"project",
";",
"if",
"(",
"typeof",
"val",
"!==",
"'undefined'",
")",
"{",
"data",
"[",
"prop",
"]",
"=",
"val",
";",
"}",
"else",
"if",
"(",
"typeof",
"app",
".",
"cache",
".",
"data",
"[",
"prop",
"]",
"!==",
"'undefined'",
")",
"{",
"data",
"[",
"prop",
"]",
"=",
"app",
".",
"cache",
".",
"data",
"[",
"prop",
"]",
";",
"}",
"}"
]
| Set data values on the `app.cache.data.project` object, which is
merged onto the context at render time and is available in templats
as `project`. | [
"Set",
"data",
"values",
"on",
"the",
"app",
".",
"cache",
".",
"data",
".",
"project",
"object",
"which",
"is",
"merged",
"onto",
"the",
"context",
"at",
"render",
"time",
"and",
"is",
"available",
"in",
"templats",
"as",
"project",
"."
]
| b580b51151773aa2cda8288e489951bdf1af2d47 | https://github.com/generate/generate-data/blob/b580b51151773aa2cda8288e489951bdf1af2d47/generator.js#L58-L65 |
40,421 | joyent/node-sdc-changefeed | lib/publisher.js | assertPublisherOptions | function assertPublisherOptions(options) {
mod_assert.object(options, 'options');
mod_assert.object(options.log, 'options.log');
mod_assert.object(options.moray, 'options.moray');
mod_assert.string(options.moray.bucketName, 'options.moray.bucketName');
mod_assert.optionalObject(options.backoff, 'options.backoff');
mod_assert.optionalObject(options.moray.client, 'options.moray.client');
mod_assert.optionalObject(options.restifyServer, 'options.restifyServer');
if (options.moray.client === undefined || options.moray.client === null) {
mod_assert.string(options.moray.host, 'options.moray.host');
mod_assert.number(options.moray.port, 'options.moray.port');
} else {
mod_assert.equal(options.moray.host, undefined, 'options.moray.host');
mod_assert.equal(options.moray.port, undefined, 'options.moray.port');
}
} | javascript | function assertPublisherOptions(options) {
mod_assert.object(options, 'options');
mod_assert.object(options.log, 'options.log');
mod_assert.object(options.moray, 'options.moray');
mod_assert.string(options.moray.bucketName, 'options.moray.bucketName');
mod_assert.optionalObject(options.backoff, 'options.backoff');
mod_assert.optionalObject(options.moray.client, 'options.moray.client');
mod_assert.optionalObject(options.restifyServer, 'options.restifyServer');
if (options.moray.client === undefined || options.moray.client === null) {
mod_assert.string(options.moray.host, 'options.moray.host');
mod_assert.number(options.moray.port, 'options.moray.port');
} else {
mod_assert.equal(options.moray.host, undefined, 'options.moray.host');
mod_assert.equal(options.moray.port, undefined, 'options.moray.port');
}
} | [
"function",
"assertPublisherOptions",
"(",
"options",
")",
"{",
"mod_assert",
".",
"object",
"(",
"options",
",",
"'options'",
")",
";",
"mod_assert",
".",
"object",
"(",
"options",
".",
"log",
",",
"'options.log'",
")",
";",
"mod_assert",
".",
"object",
"(",
"options",
".",
"moray",
",",
"'options.moray'",
")",
";",
"mod_assert",
".",
"string",
"(",
"options",
".",
"moray",
".",
"bucketName",
",",
"'options.moray.bucketName'",
")",
";",
"mod_assert",
".",
"optionalObject",
"(",
"options",
".",
"backoff",
",",
"'options.backoff'",
")",
";",
"mod_assert",
".",
"optionalObject",
"(",
"options",
".",
"moray",
".",
"client",
",",
"'options.moray.client'",
")",
";",
"mod_assert",
".",
"optionalObject",
"(",
"options",
".",
"restifyServer",
",",
"'options.restifyServer'",
")",
";",
"if",
"(",
"options",
".",
"moray",
".",
"client",
"===",
"undefined",
"||",
"options",
".",
"moray",
".",
"client",
"===",
"null",
")",
"{",
"mod_assert",
".",
"string",
"(",
"options",
".",
"moray",
".",
"host",
",",
"'options.moray.host'",
")",
";",
"mod_assert",
".",
"number",
"(",
"options",
".",
"moray",
".",
"port",
",",
"'options.moray.port'",
")",
";",
"}",
"else",
"{",
"mod_assert",
".",
"equal",
"(",
"options",
".",
"moray",
".",
"host",
",",
"undefined",
",",
"'options.moray.host'",
")",
";",
"mod_assert",
".",
"equal",
"(",
"options",
".",
"moray",
".",
"port",
",",
"undefined",
",",
"'options.moray.port'",
")",
";",
"}",
"}"
]
| Prime number chosen to alleviate overlap with pollTime | [
"Prime",
"number",
"chosen",
"to",
"alleviate",
"overlap",
"with",
"pollTime"
]
| 4ed110e7a91a5766a794e7962b66b37ae9aea92d | https://github.com/joyent/node-sdc-changefeed/blob/4ed110e7a91a5766a794e7962b66b37ae9aea92d/lib/publisher.js#L25-L40 |
40,422 | joyent/node-sdc-changefeed | lib/publisher.js | _bucketInit | function _bucketInit() {
morayClient.getBucket(self.morayBucket.name, function _gb(err) {
if (isBucketNotFoundError(err)) {
var name = self.morayBucket.name;
var config = self.morayBucket.config;
morayClient.createBucket(name, config, function _cb(err2) {
log.info({ n: name, c: config }, 'cf: creating bucket');
if (err2) {
log.error({ cErr: err2 }, 'cf: Bucket not created');
expBackoff.backoff();
} else {
log.info('cf: Bucket successfully setup');
self.emit('moray-ready');
expBackoff.reset();
}
});
} else if (err) {
log.error({ cErr: err }, 'cf: Bucket was not loaded');
expBackoff.backoff();
} else {
log.info('cf: Bucket successfully setup');
self.emit('moray-ready');
expBackoff.reset();
}
});
} | javascript | function _bucketInit() {
morayClient.getBucket(self.morayBucket.name, function _gb(err) {
if (isBucketNotFoundError(err)) {
var name = self.morayBucket.name;
var config = self.morayBucket.config;
morayClient.createBucket(name, config, function _cb(err2) {
log.info({ n: name, c: config }, 'cf: creating bucket');
if (err2) {
log.error({ cErr: err2 }, 'cf: Bucket not created');
expBackoff.backoff();
} else {
log.info('cf: Bucket successfully setup');
self.emit('moray-ready');
expBackoff.reset();
}
});
} else if (err) {
log.error({ cErr: err }, 'cf: Bucket was not loaded');
expBackoff.backoff();
} else {
log.info('cf: Bucket successfully setup');
self.emit('moray-ready');
expBackoff.reset();
}
});
} | [
"function",
"_bucketInit",
"(",
")",
"{",
"morayClient",
".",
"getBucket",
"(",
"self",
".",
"morayBucket",
".",
"name",
",",
"function",
"_gb",
"(",
"err",
")",
"{",
"if",
"(",
"isBucketNotFoundError",
"(",
"err",
")",
")",
"{",
"var",
"name",
"=",
"self",
".",
"morayBucket",
".",
"name",
";",
"var",
"config",
"=",
"self",
".",
"morayBucket",
".",
"config",
";",
"morayClient",
".",
"createBucket",
"(",
"name",
",",
"config",
",",
"function",
"_cb",
"(",
"err2",
")",
"{",
"log",
".",
"info",
"(",
"{",
"n",
":",
"name",
",",
"c",
":",
"config",
"}",
",",
"'cf: creating bucket'",
")",
";",
"if",
"(",
"err2",
")",
"{",
"log",
".",
"error",
"(",
"{",
"cErr",
":",
"err2",
"}",
",",
"'cf: Bucket not created'",
")",
";",
"expBackoff",
".",
"backoff",
"(",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"'cf: Bucket successfully setup'",
")",
";",
"self",
".",
"emit",
"(",
"'moray-ready'",
")",
";",
"expBackoff",
".",
"reset",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"{",
"cErr",
":",
"err",
"}",
",",
"'cf: Bucket was not loaded'",
")",
";",
"expBackoff",
".",
"backoff",
"(",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"'cf: Bucket successfully setup'",
")",
";",
"self",
".",
"emit",
"(",
"'moray-ready'",
")",
";",
"expBackoff",
".",
"reset",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Handles bucket initilization and backoff on failure | [
"Handles",
"bucket",
"initilization",
"and",
"backoff",
"on",
"failure"
]
| 4ed110e7a91a5766a794e7962b66b37ae9aea92d | https://github.com/joyent/node-sdc-changefeed/blob/4ed110e7a91a5766a794e7962b66b37ae9aea92d/lib/publisher.js#L144-L169 |
40,423 | leon/angular-upload | angular-upload.js | removePendingReq | function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) {
$http.pendingRequests.splice(idx, 1);
config.$iframeTransportForm.remove();
delete config.$iframeTransportForm;
}
} | javascript | function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) {
$http.pendingRequests.splice(idx, 1);
config.$iframeTransportForm.remove();
delete config.$iframeTransportForm;
}
} | [
"function",
"removePendingReq",
"(",
")",
"{",
"var",
"idx",
"=",
"indexOf",
"(",
"$http",
".",
"pendingRequests",
",",
"config",
")",
";",
"if",
"(",
"idx",
"!==",
"-",
"1",
")",
"{",
"$http",
".",
"pendingRequests",
".",
"splice",
"(",
"idx",
",",
"1",
")",
";",
"config",
".",
"$iframeTransportForm",
".",
"remove",
"(",
")",
";",
"delete",
"config",
".",
"$iframeTransportForm",
";",
"}",
"}"
]
| Remove everything when we are done | [
"Remove",
"everything",
"when",
"we",
"are",
"done"
]
| 5b8efe6a8a95846525b8d2dc3ff269b7dbfcf663 | https://github.com/leon/angular-upload/blob/5b8efe6a8a95846525b8d2dc3ff269b7dbfcf663/angular-upload.js#L264-L271 |
40,424 | sendanor/node-joker-dmapi | src/JokerDMAPI.js | parse_domain | function parse_domain (line) {
debug.assert(line).is('string');
// -S-G-J ==> "tili-lii.fi 2017-06-02"
// +S-G-J ==> "tili-lii.fi 2017-06-02 lock"
// +S+G-J ==> "tili-lii.fi 2017-06-02 lock @creator true 0 undef"
// -S+G-J ==> "tili-lii.fi 2017-06-02 @creator true 0 undef"
// -S-G+J ==> "tili-lii.fi 2017-06-02 0"
// +S+G+J ==> "tili-lii.fi 2017-06-02 lock @creator true 0 undef 0"
//debug.log('line = "' + line + '"');
var tmp = line.split(' ');
//debug.log('tmp = ', tmp);
var domain = tmp.shift();
var exp_date = tmp.shift();
var obj = {
'domain': domain,
'expiration': exp_date
};
debug.assert(obj.domain).is('string');
debug.assert(obj.expiration).is('string');
if (showstatus) {
obj.status = tmp.shift().split(',');
debug.assert(obj.status).is('array');
}
if (showjokerns) {
obj.jokerns = parse_jokerns(tmp.pop());
debug.assert(obj.jokerns).is('boolean');
}
if (showgrants) {
obj.grants = tmp.join(' ');
debug.assert(obj.grants).is('string');
}
if (tmp.length !== 0) {
throw new TypeError("Failed to parse everything: " + tmp.join(','));
}
//debug.log("obj = ", obj);
return obj;
} | javascript | function parse_domain (line) {
debug.assert(line).is('string');
// -S-G-J ==> "tili-lii.fi 2017-06-02"
// +S-G-J ==> "tili-lii.fi 2017-06-02 lock"
// +S+G-J ==> "tili-lii.fi 2017-06-02 lock @creator true 0 undef"
// -S+G-J ==> "tili-lii.fi 2017-06-02 @creator true 0 undef"
// -S-G+J ==> "tili-lii.fi 2017-06-02 0"
// +S+G+J ==> "tili-lii.fi 2017-06-02 lock @creator true 0 undef 0"
//debug.log('line = "' + line + '"');
var tmp = line.split(' ');
//debug.log('tmp = ', tmp);
var domain = tmp.shift();
var exp_date = tmp.shift();
var obj = {
'domain': domain,
'expiration': exp_date
};
debug.assert(obj.domain).is('string');
debug.assert(obj.expiration).is('string');
if (showstatus) {
obj.status = tmp.shift().split(',');
debug.assert(obj.status).is('array');
}
if (showjokerns) {
obj.jokerns = parse_jokerns(tmp.pop());
debug.assert(obj.jokerns).is('boolean');
}
if (showgrants) {
obj.grants = tmp.join(' ');
debug.assert(obj.grants).is('string');
}
if (tmp.length !== 0) {
throw new TypeError("Failed to parse everything: " + tmp.join(','));
}
//debug.log("obj = ", obj);
return obj;
} | [
"function",
"parse_domain",
"(",
"line",
")",
"{",
"debug",
".",
"assert",
"(",
"line",
")",
".",
"is",
"(",
"'string'",
")",
";",
"// -S-G-J ==> \"tili-lii.fi 2017-06-02\"",
"// +S-G-J ==> \"tili-lii.fi 2017-06-02 lock\"",
"// +S+G-J ==> \"tili-lii.fi 2017-06-02 lock @creator true 0 undef\"",
"// -S+G-J ==> \"tili-lii.fi 2017-06-02 @creator true 0 undef\"",
"// -S-G+J ==> \"tili-lii.fi 2017-06-02 0\"",
"// +S+G+J ==> \"tili-lii.fi 2017-06-02 lock @creator true 0 undef 0\"",
"//debug.log('line = \"' + line + '\"');",
"var",
"tmp",
"=",
"line",
".",
"split",
"(",
"' '",
")",
";",
"//debug.log('tmp = ', tmp);",
"var",
"domain",
"=",
"tmp",
".",
"shift",
"(",
")",
";",
"var",
"exp_date",
"=",
"tmp",
".",
"shift",
"(",
")",
";",
"var",
"obj",
"=",
"{",
"'domain'",
":",
"domain",
",",
"'expiration'",
":",
"exp_date",
"}",
";",
"debug",
".",
"assert",
"(",
"obj",
".",
"domain",
")",
".",
"is",
"(",
"'string'",
")",
";",
"debug",
".",
"assert",
"(",
"obj",
".",
"expiration",
")",
".",
"is",
"(",
"'string'",
")",
";",
"if",
"(",
"showstatus",
")",
"{",
"obj",
".",
"status",
"=",
"tmp",
".",
"shift",
"(",
")",
".",
"split",
"(",
"','",
")",
";",
"debug",
".",
"assert",
"(",
"obj",
".",
"status",
")",
".",
"is",
"(",
"'array'",
")",
";",
"}",
"if",
"(",
"showjokerns",
")",
"{",
"obj",
".",
"jokerns",
"=",
"parse_jokerns",
"(",
"tmp",
".",
"pop",
"(",
")",
")",
";",
"debug",
".",
"assert",
"(",
"obj",
".",
"jokerns",
")",
".",
"is",
"(",
"'boolean'",
")",
";",
"}",
"if",
"(",
"showgrants",
")",
"{",
"obj",
".",
"grants",
"=",
"tmp",
".",
"join",
"(",
"' '",
")",
";",
"debug",
".",
"assert",
"(",
"obj",
".",
"grants",
")",
".",
"is",
"(",
"'string'",
")",
";",
"}",
"if",
"(",
"tmp",
".",
"length",
"!==",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Failed to parse everything: \"",
"+",
"tmp",
".",
"join",
"(",
"','",
")",
")",
";",
"}",
"//debug.log(\"obj = \", obj);",
"return",
"obj",
";",
"}"
]
| Parse single line | [
"Parse",
"single",
"line"
]
| 4644bb0e5358ba40ff96968d1bf8d1dd93a49712 | https://github.com/sendanor/node-joker-dmapi/blob/4644bb0e5358ba40ff96968d1bf8d1dd93a49712/src/JokerDMAPI.js#L216-L264 |
40,425 | jldec/pub-src-fs | fs-base.js | processData | function processData(err, data) {
if (enc) { file.text = data.toString(enc); } else { file.buffer = data; }
if (entry.sha) { file.sha = entry.sha; }
append(err, file);
readDone();
} | javascript | function processData(err, data) {
if (enc) { file.text = data.toString(enc); } else { file.buffer = data; }
if (entry.sha) { file.sha = entry.sha; }
append(err, file);
readDone();
} | [
"function",
"processData",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"enc",
")",
"{",
"file",
".",
"text",
"=",
"data",
".",
"toString",
"(",
"enc",
")",
";",
"}",
"else",
"{",
"file",
".",
"buffer",
"=",
"data",
";",
"}",
"if",
"(",
"entry",
".",
"sha",
")",
"{",
"file",
".",
"sha",
"=",
"entry",
".",
"sha",
";",
"}",
"append",
"(",
"err",
",",
"file",
")",
";",
"readDone",
"(",
")",
";",
"}"
]
| populate file.text or, for binary files, file.buffer | [
"populate",
"file",
".",
"text",
"or",
"for",
"binary",
"files",
"file",
".",
"buffer"
]
| 25058d68839163f74fb850b896cf039a7e1e59be | https://github.com/jldec/pub-src-fs/blob/25058d68839163f74fb850b896cf039a7e1e59be/fs-base.js#L121-L126 |
40,426 | Wlada/angular-carousel-3d | dist/carousel-3d.js | handleReject | function handleReject(carousel) {
$element.css({ 'height': carousel.getOuterHeight() + 'px' });
vm.isLoading = false;
vm.isSuccessful = false;
} | javascript | function handleReject(carousel) {
$element.css({ 'height': carousel.getOuterHeight() + 'px' });
vm.isLoading = false;
vm.isSuccessful = false;
} | [
"function",
"handleReject",
"(",
"carousel",
")",
"{",
"$element",
".",
"css",
"(",
"{",
"'height'",
":",
"carousel",
".",
"getOuterHeight",
"(",
")",
"+",
"'px'",
"}",
")",
";",
"vm",
".",
"isLoading",
"=",
"false",
";",
"vm",
".",
"isSuccessful",
"=",
"false",
";",
"}"
]
| == Preloaded images reject handler | [
"==",
"Preloaded",
"images",
"reject",
"handler"
]
| 6895284cf59f15602e451130c38aa4605ae9012b | https://github.com/Wlada/angular-carousel-3d/blob/6895284cf59f15602e451130c38aa4605ae9012b/dist/carousel-3d.js#L105-L111 |
40,427 | airbnb/react-with-styles-interface-css | packages/interface/src/index.js | create | function create(stylesObject) {
const stylesToClasses = {};
const styleNames = Object.keys(stylesObject);
const sharedState = globalCache.get(GLOBAL_CACHE_KEY) || {};
const { namespace = '' } = sharedState;
styleNames.forEach((styleName) => {
const className = getClassName(namespace, styleName);
stylesToClasses[styleName] = className;
});
return stylesToClasses;
} | javascript | function create(stylesObject) {
const stylesToClasses = {};
const styleNames = Object.keys(stylesObject);
const sharedState = globalCache.get(GLOBAL_CACHE_KEY) || {};
const { namespace = '' } = sharedState;
styleNames.forEach((styleName) => {
const className = getClassName(namespace, styleName);
stylesToClasses[styleName] = className;
});
return stylesToClasses;
} | [
"function",
"create",
"(",
"stylesObject",
")",
"{",
"const",
"stylesToClasses",
"=",
"{",
"}",
";",
"const",
"styleNames",
"=",
"Object",
".",
"keys",
"(",
"stylesObject",
")",
";",
"const",
"sharedState",
"=",
"globalCache",
".",
"get",
"(",
"GLOBAL_CACHE_KEY",
")",
"||",
"{",
"}",
";",
"const",
"{",
"namespace",
"=",
"''",
"}",
"=",
"sharedState",
";",
"styleNames",
".",
"forEach",
"(",
"(",
"styleName",
")",
"=>",
"{",
"const",
"className",
"=",
"getClassName",
"(",
"namespace",
",",
"styleName",
")",
";",
"stylesToClasses",
"[",
"styleName",
"]",
"=",
"className",
";",
"}",
")",
";",
"return",
"stylesToClasses",
";",
"}"
]
| Function required as part of the react-with-styles interface. Parses the styles provided by
react-with-styles to produce class names based on the style name and optionally the namespace if
available.
stylesObject {Object} The styles object passed to withStyles.
Return an object mapping style names to class names. | [
"Function",
"required",
"as",
"part",
"of",
"the",
"react",
"-",
"with",
"-",
"styles",
"interface",
".",
"Parses",
"the",
"styles",
"provided",
"by",
"react",
"-",
"with",
"-",
"styles",
"to",
"produce",
"class",
"names",
"based",
"on",
"the",
"style",
"name",
"and",
"optionally",
"the",
"namespace",
"if",
"available",
"."
]
| 41608ca0156deffc9c6a11a69beb78290532fddb | https://github.com/airbnb/react-with-styles-interface-css/blob/41608ca0156deffc9c6a11a69beb78290532fddb/packages/interface/src/index.js#L17-L27 |
40,428 | airbnb/react-with-styles-interface-css | packages/interface/src/index.js | resolve | function resolve(stylesArray) {
const flattenedStyles = flat(stylesArray, Infinity);
const { classNames, hasInlineStyles, inlineStyles } = separateStyles(flattenedStyles);
const specificClassNames = classNames.map((name, index) => `${name} ${name}_${index + 1}`);
const className = specificClassNames.join(' ');
const result = { className };
if (hasInlineStyles) result.style = inlineStyles;
return result;
} | javascript | function resolve(stylesArray) {
const flattenedStyles = flat(stylesArray, Infinity);
const { classNames, hasInlineStyles, inlineStyles } = separateStyles(flattenedStyles);
const specificClassNames = classNames.map((name, index) => `${name} ${name}_${index + 1}`);
const className = specificClassNames.join(' ');
const result = { className };
if (hasInlineStyles) result.style = inlineStyles;
return result;
} | [
"function",
"resolve",
"(",
"stylesArray",
")",
"{",
"const",
"flattenedStyles",
"=",
"flat",
"(",
"stylesArray",
",",
"Infinity",
")",
";",
"const",
"{",
"classNames",
",",
"hasInlineStyles",
",",
"inlineStyles",
"}",
"=",
"separateStyles",
"(",
"flattenedStyles",
")",
";",
"const",
"specificClassNames",
"=",
"classNames",
".",
"map",
"(",
"(",
"name",
",",
"index",
")",
"=>",
"`",
"${",
"name",
"}",
"${",
"name",
"}",
"${",
"index",
"+",
"1",
"}",
"`",
")",
";",
"const",
"className",
"=",
"specificClassNames",
".",
"join",
"(",
"' '",
")",
";",
"const",
"result",
"=",
"{",
"className",
"}",
";",
"if",
"(",
"hasInlineStyles",
")",
"result",
".",
"style",
"=",
"inlineStyles",
";",
"return",
"result",
";",
"}"
]
| Process styles to be consumed by a component.
stylesArray {Array} Array of the following: values returned by create, plain JavaScript objects
representing inline styles, or arrays thereof.
Return an object with optional className and style properties to be spread on a component. | [
"Process",
"styles",
"to",
"be",
"consumed",
"by",
"a",
"component",
"."
]
| 41608ca0156deffc9c6a11a69beb78290532fddb | https://github.com/airbnb/react-with-styles-interface-css/blob/41608ca0156deffc9c6a11a69beb78290532fddb/packages/interface/src/index.js#L37-L46 |
40,429 | dssrv/srv-prerender | lib/index.js | function(file, done){
process.nextTick(function () {
terra.render(file, function(error, body){
if(error){
done(error);
}else{
if(body){
var dest = path.resolve(outputPath, ssr.helpers.outputPath(file));
fs.mkdirp(path.dirname(dest), function(err){
fs.writeFile(dest, body, done);
});
}else{
done();
}
}
});
});
} | javascript | function(file, done){
process.nextTick(function () {
terra.render(file, function(error, body){
if(error){
done(error);
}else{
if(body){
var dest = path.resolve(outputPath, ssr.helpers.outputPath(file));
fs.mkdirp(path.dirname(dest), function(err){
fs.writeFile(dest, body, done);
});
}else{
done();
}
}
});
});
} | [
"function",
"(",
"file",
",",
"done",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"terra",
".",
"render",
"(",
"file",
",",
"function",
"(",
"error",
",",
"body",
")",
"{",
"if",
"(",
"error",
")",
"{",
"done",
"(",
"error",
")",
";",
"}",
"else",
"{",
"if",
"(",
"body",
")",
"{",
"var",
"dest",
"=",
"path",
".",
"resolve",
"(",
"outputPath",
",",
"ssr",
".",
"helpers",
".",
"outputPath",
"(",
"file",
")",
")",
";",
"fs",
".",
"mkdirp",
"(",
"path",
".",
"dirname",
"(",
"dest",
")",
",",
"function",
"(",
"err",
")",
"{",
"fs",
".",
"writeFile",
"(",
"dest",
",",
"body",
",",
"done",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"done",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Compile and save file | [
"Compile",
"and",
"save",
"file"
]
| 60a57b953442e4ffb4b13c19d61f16a808e0c42f | https://github.com/dssrv/srv-prerender/blob/60a57b953442e4ffb4b13c19d61f16a808e0c42f/lib/index.js#L204-L221 |
|
40,430 | right-track/right-track-core | modules/search/search.js | search | function search(db, origin, destination, departure, options, callback) {
_log("====== STARTING SEARCH ======");
_log("ORIGIN: " + origin.name);
_log("DESTINATION: " + destination.name);
_log("DATE/TIME: " + departure.toString());
_log("OPTIONS: " + JSON.stringify(options, null, 2));
// List of Results
let RESULTS = [];
// Get the initial Trip Search Dates
_getTripSearchDates(db, departure, options.preDepartureHours*60, options.postDepartureHours*60, function(err, tripSearchDates) {
_log("===== SEARCH TIME RANGE =====");
for ( let i = 0; i < tripSearchDates.length; i++ ) {
_log(JSON.stringify(tripSearchDates[i], null, 2));
}
// Database Query Error
if ( err ) {
return callback(err);
}
// Get the Initial Trips
_getTripsFromStop(db, origin, destination, origin, tripSearchDates, [], function(err, direct, indirect) {
_log("======= INITIAL TRIPS =======");
_log("DIRECT TRIPS: " + direct.length);
_log("INDIRECT TRIPS: " + indirect.length);
// Database Query Error
if ( err ) {
return callback(err);
}
// Process Direct Trips
for ( let i = 0; i < direct.length; i++ ) {
let trip = direct[i];
// Create a new Trip Search Result Segment
let segment = new TripSearchResultSegment(trip, origin, destination);
// Create new Trip Search Result
let result = new TripSearchResult(segment);
// Add Result to List
RESULTS.push(result);
}
// Process Indirect Trips, if transfers are allowed
if ( indirect.length > 0 && options.allowTransfers ) {
_log("====== TRANSFER SEARCH ======");
// Process the Indirect Trips
_processTrips(db, options, origin, destination, origin, indirect, [], function(err, results) {
_log("=== TRANSFER SEARCH RETURN ==");
// Add results to final list
RESULTS = RESULTS.concat(results);
// Finish
_finish();
});
}
// No transfers required or disabled, finish
else {
_finish();
}
});
});
/**
* Finished processing all trips, get Results ready to return
* @private
*/
function _finish() {
_log("=============================");
// Clean the Results
RESULTS = _cleanResults(RESULTS);
// Return the Results
return callback(null, RESULTS);
}
} | javascript | function search(db, origin, destination, departure, options, callback) {
_log("====== STARTING SEARCH ======");
_log("ORIGIN: " + origin.name);
_log("DESTINATION: " + destination.name);
_log("DATE/TIME: " + departure.toString());
_log("OPTIONS: " + JSON.stringify(options, null, 2));
// List of Results
let RESULTS = [];
// Get the initial Trip Search Dates
_getTripSearchDates(db, departure, options.preDepartureHours*60, options.postDepartureHours*60, function(err, tripSearchDates) {
_log("===== SEARCH TIME RANGE =====");
for ( let i = 0; i < tripSearchDates.length; i++ ) {
_log(JSON.stringify(tripSearchDates[i], null, 2));
}
// Database Query Error
if ( err ) {
return callback(err);
}
// Get the Initial Trips
_getTripsFromStop(db, origin, destination, origin, tripSearchDates, [], function(err, direct, indirect) {
_log("======= INITIAL TRIPS =======");
_log("DIRECT TRIPS: " + direct.length);
_log("INDIRECT TRIPS: " + indirect.length);
// Database Query Error
if ( err ) {
return callback(err);
}
// Process Direct Trips
for ( let i = 0; i < direct.length; i++ ) {
let trip = direct[i];
// Create a new Trip Search Result Segment
let segment = new TripSearchResultSegment(trip, origin, destination);
// Create new Trip Search Result
let result = new TripSearchResult(segment);
// Add Result to List
RESULTS.push(result);
}
// Process Indirect Trips, if transfers are allowed
if ( indirect.length > 0 && options.allowTransfers ) {
_log("====== TRANSFER SEARCH ======");
// Process the Indirect Trips
_processTrips(db, options, origin, destination, origin, indirect, [], function(err, results) {
_log("=== TRANSFER SEARCH RETURN ==");
// Add results to final list
RESULTS = RESULTS.concat(results);
// Finish
_finish();
});
}
// No transfers required or disabled, finish
else {
_finish();
}
});
});
/**
* Finished processing all trips, get Results ready to return
* @private
*/
function _finish() {
_log("=============================");
// Clean the Results
RESULTS = _cleanResults(RESULTS);
// Return the Results
return callback(null, RESULTS);
}
} | [
"function",
"search",
"(",
"db",
",",
"origin",
",",
"destination",
",",
"departure",
",",
"options",
",",
"callback",
")",
"{",
"_log",
"(",
"\"====== STARTING SEARCH ======\"",
")",
";",
"_log",
"(",
"\"ORIGIN: \"",
"+",
"origin",
".",
"name",
")",
";",
"_log",
"(",
"\"DESTINATION: \"",
"+",
"destination",
".",
"name",
")",
";",
"_log",
"(",
"\"DATE/TIME: \"",
"+",
"departure",
".",
"toString",
"(",
")",
")",
";",
"_log",
"(",
"\"OPTIONS: \"",
"+",
"JSON",
".",
"stringify",
"(",
"options",
",",
"null",
",",
"2",
")",
")",
";",
"// List of Results",
"let",
"RESULTS",
"=",
"[",
"]",
";",
"// Get the initial Trip Search Dates",
"_getTripSearchDates",
"(",
"db",
",",
"departure",
",",
"options",
".",
"preDepartureHours",
"*",
"60",
",",
"options",
".",
"postDepartureHours",
"*",
"60",
",",
"function",
"(",
"err",
",",
"tripSearchDates",
")",
"{",
"_log",
"(",
"\"===== SEARCH TIME RANGE =====\"",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"tripSearchDates",
".",
"length",
";",
"i",
"++",
")",
"{",
"_log",
"(",
"JSON",
".",
"stringify",
"(",
"tripSearchDates",
"[",
"i",
"]",
",",
"null",
",",
"2",
")",
")",
";",
"}",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Get the Initial Trips",
"_getTripsFromStop",
"(",
"db",
",",
"origin",
",",
"destination",
",",
"origin",
",",
"tripSearchDates",
",",
"[",
"]",
",",
"function",
"(",
"err",
",",
"direct",
",",
"indirect",
")",
"{",
"_log",
"(",
"\"======= INITIAL TRIPS =======\"",
")",
";",
"_log",
"(",
"\"DIRECT TRIPS: \"",
"+",
"direct",
".",
"length",
")",
";",
"_log",
"(",
"\"INDIRECT TRIPS: \"",
"+",
"indirect",
".",
"length",
")",
";",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Process Direct Trips",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"direct",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"trip",
"=",
"direct",
"[",
"i",
"]",
";",
"// Create a new Trip Search Result Segment",
"let",
"segment",
"=",
"new",
"TripSearchResultSegment",
"(",
"trip",
",",
"origin",
",",
"destination",
")",
";",
"// Create new Trip Search Result",
"let",
"result",
"=",
"new",
"TripSearchResult",
"(",
"segment",
")",
";",
"// Add Result to List",
"RESULTS",
".",
"push",
"(",
"result",
")",
";",
"}",
"// Process Indirect Trips, if transfers are allowed",
"if",
"(",
"indirect",
".",
"length",
">",
"0",
"&&",
"options",
".",
"allowTransfers",
")",
"{",
"_log",
"(",
"\"====== TRANSFER SEARCH ======\"",
")",
";",
"// Process the Indirect Trips",
"_processTrips",
"(",
"db",
",",
"options",
",",
"origin",
",",
"destination",
",",
"origin",
",",
"indirect",
",",
"[",
"]",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"_log",
"(",
"\"=== TRANSFER SEARCH RETURN ==\"",
")",
";",
"// Add results to final list",
"RESULTS",
"=",
"RESULTS",
".",
"concat",
"(",
"results",
")",
";",
"// Finish",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"// No transfers required or disabled, finish",
"else",
"{",
"_finish",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"/**\n * Finished processing all trips, get Results ready to return\n * @private\n */",
"function",
"_finish",
"(",
")",
"{",
"_log",
"(",
"\"=============================\"",
")",
";",
"// Clean the Results",
"RESULTS",
"=",
"_cleanResults",
"(",
"RESULTS",
")",
";",
"// Return the Results",
"return",
"callback",
"(",
"null",
",",
"RESULTS",
")",
";",
"}",
"}"
]
| Perform a Trip Search between the origin and destination Stops
with the provided parameters and options
@param {RightTrackDB} db The Right Track DB to query
@param {Stop} origin Origin Stop
@param {Stop} destination Destination Stop
@param {DateTime} departure Requested Departure Date/Time
@param {Object} options Trip Search Options
@param {function} callback Callback Function
@private | [
"Perform",
"a",
"Trip",
"Search",
"between",
"the",
"origin",
"and",
"destination",
"Stops",
"with",
"the",
"provided",
"parameters",
"and",
"options"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L34-L133 |
40,431 | right-track/right-track-core | modules/search/search.js | _cleanDepartures | function _cleanDepartures(results) {
// List of Departures to Keep
let departures = [];
// Get unique departures
let departureTimes = [];
for ( let i = 0; i < results.length; i++ ) {
if ( departureTimes.indexOf(results[i].origin.departure.toTimestamp()) === -1 ) {
departureTimes.push(results[i].origin.departure.toTimestamp());
}
}
// Pick best Trip for each departure
for ( let i = 0; i < departureTimes.length; i++ ) {
let departureTime = departureTimes[i];
let departure = undefined;
// Get Trips with departure time
for ( let j = 0; j < results.length; j++ ) {
let result = results[j];
if ( result.origin.departure.toTimestamp() === departureTime ) {
if ( departure === undefined ) {
departure = result;
}
else if ( result.destination.arrival.toTimestamp() < departure.destination.arrival.toTimestamp() ) {
departure = result;
}
else if ( result.destination.arrival.toTimestamp() === departure.destination.arrival.toTimestamp() && result.length < departure.length ) {
departure = result;
}
}
}
// Add departure to list
departures.push(departure);
}
// Return departures
return departures;
} | javascript | function _cleanDepartures(results) {
// List of Departures to Keep
let departures = [];
// Get unique departures
let departureTimes = [];
for ( let i = 0; i < results.length; i++ ) {
if ( departureTimes.indexOf(results[i].origin.departure.toTimestamp()) === -1 ) {
departureTimes.push(results[i].origin.departure.toTimestamp());
}
}
// Pick best Trip for each departure
for ( let i = 0; i < departureTimes.length; i++ ) {
let departureTime = departureTimes[i];
let departure = undefined;
// Get Trips with departure time
for ( let j = 0; j < results.length; j++ ) {
let result = results[j];
if ( result.origin.departure.toTimestamp() === departureTime ) {
if ( departure === undefined ) {
departure = result;
}
else if ( result.destination.arrival.toTimestamp() < departure.destination.arrival.toTimestamp() ) {
departure = result;
}
else if ( result.destination.arrival.toTimestamp() === departure.destination.arrival.toTimestamp() && result.length < departure.length ) {
departure = result;
}
}
}
// Add departure to list
departures.push(departure);
}
// Return departures
return departures;
} | [
"function",
"_cleanDepartures",
"(",
"results",
")",
"{",
"// List of Departures to Keep",
"let",
"departures",
"=",
"[",
"]",
";",
"// Get unique departures",
"let",
"departureTimes",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"departureTimes",
".",
"indexOf",
"(",
"results",
"[",
"i",
"]",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
")",
"===",
"-",
"1",
")",
"{",
"departureTimes",
".",
"push",
"(",
"results",
"[",
"i",
"]",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
")",
";",
"}",
"}",
"// Pick best Trip for each departure",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"departureTimes",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"departureTime",
"=",
"departureTimes",
"[",
"i",
"]",
";",
"let",
"departure",
"=",
"undefined",
";",
"// Get Trips with departure time",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"results",
".",
"length",
";",
"j",
"++",
")",
"{",
"let",
"result",
"=",
"results",
"[",
"j",
"]",
";",
"if",
"(",
"result",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
"===",
"departureTime",
")",
"{",
"if",
"(",
"departure",
"===",
"undefined",
")",
"{",
"departure",
"=",
"result",
";",
"}",
"else",
"if",
"(",
"result",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
"<",
"departure",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
")",
"{",
"departure",
"=",
"result",
";",
"}",
"else",
"if",
"(",
"result",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
"===",
"departure",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
"&&",
"result",
".",
"length",
"<",
"departure",
".",
"length",
")",
"{",
"departure",
"=",
"result",
";",
"}",
"}",
"}",
"// Add departure to list",
"departures",
".",
"push",
"(",
"departure",
")",
";",
"}",
"// Return departures",
"return",
"departures",
";",
"}"
]
| Pick best Trip with equal departures
@param results
@returns {Array}
@private | [
"Pick",
"best",
"Trip",
"with",
"equal",
"departures"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L166-L205 |
40,432 | right-track/right-track-core | modules/search/search.js | _cleanArrivals | function _cleanArrivals(results) {
// List of Arrivals to Keep
let arrivals = [];
// Get unique arrivals
let arrivalTimes = [];
for ( let i = 0; i < results.length; i++ ) {
if ( arrivalTimes.indexOf(results[i].destination.arrival.toTimestamp()) === -1 ) {
arrivalTimes.push(results[i].destination.arrival.toTimestamp());
}
}
// Pick best Trip for each arrival
for ( let i = 0; i < arrivalTimes.length; i++ ) {
let arrivalTime = arrivalTimes[i];
let arrival = undefined;
// Get Trips with arrival time
for ( let j = 0; j < results.length; j++ ) {
let result = results[j];
if ( result.destination.arrival.toTimestamp() === arrivalTime ) {
if ( arrival === undefined ) {
arrival = result;
}
else if ( result.origin.departure.toTimestamp() > arrival.origin.departure.toTimestamp() ) {
arrival = result;
}
else if ( result.origin.departure.toTimestamp() === arrival.origin.departure.toTimestamp() && result.length < arrival.length ) {
arrival = result;
}
}
}
// Add arrival to list
arrivals.push(arrival);
}
// Return arrivals
return arrivals;
} | javascript | function _cleanArrivals(results) {
// List of Arrivals to Keep
let arrivals = [];
// Get unique arrivals
let arrivalTimes = [];
for ( let i = 0; i < results.length; i++ ) {
if ( arrivalTimes.indexOf(results[i].destination.arrival.toTimestamp()) === -1 ) {
arrivalTimes.push(results[i].destination.arrival.toTimestamp());
}
}
// Pick best Trip for each arrival
for ( let i = 0; i < arrivalTimes.length; i++ ) {
let arrivalTime = arrivalTimes[i];
let arrival = undefined;
// Get Trips with arrival time
for ( let j = 0; j < results.length; j++ ) {
let result = results[j];
if ( result.destination.arrival.toTimestamp() === arrivalTime ) {
if ( arrival === undefined ) {
arrival = result;
}
else if ( result.origin.departure.toTimestamp() > arrival.origin.departure.toTimestamp() ) {
arrival = result;
}
else if ( result.origin.departure.toTimestamp() === arrival.origin.departure.toTimestamp() && result.length < arrival.length ) {
arrival = result;
}
}
}
// Add arrival to list
arrivals.push(arrival);
}
// Return arrivals
return arrivals;
} | [
"function",
"_cleanArrivals",
"(",
"results",
")",
"{",
"// List of Arrivals to Keep",
"let",
"arrivals",
"=",
"[",
"]",
";",
"// Get unique arrivals",
"let",
"arrivalTimes",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"arrivalTimes",
".",
"indexOf",
"(",
"results",
"[",
"i",
"]",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
")",
"===",
"-",
"1",
")",
"{",
"arrivalTimes",
".",
"push",
"(",
"results",
"[",
"i",
"]",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
")",
";",
"}",
"}",
"// Pick best Trip for each arrival",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"arrivalTimes",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"arrivalTime",
"=",
"arrivalTimes",
"[",
"i",
"]",
";",
"let",
"arrival",
"=",
"undefined",
";",
"// Get Trips with arrival time",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"results",
".",
"length",
";",
"j",
"++",
")",
"{",
"let",
"result",
"=",
"results",
"[",
"j",
"]",
";",
"if",
"(",
"result",
".",
"destination",
".",
"arrival",
".",
"toTimestamp",
"(",
")",
"===",
"arrivalTime",
")",
"{",
"if",
"(",
"arrival",
"===",
"undefined",
")",
"{",
"arrival",
"=",
"result",
";",
"}",
"else",
"if",
"(",
"result",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
">",
"arrival",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
")",
"{",
"arrival",
"=",
"result",
";",
"}",
"else",
"if",
"(",
"result",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
"===",
"arrival",
".",
"origin",
".",
"departure",
".",
"toTimestamp",
"(",
")",
"&&",
"result",
".",
"length",
"<",
"arrival",
".",
"length",
")",
"{",
"arrival",
"=",
"result",
";",
"}",
"}",
"}",
"// Add arrival to list",
"arrivals",
".",
"push",
"(",
"arrival",
")",
";",
"}",
"// Return arrivals",
"return",
"arrivals",
";",
"}"
]
| Pick best Trip with equal arrivals
@param results
@returns {Array}
@private | [
"Pick",
"best",
"Trip",
"with",
"equal",
"arrivals"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L214-L254 |
40,433 | right-track/right-track-core | modules/search/search.js | _processTrips | function _processTrips(db, options, origin, destination, enter, trips, segments, callback) {
// Display function logs
_info();
// Results to Return
let RESULTS = [];
// Set up counters
let done = 0;
let count = trips.length;
// Finish when there are no trips to process
if ( trips.length === 0 ) {
_finish();
}
// Process each of the Trips
for ( let i = 0; i < trips.length; i++ ) {
_processTrip(db, options, origin, destination, enter, trips[i], segments, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add Results to final list
RESULTS = RESULTS.concat(results);
// Finish
_finish();
})
}
/**
* Finished Processing the Trips
* @private
*/
function _finish() {
done++;
if ( count === 0 || done === count ) {
return callback(null, RESULTS);
}
}
/**
* Display function logging info
* @private
*/
function _info() {
if ( LOG ) {
let p = "";
for ( let i = 0; i < segments.length * 2; i++ ) {
p = p + " ";
}
let tripIds = [];
for ( let i = 0; i < trips.length; i++ ) {
tripIds.push(trips[i].id);
}
_log(p + "Trips From " + enter.name + ": " + trips.length + " ('" + tripIds.join("', '") + "')");
_log(p + " Segments: " + segments.length);
_printSegments(segments, p + " ");
}
}
} | javascript | function _processTrips(db, options, origin, destination, enter, trips, segments, callback) {
// Display function logs
_info();
// Results to Return
let RESULTS = [];
// Set up counters
let done = 0;
let count = trips.length;
// Finish when there are no trips to process
if ( trips.length === 0 ) {
_finish();
}
// Process each of the Trips
for ( let i = 0; i < trips.length; i++ ) {
_processTrip(db, options, origin, destination, enter, trips[i], segments, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add Results to final list
RESULTS = RESULTS.concat(results);
// Finish
_finish();
})
}
/**
* Finished Processing the Trips
* @private
*/
function _finish() {
done++;
if ( count === 0 || done === count ) {
return callback(null, RESULTS);
}
}
/**
* Display function logging info
* @private
*/
function _info() {
if ( LOG ) {
let p = "";
for ( let i = 0; i < segments.length * 2; i++ ) {
p = p + " ";
}
let tripIds = [];
for ( let i = 0; i < trips.length; i++ ) {
tripIds.push(trips[i].id);
}
_log(p + "Trips From " + enter.name + ": " + trips.length + " ('" + tripIds.join("', '") + "')");
_log(p + " Segments: " + segments.length);
_printSegments(segments, p + " ");
}
}
} | [
"function",
"_processTrips",
"(",
"db",
",",
"options",
",",
"origin",
",",
"destination",
",",
"enter",
",",
"trips",
",",
"segments",
",",
"callback",
")",
"{",
"// Display function logs",
"_info",
"(",
")",
";",
"// Results to Return",
"let",
"RESULTS",
"=",
"[",
"]",
";",
"// Set up counters",
"let",
"done",
"=",
"0",
";",
"let",
"count",
"=",
"trips",
".",
"length",
";",
"// Finish when there are no trips to process",
"if",
"(",
"trips",
".",
"length",
"===",
"0",
")",
"{",
"_finish",
"(",
")",
";",
"}",
"// Process each of the Trips",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trips",
".",
"length",
";",
"i",
"++",
")",
"{",
"_processTrip",
"(",
"db",
",",
"options",
",",
"origin",
",",
"destination",
",",
"enter",
",",
"trips",
"[",
"i",
"]",
",",
"segments",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add Results to final list",
"RESULTS",
"=",
"RESULTS",
".",
"concat",
"(",
"results",
")",
";",
"// Finish",
"_finish",
"(",
")",
";",
"}",
")",
"}",
"/**\n * Finished Processing the Trips\n * @private\n */",
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"count",
"===",
"0",
"||",
"done",
"===",
"count",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"RESULTS",
")",
";",
"}",
"}",
"/**\n * Display function logging info\n * @private\n */",
"function",
"_info",
"(",
")",
"{",
"if",
"(",
"LOG",
")",
"{",
"let",
"p",
"=",
"\"\"",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
"*",
"2",
";",
"i",
"++",
")",
"{",
"p",
"=",
"p",
"+",
"\" \"",
";",
"}",
"let",
"tripIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trips",
".",
"length",
";",
"i",
"++",
")",
"{",
"tripIds",
".",
"push",
"(",
"trips",
"[",
"i",
"]",
".",
"id",
")",
";",
"}",
"_log",
"(",
"p",
"+",
"\"Trips From \"",
"+",
"enter",
".",
"name",
"+",
"\": \"",
"+",
"trips",
".",
"length",
"+",
"\" ('\"",
"+",
"tripIds",
".",
"join",
"(",
"\"', '\"",
")",
"+",
"\"')\"",
")",
";",
"_log",
"(",
"p",
"+",
"\" Segments: \"",
"+",
"segments",
".",
"length",
")",
";",
"_printSegments",
"(",
"segments",
",",
"p",
"+",
"\" \"",
")",
";",
"}",
"}",
"}"
]
| Process a group of Trips from the reference Stop
@param {RightTrackDB} db The Right Track DB to query
@param {Object} options Trip Search Options
@param {Stop} origin Trip Search Origin Stop
@param {Stop} destination Trip Search Destination Stop
@param {Stop} enter Reference/Entry Stop
@param {Trip[]} trips List of Trips to process
@param {TripSearchResultSegment[]} segments Previously added Trip Search Result Segments
@param {function} callback Callback function(err, results)
@private | [
"Process",
"a",
"group",
"of",
"Trips",
"from",
"the",
"reference",
"Stop"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L272-L343 |
40,434 | right-track/right-track-core | modules/search/search.js | _info | function _info() {
if ( LOG ) {
let p = "";
for ( let i = 0; i < segments.length * 2; i++ ) {
p = p + " ";
}
let tripIds = [];
for ( let i = 0; i < trips.length; i++ ) {
tripIds.push(trips[i].id);
}
_log(p + "Trips From " + enter.name + ": " + trips.length + " ('" + tripIds.join("', '") + "')");
_log(p + " Segments: " + segments.length);
_printSegments(segments, p + " ");
}
} | javascript | function _info() {
if ( LOG ) {
let p = "";
for ( let i = 0; i < segments.length * 2; i++ ) {
p = p + " ";
}
let tripIds = [];
for ( let i = 0; i < trips.length; i++ ) {
tripIds.push(trips[i].id);
}
_log(p + "Trips From " + enter.name + ": " + trips.length + " ('" + tripIds.join("', '") + "')");
_log(p + " Segments: " + segments.length);
_printSegments(segments, p + " ");
}
} | [
"function",
"_info",
"(",
")",
"{",
"if",
"(",
"LOG",
")",
"{",
"let",
"p",
"=",
"\"\"",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
"*",
"2",
";",
"i",
"++",
")",
"{",
"p",
"=",
"p",
"+",
"\" \"",
";",
"}",
"let",
"tripIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trips",
".",
"length",
";",
"i",
"++",
")",
"{",
"tripIds",
".",
"push",
"(",
"trips",
"[",
"i",
"]",
".",
"id",
")",
";",
"}",
"_log",
"(",
"p",
"+",
"\"Trips From \"",
"+",
"enter",
".",
"name",
"+",
"\": \"",
"+",
"trips",
".",
"length",
"+",
"\" ('\"",
"+",
"tripIds",
".",
"join",
"(",
"\"', '\"",
")",
"+",
"\"')\"",
")",
";",
"_log",
"(",
"p",
"+",
"\" Segments: \"",
"+",
"segments",
".",
"length",
")",
";",
"_printSegments",
"(",
"segments",
",",
"p",
"+",
"\" \"",
")",
";",
"}",
"}"
]
| Display function logging info
@private | [
"Display",
"function",
"logging",
"info"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L325-L341 |
40,435 | right-track/right-track-core | modules/search/search.js | _info | function _info(stops) {
if ( LOG ) {
let p = "";
for ( let i = 0; i < segments.length * 2; i++ ) {
p = p + " ";
}
_log(p + "...Trip " + trip.id);
_log(p + " Stop: " + enter.name + " @ " + trip.getStopTime(enter).departure.getTimeReadable());
_log(p + " Segments: " + segments.length);
_printSegments(segments, p + " ");
let stopNames = [];
for ( let i = 0; i < stops.length; i++ ) {
stopNames.push(stops[i].name);
}
_log(p + " Transfer Stops: " + stops.length + " (" + stopNames.join(', ') + ")");
}
} | javascript | function _info(stops) {
if ( LOG ) {
let p = "";
for ( let i = 0; i < segments.length * 2; i++ ) {
p = p + " ";
}
_log(p + "...Trip " + trip.id);
_log(p + " Stop: " + enter.name + " @ " + trip.getStopTime(enter).departure.getTimeReadable());
_log(p + " Segments: " + segments.length);
_printSegments(segments, p + " ");
let stopNames = [];
for ( let i = 0; i < stops.length; i++ ) {
stopNames.push(stops[i].name);
}
_log(p + " Transfer Stops: " + stops.length + " (" + stopNames.join(', ') + ")");
}
} | [
"function",
"_info",
"(",
"stops",
")",
"{",
"if",
"(",
"LOG",
")",
"{",
"let",
"p",
"=",
"\"\"",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
"*",
"2",
";",
"i",
"++",
")",
"{",
"p",
"=",
"p",
"+",
"\" \"",
";",
"}",
"_log",
"(",
"p",
"+",
"\"...Trip \"",
"+",
"trip",
".",
"id",
")",
";",
"_log",
"(",
"p",
"+",
"\" Stop: \"",
"+",
"enter",
".",
"name",
"+",
"\" @ \"",
"+",
"trip",
".",
"getStopTime",
"(",
"enter",
")",
".",
"departure",
".",
"getTimeReadable",
"(",
")",
")",
";",
"_log",
"(",
"p",
"+",
"\" Segments: \"",
"+",
"segments",
".",
"length",
")",
";",
"_printSegments",
"(",
"segments",
",",
"p",
"+",
"\" \"",
")",
";",
"let",
"stopNames",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"stops",
".",
"length",
";",
"i",
"++",
")",
"{",
"stopNames",
".",
"push",
"(",
"stops",
"[",
"i",
"]",
".",
"name",
")",
";",
"}",
"_log",
"(",
"p",
"+",
"\" Transfer Stops: \"",
"+",
"stops",
".",
"length",
"+",
"\" (\"",
"+",
"stopNames",
".",
"join",
"(",
"', '",
")",
"+",
"\")\"",
")",
";",
"}",
"}"
]
| Display logging info
@private | [
"Display",
"logging",
"info"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L391-L409 |
40,436 | right-track/right-track-core | modules/search/search.js | _getTransferStops | function _getTransferStops(db, origin, destination, stop, trip, callback) {
// List of Transfer Stops
let rtn = [];
// Get Next Stops from this Stop
LineGraphTable.getNextStops(db, origin.id, destination.id, stop.id, function(err, nextStops) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Get Remaining Stops on Trip
let remainingStops = [];
let stopFound = false;
for ( let i = 0; i < trip.stopTimes.length; i++ ) {
if ( !stopFound && trip.stopTimes[i].stop.id === stop.id ) {
stopFound = true;
}
else if ( stopFound ) {
remainingStops.push(trip.stopTimes[i].stop.id);
}
}
// Get Next Stops that are remaining on this Trip
for ( let i = 0; i < nextStops.length; i++ ) {
if ( remainingStops.indexOf(nextStops[i]) > -1 ) {
rtn.push(
trip.getStopTime(nextStops[i]).stop
);
}
}
// Return only the top 3 transfer Stops
if ( rtn.length > 3 ) {
rtn = [rtn[0], rtn[1], rtn[2]];
}
return callback(null, rtn);
});
} | javascript | function _getTransferStops(db, origin, destination, stop, trip, callback) {
// List of Transfer Stops
let rtn = [];
// Get Next Stops from this Stop
LineGraphTable.getNextStops(db, origin.id, destination.id, stop.id, function(err, nextStops) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Get Remaining Stops on Trip
let remainingStops = [];
let stopFound = false;
for ( let i = 0; i < trip.stopTimes.length; i++ ) {
if ( !stopFound && trip.stopTimes[i].stop.id === stop.id ) {
stopFound = true;
}
else if ( stopFound ) {
remainingStops.push(trip.stopTimes[i].stop.id);
}
}
// Get Next Stops that are remaining on this Trip
for ( let i = 0; i < nextStops.length; i++ ) {
if ( remainingStops.indexOf(nextStops[i]) > -1 ) {
rtn.push(
trip.getStopTime(nextStops[i]).stop
);
}
}
// Return only the top 3 transfer Stops
if ( rtn.length > 3 ) {
rtn = [rtn[0], rtn[1], rtn[2]];
}
return callback(null, rtn);
});
} | [
"function",
"_getTransferStops",
"(",
"db",
",",
"origin",
",",
"destination",
",",
"stop",
",",
"trip",
",",
"callback",
")",
"{",
"// List of Transfer Stops",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Get Next Stops from this Stop",
"LineGraphTable",
".",
"getNextStops",
"(",
"db",
",",
"origin",
".",
"id",
",",
"destination",
".",
"id",
",",
"stop",
".",
"id",
",",
"function",
"(",
"err",
",",
"nextStops",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Get Remaining Stops on Trip",
"let",
"remainingStops",
"=",
"[",
"]",
";",
"let",
"stopFound",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trip",
".",
"stopTimes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"stopFound",
"&&",
"trip",
".",
"stopTimes",
"[",
"i",
"]",
".",
"stop",
".",
"id",
"===",
"stop",
".",
"id",
")",
"{",
"stopFound",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"stopFound",
")",
"{",
"remainingStops",
".",
"push",
"(",
"trip",
".",
"stopTimes",
"[",
"i",
"]",
".",
"stop",
".",
"id",
")",
";",
"}",
"}",
"// Get Next Stops that are remaining on this Trip",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"nextStops",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"remainingStops",
".",
"indexOf",
"(",
"nextStops",
"[",
"i",
"]",
")",
">",
"-",
"1",
")",
"{",
"rtn",
".",
"push",
"(",
"trip",
".",
"getStopTime",
"(",
"nextStops",
"[",
"i",
"]",
")",
".",
"stop",
")",
";",
"}",
"}",
"// Return only the top 3 transfer Stops",
"if",
"(",
"rtn",
".",
"length",
">",
"3",
")",
"{",
"rtn",
"=",
"[",
"rtn",
"[",
"0",
"]",
",",
"rtn",
"[",
"1",
"]",
",",
"rtn",
"[",
"2",
"]",
"]",
";",
"}",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
")",
";",
"}"
]
| Get a list of Stop IDs, sorted by transfer weight, that can be
used as a Transfer Stop for this Trip
@param {RightTrackDB} db The Right Track DB to query
@param {Stop} origin Origin Stop
@param {Stop} destination Destination Stop
@param {Stop} stop Reference Stop
@param {Trip} trip Trip to transfer from
@param {function} callback Callback function(err, stops)
@private | [
"Get",
"a",
"list",
"of",
"Stop",
"IDs",
"sorted",
"by",
"transfer",
"weight",
"that",
"can",
"be",
"used",
"as",
"a",
"Transfer",
"Stop",
"for",
"this",
"Trip"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L617-L660 |
40,437 | right-track/right-track-core | modules/search/search.js | _getTripsFromStop | function _getTripsFromStop(db, origin, destination, stop, tripSearchDates, excludeTrips, callback) {
// Get all possible following stops
LineGraphTable.getNextStops(db, origin.id, destination.id, stop.id, function(err, nextStops) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Get Trips from Stop
query.getTripsFromStop(db, stop, tripSearchDates, nextStops, function(err, trips) {
// Database Query Error
if ( err ) {
return callback(err);
}
// List of Direct and Indirect Trips
let direct = [];
let indirect = [];
// Sort Trips
for ( let i = 0; i < trips.length; i++ ) {
if ( excludeTrips.indexOf(trips[i].id) === -1 ) {
if ( _tripGoesTo(trips[i], stop, destination) ) {
direct.push(trips[i]);
}
else {
indirect.push(trips[i]);
}
}
}
// Return the Trips
return callback(null, direct, indirect);
});
});
} | javascript | function _getTripsFromStop(db, origin, destination, stop, tripSearchDates, excludeTrips, callback) {
// Get all possible following stops
LineGraphTable.getNextStops(db, origin.id, destination.id, stop.id, function(err, nextStops) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Get Trips from Stop
query.getTripsFromStop(db, stop, tripSearchDates, nextStops, function(err, trips) {
// Database Query Error
if ( err ) {
return callback(err);
}
// List of Direct and Indirect Trips
let direct = [];
let indirect = [];
// Sort Trips
for ( let i = 0; i < trips.length; i++ ) {
if ( excludeTrips.indexOf(trips[i].id) === -1 ) {
if ( _tripGoesTo(trips[i], stop, destination) ) {
direct.push(trips[i]);
}
else {
indirect.push(trips[i]);
}
}
}
// Return the Trips
return callback(null, direct, indirect);
});
});
} | [
"function",
"_getTripsFromStop",
"(",
"db",
",",
"origin",
",",
"destination",
",",
"stop",
",",
"tripSearchDates",
",",
"excludeTrips",
",",
"callback",
")",
"{",
"// Get all possible following stops",
"LineGraphTable",
".",
"getNextStops",
"(",
"db",
",",
"origin",
".",
"id",
",",
"destination",
".",
"id",
",",
"stop",
".",
"id",
",",
"function",
"(",
"err",
",",
"nextStops",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Get Trips from Stop",
"query",
".",
"getTripsFromStop",
"(",
"db",
",",
"stop",
",",
"tripSearchDates",
",",
"nextStops",
",",
"function",
"(",
"err",
",",
"trips",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// List of Direct and Indirect Trips",
"let",
"direct",
"=",
"[",
"]",
";",
"let",
"indirect",
"=",
"[",
"]",
";",
"// Sort Trips",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trips",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"excludeTrips",
".",
"indexOf",
"(",
"trips",
"[",
"i",
"]",
".",
"id",
")",
"===",
"-",
"1",
")",
"{",
"if",
"(",
"_tripGoesTo",
"(",
"trips",
"[",
"i",
"]",
",",
"stop",
",",
"destination",
")",
")",
"{",
"direct",
".",
"push",
"(",
"trips",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"indirect",
".",
"push",
"(",
"trips",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"// Return the Trips",
"return",
"callback",
"(",
"null",
",",
"direct",
",",
"indirect",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Get a List of Trips from the reference Stop that operate during the
TripSearchDates and along the Line Graph paths between the origin
and destination Stops
@param {RightTrackDB} db The Right Track DB to query
@param {Stop} origin Trip Origin Stop
@param {Stop} destination Trip Destination Stop
@param {Stop} stop Reference Stop
@param {TripSearchDate[]} tripSearchDates Trip Search Dates
@param {String[]} excludeTrips List of Trip IDs to exclude
@param {function} callback Callback function(err, direct, indirect)
@private | [
"Get",
"a",
"List",
"of",
"Trips",
"from",
"the",
"reference",
"Stop",
"that",
"operate",
"during",
"the",
"TripSearchDates",
"and",
"along",
"the",
"Line",
"Graph",
"paths",
"between",
"the",
"origin",
"and",
"destination",
"Stops"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L677-L718 |
40,438 | right-track/right-track-core | modules/search/search.js | _getTripSearchDates | function _getTripSearchDates(db, datetime, preMins, postMins, callback) {
// Get pre and post dates
let preDateTime = datetime.clone().deltaMins(-1*preMins);
let postDateTime = datetime.clone().deltaMins(postMins);
// List of TripSearchDates to return
let rtn = [];
// Counters
let done = 0;
let count = 0;
// ==== PRE AND POST DATES ARE SAME DAY ==== //
if ( preDateTime.getDateInt() === postDateTime.getDateInt() ) {
count = 1;
// Get Effective Services
CalendarTable.getServicesEffective(db, datetime.getDateInt(), function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Create new TripSearchDate
let tsd = new TripSearchDate(
preDateTime.getDateInt(),
preDateTime.getTimeSeconds(),
postDateTime.getTimeSeconds(),
services
);
// Add to List
rtn.push(tsd);
// Finish
_finish();
});
}
// ==== PRE AND POST DATES ARE DIFFERENT DAYS ==== //
else {
count = 2;
// Get Effective Services for Prev Day
CalendarTable.getServicesEffective(db, preDateTime.getDateInt(), function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Create new TripSearchDate
let tsd = new TripSearchDate(
preDateTime.getDateInt(),
preDateTime.getTimeSeconds(),
postDateTime.getTimeSeconds() + 86400,
services
);
// Add to List
rtn.push(tsd);
// Finish
_finish();
});
// Get Effective Services for Post Day
CalendarTable.getServicesEffective(db, postDateTime.getDateInt(), function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Create new TripSearchDate
let tsd = new TripSearchDate(
postDateTime.getDateInt(),
0,
postDateTime.getTimeSeconds(),
services
);
// Add to List
rtn.push(tsd);
// Finish
_finish();
});
}
// Finish processing a Trip Search Date
function _finish() {
done++;
if ( done === count ) {
return callback(null, rtn);
}
}
} | javascript | function _getTripSearchDates(db, datetime, preMins, postMins, callback) {
// Get pre and post dates
let preDateTime = datetime.clone().deltaMins(-1*preMins);
let postDateTime = datetime.clone().deltaMins(postMins);
// List of TripSearchDates to return
let rtn = [];
// Counters
let done = 0;
let count = 0;
// ==== PRE AND POST DATES ARE SAME DAY ==== //
if ( preDateTime.getDateInt() === postDateTime.getDateInt() ) {
count = 1;
// Get Effective Services
CalendarTable.getServicesEffective(db, datetime.getDateInt(), function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Create new TripSearchDate
let tsd = new TripSearchDate(
preDateTime.getDateInt(),
preDateTime.getTimeSeconds(),
postDateTime.getTimeSeconds(),
services
);
// Add to List
rtn.push(tsd);
// Finish
_finish();
});
}
// ==== PRE AND POST DATES ARE DIFFERENT DAYS ==== //
else {
count = 2;
// Get Effective Services for Prev Day
CalendarTable.getServicesEffective(db, preDateTime.getDateInt(), function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Create new TripSearchDate
let tsd = new TripSearchDate(
preDateTime.getDateInt(),
preDateTime.getTimeSeconds(),
postDateTime.getTimeSeconds() + 86400,
services
);
// Add to List
rtn.push(tsd);
// Finish
_finish();
});
// Get Effective Services for Post Day
CalendarTable.getServicesEffective(db, postDateTime.getDateInt(), function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Create new TripSearchDate
let tsd = new TripSearchDate(
postDateTime.getDateInt(),
0,
postDateTime.getTimeSeconds(),
services
);
// Add to List
rtn.push(tsd);
// Finish
_finish();
});
}
// Finish processing a Trip Search Date
function _finish() {
done++;
if ( done === count ) {
return callback(null, rtn);
}
}
} | [
"function",
"_getTripSearchDates",
"(",
"db",
",",
"datetime",
",",
"preMins",
",",
"postMins",
",",
"callback",
")",
"{",
"// Get pre and post dates",
"let",
"preDateTime",
"=",
"datetime",
".",
"clone",
"(",
")",
".",
"deltaMins",
"(",
"-",
"1",
"*",
"preMins",
")",
";",
"let",
"postDateTime",
"=",
"datetime",
".",
"clone",
"(",
")",
".",
"deltaMins",
"(",
"postMins",
")",
";",
"// List of TripSearchDates to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Counters",
"let",
"done",
"=",
"0",
";",
"let",
"count",
"=",
"0",
";",
"// ==== PRE AND POST DATES ARE SAME DAY ==== //",
"if",
"(",
"preDateTime",
".",
"getDateInt",
"(",
")",
"===",
"postDateTime",
".",
"getDateInt",
"(",
")",
")",
"{",
"count",
"=",
"1",
";",
"// Get Effective Services",
"CalendarTable",
".",
"getServicesEffective",
"(",
"db",
",",
"datetime",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"err",
",",
"services",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Create new TripSearchDate",
"let",
"tsd",
"=",
"new",
"TripSearchDate",
"(",
"preDateTime",
".",
"getDateInt",
"(",
")",
",",
"preDateTime",
".",
"getTimeSeconds",
"(",
")",
",",
"postDateTime",
".",
"getTimeSeconds",
"(",
")",
",",
"services",
")",
";",
"// Add to List",
"rtn",
".",
"push",
"(",
"tsd",
")",
";",
"// Finish",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"// ==== PRE AND POST DATES ARE DIFFERENT DAYS ==== //",
"else",
"{",
"count",
"=",
"2",
";",
"// Get Effective Services for Prev Day",
"CalendarTable",
".",
"getServicesEffective",
"(",
"db",
",",
"preDateTime",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"err",
",",
"services",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Create new TripSearchDate",
"let",
"tsd",
"=",
"new",
"TripSearchDate",
"(",
"preDateTime",
".",
"getDateInt",
"(",
")",
",",
"preDateTime",
".",
"getTimeSeconds",
"(",
")",
",",
"postDateTime",
".",
"getTimeSeconds",
"(",
")",
"+",
"86400",
",",
"services",
")",
";",
"// Add to List",
"rtn",
".",
"push",
"(",
"tsd",
")",
";",
"// Finish",
"_finish",
"(",
")",
";",
"}",
")",
";",
"// Get Effective Services for Post Day",
"CalendarTable",
".",
"getServicesEffective",
"(",
"db",
",",
"postDateTime",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"err",
",",
"services",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Create new TripSearchDate",
"let",
"tsd",
"=",
"new",
"TripSearchDate",
"(",
"postDateTime",
".",
"getDateInt",
"(",
")",
",",
"0",
",",
"postDateTime",
".",
"getTimeSeconds",
"(",
")",
",",
"services",
")",
";",
"// Add to List",
"rtn",
".",
"push",
"(",
"tsd",
")",
";",
"// Finish",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"// Finish processing a Trip Search Date",
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"done",
"===",
"count",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
"}",
"}"
]
| Get the Trip Search Dates for the specified search range
@param {RightTrackDB} db The Right Track DB to query
@param {DateTime} datetime The Date/Time of the search starting point
@param {int} preMins The number of mins before the datetime to include
@param {int} postMins The number of mins after the datetime to include
@param {function} callback Callback function(err, tripSearchDates)
@private | [
"Get",
"the",
"Trip",
"Search",
"Dates",
"for",
"the",
"specified",
"search",
"range"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/search.js#L731-L840 |
40,439 | dimsmol/npgt | lib/upsert.js | function (db, options, cb) {
this.db = db;
this.cb = cb;
this.updateQueryMaker = options.update;
this.insertQueryMaker = options.insert;
this.maxUpdateAttemptsCount = options.maxUpdateAttemptsCount || 2;
this.transform = options.transform;
this.insertFirst = !!options.insertFirst;
this.nonQuery = !!options.nonQuery;
var self = this;
this.updateAttemptsCount = 0;
this.updateOrInsertBound = function () {
self.updateOrInsert();
};
} | javascript | function (db, options, cb) {
this.db = db;
this.cb = cb;
this.updateQueryMaker = options.update;
this.insertQueryMaker = options.insert;
this.maxUpdateAttemptsCount = options.maxUpdateAttemptsCount || 2;
this.transform = options.transform;
this.insertFirst = !!options.insertFirst;
this.nonQuery = !!options.nonQuery;
var self = this;
this.updateAttemptsCount = 0;
this.updateOrInsertBound = function () {
self.updateOrInsert();
};
} | [
"function",
"(",
"db",
",",
"options",
",",
"cb",
")",
"{",
"this",
".",
"db",
"=",
"db",
";",
"this",
".",
"cb",
"=",
"cb",
";",
"this",
".",
"updateQueryMaker",
"=",
"options",
".",
"update",
";",
"this",
".",
"insertQueryMaker",
"=",
"options",
".",
"insert",
";",
"this",
".",
"maxUpdateAttemptsCount",
"=",
"options",
".",
"maxUpdateAttemptsCount",
"||",
"2",
";",
"this",
".",
"transform",
"=",
"options",
".",
"transform",
";",
"this",
".",
"insertFirst",
"=",
"!",
"!",
"options",
".",
"insertFirst",
";",
"this",
".",
"nonQuery",
"=",
"!",
"!",
"options",
".",
"nonQuery",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"updateAttemptsCount",
"=",
"0",
";",
"this",
".",
"updateOrInsertBound",
"=",
"function",
"(",
")",
"{",
"self",
".",
"updateOrInsert",
"(",
")",
";",
"}",
";",
"}"
]
| WARN doesn't support transactions for now | [
"WARN",
"doesn",
"t",
"support",
"transactions",
"for",
"now"
]
| ff367b0b5a96c811ebbacfd45156f3bc4fa02a37 | https://github.com/dimsmol/npgt/blob/ff367b0b5a96c811ebbacfd45156f3bc4fa02a37/lib/upsert.js#L6-L21 |
|
40,440 | nodeGame/nodegame-generator | games/dictator/waitroom/waitroom.js | clientConnects | function clientConnects(p) {
var pList;
var nPlayers;
var waitTime;
var widgetConfig;
node.remoteSetup('page', p.id, {
clearBody: true,
title: { title: 'Welcome!', addToBody: true }
});
node.remoteSetup('widgets', p.id, {
destroyAll: true,
append: { 'WaitingRoom': {} }
});
if (waitRoom.isRoomOpen()) {
console.log('Client connected to waiting room: ', p.id);
// Mark code as used.
channel.registry.markInvalid(p.id);
pList = waitRoom.clients.player;
nPlayers = pList.size();
if (waitRoom.START_DATE) {
waitTime = new Date(waitRoom.START_DATE).getTime() -
(new Date().getTime());
}
else if (waitRoom.MAX_WAIT_TIME) {
waitTime = waitRoom.MAX_WAIT_TIME;
}
else {
waitTime = null; // Widget won't start timer.
}
// Send the number of minutes to wait and all waitRoom settings.
widgetConfig = waitRoom.makeWidgetConfig();
widgetConfig.waitTime = waitTime;
node.remoteSetup('waitroom', p.id, widgetConfig);
console.log('NPL ', nPlayers);
// Notify all players of new connection.
node.say('PLAYERSCONNECTED', 'ROOM', nPlayers);
// Start counting a timeout for max stay in waiting room.
waitRoom.makeTimeOut(p.id, waitTime);
// Wait for all players to connect.
if (nPlayers < waitRoom.POOL_SIZE) return;
if (waitRoom.EXECUTION_MODE === 'WAIT_FOR_N_PLAYERS') {
waitRoom.dispatch({
action: 'AllPlayersConnected',
exit: 0
});
}
}
else {
node.say('ROOM_CLOSED', p.id);
}
} | javascript | function clientConnects(p) {
var pList;
var nPlayers;
var waitTime;
var widgetConfig;
node.remoteSetup('page', p.id, {
clearBody: true,
title: { title: 'Welcome!', addToBody: true }
});
node.remoteSetup('widgets', p.id, {
destroyAll: true,
append: { 'WaitingRoom': {} }
});
if (waitRoom.isRoomOpen()) {
console.log('Client connected to waiting room: ', p.id);
// Mark code as used.
channel.registry.markInvalid(p.id);
pList = waitRoom.clients.player;
nPlayers = pList.size();
if (waitRoom.START_DATE) {
waitTime = new Date(waitRoom.START_DATE).getTime() -
(new Date().getTime());
}
else if (waitRoom.MAX_WAIT_TIME) {
waitTime = waitRoom.MAX_WAIT_TIME;
}
else {
waitTime = null; // Widget won't start timer.
}
// Send the number of minutes to wait and all waitRoom settings.
widgetConfig = waitRoom.makeWidgetConfig();
widgetConfig.waitTime = waitTime;
node.remoteSetup('waitroom', p.id, widgetConfig);
console.log('NPL ', nPlayers);
// Notify all players of new connection.
node.say('PLAYERSCONNECTED', 'ROOM', nPlayers);
// Start counting a timeout for max stay in waiting room.
waitRoom.makeTimeOut(p.id, waitTime);
// Wait for all players to connect.
if (nPlayers < waitRoom.POOL_SIZE) return;
if (waitRoom.EXECUTION_MODE === 'WAIT_FOR_N_PLAYERS') {
waitRoom.dispatch({
action: 'AllPlayersConnected',
exit: 0
});
}
}
else {
node.say('ROOM_CLOSED', p.id);
}
} | [
"function",
"clientConnects",
"(",
"p",
")",
"{",
"var",
"pList",
";",
"var",
"nPlayers",
";",
"var",
"waitTime",
";",
"var",
"widgetConfig",
";",
"node",
".",
"remoteSetup",
"(",
"'page'",
",",
"p",
".",
"id",
",",
"{",
"clearBody",
":",
"true",
",",
"title",
":",
"{",
"title",
":",
"'Welcome!'",
",",
"addToBody",
":",
"true",
"}",
"}",
")",
";",
"node",
".",
"remoteSetup",
"(",
"'widgets'",
",",
"p",
".",
"id",
",",
"{",
"destroyAll",
":",
"true",
",",
"append",
":",
"{",
"'WaitingRoom'",
":",
"{",
"}",
"}",
"}",
")",
";",
"if",
"(",
"waitRoom",
".",
"isRoomOpen",
"(",
")",
")",
"{",
"console",
".",
"log",
"(",
"'Client connected to waiting room: '",
",",
"p",
".",
"id",
")",
";",
"// Mark code as used.",
"channel",
".",
"registry",
".",
"markInvalid",
"(",
"p",
".",
"id",
")",
";",
"pList",
"=",
"waitRoom",
".",
"clients",
".",
"player",
";",
"nPlayers",
"=",
"pList",
".",
"size",
"(",
")",
";",
"if",
"(",
"waitRoom",
".",
"START_DATE",
")",
"{",
"waitTime",
"=",
"new",
"Date",
"(",
"waitRoom",
".",
"START_DATE",
")",
".",
"getTime",
"(",
")",
"-",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"waitRoom",
".",
"MAX_WAIT_TIME",
")",
"{",
"waitTime",
"=",
"waitRoom",
".",
"MAX_WAIT_TIME",
";",
"}",
"else",
"{",
"waitTime",
"=",
"null",
";",
"// Widget won't start timer.",
"}",
"// Send the number of minutes to wait and all waitRoom settings.",
"widgetConfig",
"=",
"waitRoom",
".",
"makeWidgetConfig",
"(",
")",
";",
"widgetConfig",
".",
"waitTime",
"=",
"waitTime",
";",
"node",
".",
"remoteSetup",
"(",
"'waitroom'",
",",
"p",
".",
"id",
",",
"widgetConfig",
")",
";",
"console",
".",
"log",
"(",
"'NPL '",
",",
"nPlayers",
")",
";",
"// Notify all players of new connection.",
"node",
".",
"say",
"(",
"'PLAYERSCONNECTED'",
",",
"'ROOM'",
",",
"nPlayers",
")",
";",
"// Start counting a timeout for max stay in waiting room.",
"waitRoom",
".",
"makeTimeOut",
"(",
"p",
".",
"id",
",",
"waitTime",
")",
";",
"// Wait for all players to connect.",
"if",
"(",
"nPlayers",
"<",
"waitRoom",
".",
"POOL_SIZE",
")",
"return",
";",
"if",
"(",
"waitRoom",
".",
"EXECUTION_MODE",
"===",
"'WAIT_FOR_N_PLAYERS'",
")",
"{",
"waitRoom",
".",
"dispatch",
"(",
"{",
"action",
":",
"'AllPlayersConnected'",
",",
"exit",
":",
"0",
"}",
")",
";",
"}",
"}",
"else",
"{",
"node",
".",
"say",
"(",
"'ROOM_CLOSED'",
",",
"p",
".",
"id",
")",
";",
"}",
"}"
]
| Using self-calling function to put `firstTime` into closure. | [
"Using",
"self",
"-",
"calling",
"function",
"to",
"put",
"firstTime",
"into",
"closure",
"."
]
| 22afddec9ddc8a56128da4962c3923cd39bac37e | https://github.com/nodeGame/nodegame-generator/blob/22afddec9ddc8a56128da4962c3923cd39bac37e/games/dictator/waitroom/waitroom.js#L48-L111 |
40,441 | right-track/right-track-core | modules/query/CalendarTable.js | getServicesEffective | function getServicesEffective(db, date, callback) {
// Check Cache for Effective Services
let cacheKey = db.id + "-" + date;
let cache = cache_servicesEffectiveByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Get the Default Services
getServicesDefault(db, date, function(defaultError, defaultServices) {
// Get the Service Exceptions
getServiceExceptions(db, date, function(exceptionsError, serviceExceptions) {
// Check for Default Services Error
if ( defaultError ) {
return callback(defaultError);
}
// Check for Service Exceptions Error
if ( exceptionsError ) {
return callback(exceptionsError);
}
// List of Service IDs to Add to Default Services
let serviceIdsToAdd = [];
// Parse the exceptions
for ( let i = 0; i < serviceExceptions.length; i++ ) {
let serviceException = serviceExceptions[i];
// Exception Type: Added
if ( serviceException.exceptionType === ServiceException.SERVICE_ADDED ) {
// Make sure service isn't already in list
let found = false;
for ( let j = 0; j < defaultServices.length; j++ ) {
if ( defaultServices[j].id === serviceException.serviceId ) {
found = true;
}
}
// Flag Service ID to add
if ( !found ) {
serviceIdsToAdd.push(serviceException.serviceId);
}
}
// Exception Type: Removed
else if ( serviceException.exceptionType === ServiceException.SERVICE_REMOVED ) {
// Find matching default service
let removeIndex = -1;
for ( let j = 0; j < defaultServices.length; j++ ) {
if ( defaultServices[j].id === serviceException.serviceId ) {
removeIndex = j;
}
}
// Remove the matching service from default services list
if ( removeIndex !== -1 ) {
defaultServices.splice(removeIndex, 1);
}
}
}
// Add services, if we need to
if ( serviceIdsToAdd.length > 0 ) {
getService(db, serviceIdsToAdd, function(err, services) {
// Error Getting Services
if ( err ) {
return callback(err);
}
// Add Services to list
for (let i = 0; i < services.length; i++) {
let service = services[i];
defaultServices.push(service);
}
// Add Services to Cache
cache_servicesEffectiveByDate.put(cacheKey, defaultServices);
// Return Services
return callback(null, defaultServices);
});
}
// Return Default Services
else {
// Add Services to Cache
cache_servicesEffectiveByDate.put(cacheKey, defaultServices);
return callback(null, defaultServices);
}
});
});
} | javascript | function getServicesEffective(db, date, callback) {
// Check Cache for Effective Services
let cacheKey = db.id + "-" + date;
let cache = cache_servicesEffectiveByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Get the Default Services
getServicesDefault(db, date, function(defaultError, defaultServices) {
// Get the Service Exceptions
getServiceExceptions(db, date, function(exceptionsError, serviceExceptions) {
// Check for Default Services Error
if ( defaultError ) {
return callback(defaultError);
}
// Check for Service Exceptions Error
if ( exceptionsError ) {
return callback(exceptionsError);
}
// List of Service IDs to Add to Default Services
let serviceIdsToAdd = [];
// Parse the exceptions
for ( let i = 0; i < serviceExceptions.length; i++ ) {
let serviceException = serviceExceptions[i];
// Exception Type: Added
if ( serviceException.exceptionType === ServiceException.SERVICE_ADDED ) {
// Make sure service isn't already in list
let found = false;
for ( let j = 0; j < defaultServices.length; j++ ) {
if ( defaultServices[j].id === serviceException.serviceId ) {
found = true;
}
}
// Flag Service ID to add
if ( !found ) {
serviceIdsToAdd.push(serviceException.serviceId);
}
}
// Exception Type: Removed
else if ( serviceException.exceptionType === ServiceException.SERVICE_REMOVED ) {
// Find matching default service
let removeIndex = -1;
for ( let j = 0; j < defaultServices.length; j++ ) {
if ( defaultServices[j].id === serviceException.serviceId ) {
removeIndex = j;
}
}
// Remove the matching service from default services list
if ( removeIndex !== -1 ) {
defaultServices.splice(removeIndex, 1);
}
}
}
// Add services, if we need to
if ( serviceIdsToAdd.length > 0 ) {
getService(db, serviceIdsToAdd, function(err, services) {
// Error Getting Services
if ( err ) {
return callback(err);
}
// Add Services to list
for (let i = 0; i < services.length; i++) {
let service = services[i];
defaultServices.push(service);
}
// Add Services to Cache
cache_servicesEffectiveByDate.put(cacheKey, defaultServices);
// Return Services
return callback(null, defaultServices);
});
}
// Return Default Services
else {
// Add Services to Cache
cache_servicesEffectiveByDate.put(cacheKey, defaultServices);
return callback(null, defaultServices);
}
});
});
} | [
"function",
"getServicesEffective",
"(",
"db",
",",
"date",
",",
"callback",
")",
"{",
"// Check Cache for Effective Services",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_servicesEffectiveByDate",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Get the Default Services",
"getServicesDefault",
"(",
"db",
",",
"date",
",",
"function",
"(",
"defaultError",
",",
"defaultServices",
")",
"{",
"// Get the Service Exceptions",
"getServiceExceptions",
"(",
"db",
",",
"date",
",",
"function",
"(",
"exceptionsError",
",",
"serviceExceptions",
")",
"{",
"// Check for Default Services Error",
"if",
"(",
"defaultError",
")",
"{",
"return",
"callback",
"(",
"defaultError",
")",
";",
"}",
"// Check for Service Exceptions Error",
"if",
"(",
"exceptionsError",
")",
"{",
"return",
"callback",
"(",
"exceptionsError",
")",
";",
"}",
"// List of Service IDs to Add to Default Services",
"let",
"serviceIdsToAdd",
"=",
"[",
"]",
";",
"// Parse the exceptions",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"serviceExceptions",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"serviceException",
"=",
"serviceExceptions",
"[",
"i",
"]",
";",
"// Exception Type: Added",
"if",
"(",
"serviceException",
".",
"exceptionType",
"===",
"ServiceException",
".",
"SERVICE_ADDED",
")",
"{",
"// Make sure service isn't already in list",
"let",
"found",
"=",
"false",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"defaultServices",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"defaultServices",
"[",
"j",
"]",
".",
"id",
"===",
"serviceException",
".",
"serviceId",
")",
"{",
"found",
"=",
"true",
";",
"}",
"}",
"// Flag Service ID to add",
"if",
"(",
"!",
"found",
")",
"{",
"serviceIdsToAdd",
".",
"push",
"(",
"serviceException",
".",
"serviceId",
")",
";",
"}",
"}",
"// Exception Type: Removed",
"else",
"if",
"(",
"serviceException",
".",
"exceptionType",
"===",
"ServiceException",
".",
"SERVICE_REMOVED",
")",
"{",
"// Find matching default service",
"let",
"removeIndex",
"=",
"-",
"1",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"defaultServices",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"defaultServices",
"[",
"j",
"]",
".",
"id",
"===",
"serviceException",
".",
"serviceId",
")",
"{",
"removeIndex",
"=",
"j",
";",
"}",
"}",
"// Remove the matching service from default services list",
"if",
"(",
"removeIndex",
"!==",
"-",
"1",
")",
"{",
"defaultServices",
".",
"splice",
"(",
"removeIndex",
",",
"1",
")",
";",
"}",
"}",
"}",
"// Add services, if we need to",
"if",
"(",
"serviceIdsToAdd",
".",
"length",
">",
"0",
")",
"{",
"getService",
"(",
"db",
",",
"serviceIdsToAdd",
",",
"function",
"(",
"err",
",",
"services",
")",
"{",
"// Error Getting Services",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add Services to list",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"services",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"service",
"=",
"services",
"[",
"i",
"]",
";",
"defaultServices",
".",
"push",
"(",
"service",
")",
";",
"}",
"// Add Services to Cache",
"cache_servicesEffectiveByDate",
".",
"put",
"(",
"cacheKey",
",",
"defaultServices",
")",
";",
"// Return Services",
"return",
"callback",
"(",
"null",
",",
"defaultServices",
")",
";",
"}",
")",
";",
"}",
"// Return Default Services",
"else",
"{",
"// Add Services to Cache",
"cache_servicesEffectiveByDate",
".",
"put",
"(",
"cacheKey",
",",
"defaultServices",
")",
";",
"return",
"callback",
"(",
"null",
",",
"defaultServices",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Get the Services in effect on the specified date. This includes
any exceptions found in the calendar_dates file.
@param {RightTrackDB} db The Right Track Database to query
@param {int} date The date to query (yyyymmdd)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Service[]} callback.services The selected Services | [
"Get",
"the",
"Services",
"in",
"effect",
"on",
"the",
"specified",
"date",
".",
"This",
"includes",
"any",
"exceptions",
"found",
"in",
"the",
"calendar_dates",
"file",
"."
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/CalendarTable.js#L186-L298 |
40,442 | right-track/right-track-core | modules/query/CalendarTable.js | function(db, date, callback) {
// Check cache for services
let cacheKey = db.id + "-" + date;
let cache = cache_servicesDefaultByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Array of default services to return
let rtn = [];
// Get day of week
let dt = DateTime.createFromDate(date);
let dow = dt.getDateDOW();
// Get default services
let select = "SELECT service_id, monday, tuesday, wednesday, thursday, friday, " +
"saturday, sunday, start_date, end_date FROM gtfs_calendar WHERE " + dow +
"=" + Service.SERVICE_AVAILABLE + " AND start_date<=" + date + " AND " +
"end_date>=" + date + ";";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Parse each row in the results...
for ( let i = 0; i < results.length; i++ ) {
let row = results[i];
let service = new Service(
row.service_id,
row.monday,
row.tuesday,
row.wednesday,
row.thursday,
row.friday,
row.saturday,
row.sunday,
row.start_date,
row.end_date
);
rtn.push(service);
}
// Add Services to Cache
cache_servicesDefaultByDate.put(cacheKey, rtn);
// Return the default services with provided callback
return callback(null, rtn);
});
} | javascript | function(db, date, callback) {
// Check cache for services
let cacheKey = db.id + "-" + date;
let cache = cache_servicesDefaultByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Array of default services to return
let rtn = [];
// Get day of week
let dt = DateTime.createFromDate(date);
let dow = dt.getDateDOW();
// Get default services
let select = "SELECT service_id, monday, tuesday, wednesday, thursday, friday, " +
"saturday, sunday, start_date, end_date FROM gtfs_calendar WHERE " + dow +
"=" + Service.SERVICE_AVAILABLE + " AND start_date<=" + date + " AND " +
"end_date>=" + date + ";";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Parse each row in the results...
for ( let i = 0; i < results.length; i++ ) {
let row = results[i];
let service = new Service(
row.service_id,
row.monday,
row.tuesday,
row.wednesday,
row.thursday,
row.friday,
row.saturday,
row.sunday,
row.start_date,
row.end_date
);
rtn.push(service);
}
// Add Services to Cache
cache_servicesDefaultByDate.put(cacheKey, rtn);
// Return the default services with provided callback
return callback(null, rtn);
});
} | [
"function",
"(",
"db",
",",
"date",
",",
"callback",
")",
"{",
"// Check cache for services",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_servicesDefaultByDate",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Array of default services to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Get day of week",
"let",
"dt",
"=",
"DateTime",
".",
"createFromDate",
"(",
"date",
")",
";",
"let",
"dow",
"=",
"dt",
".",
"getDateDOW",
"(",
")",
";",
"// Get default services",
"let",
"select",
"=",
"\"SELECT service_id, monday, tuesday, wednesday, thursday, friday, \"",
"+",
"\"saturday, sunday, start_date, end_date FROM gtfs_calendar WHERE \"",
"+",
"dow",
"+",
"\"=\"",
"+",
"Service",
".",
"SERVICE_AVAILABLE",
"+",
"\" AND start_date<=\"",
"+",
"date",
"+",
"\" AND \"",
"+",
"\"end_date>=\"",
"+",
"date",
"+",
"\";\"",
";",
"// Query the database",
"db",
".",
"select",
"(",
"select",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Parse each row in the results...",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"row",
"=",
"results",
"[",
"i",
"]",
";",
"let",
"service",
"=",
"new",
"Service",
"(",
"row",
".",
"service_id",
",",
"row",
".",
"monday",
",",
"row",
".",
"tuesday",
",",
"row",
".",
"wednesday",
",",
"row",
".",
"thursday",
",",
"row",
".",
"friday",
",",
"row",
".",
"saturday",
",",
"row",
".",
"sunday",
",",
"row",
".",
"start_date",
",",
"row",
".",
"end_date",
")",
";",
"rtn",
".",
"push",
"(",
"service",
")",
";",
"}",
"// Add Services to Cache",
"cache_servicesDefaultByDate",
".",
"put",
"(",
"cacheKey",
",",
"rtn",
")",
";",
"// Return the default services with provided callback",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
")",
";",
"}"
]
| Get the default Services in effect on the specified date. These
services don't include any changes due to service exceptions.
@param {RightTrackDB} db The Right Track Database to query
@param {int} date The date to query (yyyymmdd)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Service[]} callback.services The selected Services | [
"Get",
"the",
"default",
"Services",
"in",
"effect",
"on",
"the",
"specified",
"date",
".",
"These",
"services",
"don",
"t",
"include",
"any",
"changes",
"due",
"to",
"service",
"exceptions",
"."
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/CalendarTable.js#L311-L370 |
|
40,443 | right-track/right-track-core | modules/query/CalendarTable.js | function(db, date, callback) {
// Check cache for service exceptions
let cacheKey = db.id + "-" + date;
let cache = cache_serviceExceptionsByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Array of Service Exceptions to return
let rtn = [];
// Get service exceptions from calendar_dates
let select = "SELECT service_id, date, exception_type " +
"FROM gtfs_calendar_dates WHERE date=" + date + ";";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Parse each row in the results
for ( let i = 0; i < results.length; i++ ) {
let row = results[i];
// Create Service Exception
let se = new ServiceException(
row.service_id,
row.date,
row.exception_type
);
// Add Service Exception to return list
rtn.push(se);
}
// Add Service Exceptions to cache
cache_serviceExceptionsByDate.put(cacheKey, rtn);
// Return service exceptions with provided callback
return callback(null, rtn);
});
} | javascript | function(db, date, callback) {
// Check cache for service exceptions
let cacheKey = db.id + "-" + date;
let cache = cache_serviceExceptionsByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Array of Service Exceptions to return
let rtn = [];
// Get service exceptions from calendar_dates
let select = "SELECT service_id, date, exception_type " +
"FROM gtfs_calendar_dates WHERE date=" + date + ";";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Parse each row in the results
for ( let i = 0; i < results.length; i++ ) {
let row = results[i];
// Create Service Exception
let se = new ServiceException(
row.service_id,
row.date,
row.exception_type
);
// Add Service Exception to return list
rtn.push(se);
}
// Add Service Exceptions to cache
cache_serviceExceptionsByDate.put(cacheKey, rtn);
// Return service exceptions with provided callback
return callback(null, rtn);
});
} | [
"function",
"(",
"db",
",",
"date",
",",
"callback",
")",
"{",
"// Check cache for service exceptions",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_serviceExceptionsByDate",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Array of Service Exceptions to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Get service exceptions from calendar_dates",
"let",
"select",
"=",
"\"SELECT service_id, date, exception_type \"",
"+",
"\"FROM gtfs_calendar_dates WHERE date=\"",
"+",
"date",
"+",
"\";\"",
";",
"// Query the database",
"db",
".",
"select",
"(",
"select",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Parse each row in the results",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"row",
"=",
"results",
"[",
"i",
"]",
";",
"// Create Service Exception",
"let",
"se",
"=",
"new",
"ServiceException",
"(",
"row",
".",
"service_id",
",",
"row",
".",
"date",
",",
"row",
".",
"exception_type",
")",
";",
"// Add Service Exception to return list",
"rtn",
".",
"push",
"(",
"se",
")",
";",
"}",
"// Add Service Exceptions to cache",
"cache_serviceExceptionsByDate",
".",
"put",
"(",
"cacheKey",
",",
"rtn",
")",
";",
"// Return service exceptions with provided callback",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
")",
";",
"}"
]
| Get the Service Exceptions in effect on the specified date. This includes
Services that are either added or removed on the specified date.
@param {RightTrackDB} db The Right Track Database to query
@param {int} date The date to query (yyyymmdd)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {ServiceException[]} callback.services The selected Service Exceptions | [
"Get",
"the",
"Service",
"Exceptions",
"in",
"effect",
"on",
"the",
"specified",
"date",
".",
"This",
"includes",
"Services",
"that",
"are",
"either",
"added",
"or",
"removed",
"on",
"the",
"specified",
"date",
"."
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/CalendarTable.js#L383-L430 |
|
40,444 | jstransformers/jstransformer-jstransformer | index.js | getTransform | function getTransform(options) {
if (typeof options === 'string' || options instanceof String) {
return options
}
if (typeof options === 'object' && options.engine) {
return options.engine
}
throw new Error('options.engine not found.')
} | javascript | function getTransform(options) {
if (typeof options === 'string' || options instanceof String) {
return options
}
if (typeof options === 'object' && options.engine) {
return options.engine
}
throw new Error('options.engine not found.')
} | [
"function",
"getTransform",
"(",
"options",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'string'",
"||",
"options",
"instanceof",
"String",
")",
"{",
"return",
"options",
"}",
"if",
"(",
"typeof",
"options",
"===",
"'object'",
"&&",
"options",
".",
"engine",
")",
"{",
"return",
"options",
".",
"engine",
"}",
"throw",
"new",
"Error",
"(",
"'options.engine not found.'",
")",
"}"
]
| Returns the name of the transformer from the given options. | [
"Returns",
"the",
"name",
"of",
"the",
"transformer",
"from",
"the",
"given",
"options",
"."
]
| 1c98419be2071f84a9ac4d5a62bd5e9c30f3a8bd | https://github.com/jstransformers/jstransformer-jstransformer/blob/1c98419be2071f84a9ac4d5a62bd5e9c30f3a8bd/index.js#L11-L21 |
40,445 | jstransformers/jstransformer-jstransformer | index.js | constructTransformer | function constructTransformer(options) {
const transform = getTransform(options)
if (transform && typeof transform === 'object') {
return jstransformer(transform)
}
return jstransformer(require('jstransformer-' + transform))
} | javascript | function constructTransformer(options) {
const transform = getTransform(options)
if (transform && typeof transform === 'object') {
return jstransformer(transform)
}
return jstransformer(require('jstransformer-' + transform))
} | [
"function",
"constructTransformer",
"(",
"options",
")",
"{",
"const",
"transform",
"=",
"getTransform",
"(",
"options",
")",
"if",
"(",
"transform",
"&&",
"typeof",
"transform",
"===",
"'object'",
")",
"{",
"return",
"jstransformer",
"(",
"transform",
")",
"}",
"return",
"jstransformer",
"(",
"require",
"(",
"'jstransformer-'",
"+",
"transform",
")",
")",
"}"
]
| Constructs a new JSTransformer from the given options. | [
"Constructs",
"a",
"new",
"JSTransformer",
"from",
"the",
"given",
"options",
"."
]
| 1c98419be2071f84a9ac4d5a62bd5e9c30f3a8bd | https://github.com/jstransformers/jstransformer-jstransformer/blob/1c98419be2071f84a9ac4d5a62bd5e9c30f3a8bd/index.js#L26-L33 |
40,446 | canjs/can-validate-interface | index.js | makeInterfaceValidator | function makeInterfaceValidator(interfacePropArrays) {
var props = flatten(interfacePropArrays);
return function(base) {
var missingProps = props.reduce(function(missing, prop) {
return prop in base ? missing : missing.concat(prop);
}, []);
return missingProps.length ? {message:"missing expected properties", related: missingProps} : undefined;
};
} | javascript | function makeInterfaceValidator(interfacePropArrays) {
var props = flatten(interfacePropArrays);
return function(base) {
var missingProps = props.reduce(function(missing, prop) {
return prop in base ? missing : missing.concat(prop);
}, []);
return missingProps.length ? {message:"missing expected properties", related: missingProps} : undefined;
};
} | [
"function",
"makeInterfaceValidator",
"(",
"interfacePropArrays",
")",
"{",
"var",
"props",
"=",
"flatten",
"(",
"interfacePropArrays",
")",
";",
"return",
"function",
"(",
"base",
")",
"{",
"var",
"missingProps",
"=",
"props",
".",
"reduce",
"(",
"function",
"(",
"missing",
",",
"prop",
")",
"{",
"return",
"prop",
"in",
"base",
"?",
"missing",
":",
"missing",
".",
"concat",
"(",
"prop",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"missingProps",
".",
"length",
"?",
"{",
"message",
":",
"\"missing expected properties\"",
",",
"related",
":",
"missingProps",
"}",
":",
"undefined",
";",
"}",
";",
"}"
]
| return a function that validates it's argument has all the properties in the interfacePropArrays | [
"return",
"a",
"function",
"that",
"validates",
"it",
"s",
"argument",
"has",
"all",
"the",
"properties",
"in",
"the",
"interfacePropArrays"
]
| 3aa92f8dfd5f2733daa7a2d0f3da55d9d0a09e7a | https://github.com/canjs/can-validate-interface/blob/3aa92f8dfd5f2733daa7a2d0f3da55d9d0a09e7a/index.js#L10-L20 |
40,447 | right-track/right-track-core | modules/query/LinksTable.js | getLinks | function getLinks(db, callback) {
// Check cache for links
let cacheKey = db.id + "-" + 'links';
let cache = cache_links.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build select statement
let select = "SELECT link_category_title, link_title, link_description, link_url FROM rt_links;";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// List of links to return
let rtn = [];
// Parse each row
for ( let i = 0; i < results.length; i++ ) {
let row = results[i];
// Build the link
let link = new Link(
row.link_category_title,
row.link_title,
row.link_description,
row.link_url
);
// Add link to list
rtn.push(link);
}
// Add links to cache
cache_links.put(cacheKey, rtn);
// Return the links with the callback
return callback(null, rtn);
});
} | javascript | function getLinks(db, callback) {
// Check cache for links
let cacheKey = db.id + "-" + 'links';
let cache = cache_links.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build select statement
let select = "SELECT link_category_title, link_title, link_description, link_url FROM rt_links;";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// List of links to return
let rtn = [];
// Parse each row
for ( let i = 0; i < results.length; i++ ) {
let row = results[i];
// Build the link
let link = new Link(
row.link_category_title,
row.link_title,
row.link_description,
row.link_url
);
// Add link to list
rtn.push(link);
}
// Add links to cache
cache_links.put(cacheKey, rtn);
// Return the links with the callback
return callback(null, rtn);
});
} | [
"function",
"getLinks",
"(",
"db",
",",
"callback",
")",
"{",
"// Check cache for links",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"'links'",
";",
"let",
"cache",
"=",
"cache_links",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Build select statement",
"let",
"select",
"=",
"\"SELECT link_category_title, link_title, link_description, link_url FROM rt_links;\"",
";",
"// Query the database",
"db",
".",
"select",
"(",
"select",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// List of links to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Parse each row",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"row",
"=",
"results",
"[",
"i",
"]",
";",
"// Build the link",
"let",
"link",
"=",
"new",
"Link",
"(",
"row",
".",
"link_category_title",
",",
"row",
".",
"link_title",
",",
"row",
".",
"link_description",
",",
"row",
".",
"link_url",
")",
";",
"// Add link to list",
"rtn",
".",
"push",
"(",
"link",
")",
";",
"}",
"// Add links to cache",
"cache_links",
".",
"put",
"(",
"cacheKey",
",",
"rtn",
")",
";",
"// Return the links with the callback",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
")",
";",
"}"
]
| Get all of the Agency link information from the database
@param {RightTrackDB} db The Right Track Database to query
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Link[]} [callback.links] The selected Links | [
"Get",
"all",
"of",
"the",
"Agency",
"link",
"information",
"from",
"the",
"database"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/LinksTable.js#L74-L121 |
40,448 | repetere/periodicjs.core.controller | utility/aliased/aliased_protocol.js | function () {
/**
* Get a valid file path for a template file from a set of directories
* @param {Object} opts Configurable options (see periodicjs.core.protocols for more details)
* @param {string} [opts.extname] Periodic extension that may contain view file
* @param {string} opts.viewname Name of the template file
* @param {string} [opts.themefileext="periodicjs.theme.default"] Periodic theme that may contain view file
* @param {string} [opts.viewfileext=".ejs"] File extension type
* @param {Function} callback Callback function
* @return {Object} Returns a Promise which resolves with file path if cb argument is not passed
*/
let fn = function getPluginViewDefaultTemplate (opts = {}, callback) {
let { extname, viewname, themefileext, viewfileext } = opts;
let themename = this.theme;
let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext;
return this._utility_responder.render({}, Object.assign(opts, { themename, fileext, resolve_filepath: true }), callback);
};
let message = 'CoreController.getPluginViewDefaultTemplate: Use CoreController.responder.render with a HTML adapter or CoreController._utility_responder.render instead';
return wrapWithDeprecationWarning.call(this, fn, message);
} | javascript | function () {
/**
* Get a valid file path for a template file from a set of directories
* @param {Object} opts Configurable options (see periodicjs.core.protocols for more details)
* @param {string} [opts.extname] Periodic extension that may contain view file
* @param {string} opts.viewname Name of the template file
* @param {string} [opts.themefileext="periodicjs.theme.default"] Periodic theme that may contain view file
* @param {string} [opts.viewfileext=".ejs"] File extension type
* @param {Function} callback Callback function
* @return {Object} Returns a Promise which resolves with file path if cb argument is not passed
*/
let fn = function getPluginViewDefaultTemplate (opts = {}, callback) {
let { extname, viewname, themefileext, viewfileext } = opts;
let themename = this.theme;
let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext;
return this._utility_responder.render({}, Object.assign(opts, { themename, fileext, resolve_filepath: true }), callback);
};
let message = 'CoreController.getPluginViewDefaultTemplate: Use CoreController.responder.render with a HTML adapter or CoreController._utility_responder.render instead';
return wrapWithDeprecationWarning.call(this, fn, message);
} | [
"function",
"(",
")",
"{",
"/**\n * Get a valid file path for a template file from a set of directories\n * @param {Object} opts Configurable options (see periodicjs.core.protocols for more details)\n * @param {string} [opts.extname] Periodic extension that may contain view file\n * @param {string} opts.viewname Name of the template file\n * @param {string} [opts.themefileext=\"periodicjs.theme.default\"] Periodic theme that may contain view file\n * @param {string} [opts.viewfileext=\".ejs\"] File extension type\n * @param {Function} callback Callback function\n * @return {Object} Returns a Promise which resolves with file path if cb argument is not passed\n */",
"let",
"fn",
"=",
"function",
"getPluginViewDefaultTemplate",
"(",
"opts",
"=",
"{",
"}",
",",
"callback",
")",
"{",
"let",
"{",
"extname",
",",
"viewname",
",",
"themefileext",
",",
"viewfileext",
"}",
"=",
"opts",
";",
"let",
"themename",
"=",
"this",
".",
"theme",
";",
"let",
"fileext",
"=",
"(",
"typeof",
"themefileext",
"===",
"'string'",
")",
"?",
"themefileext",
":",
"viewfileext",
";",
"return",
"this",
".",
"_utility_responder",
".",
"render",
"(",
"{",
"}",
",",
"Object",
".",
"assign",
"(",
"opts",
",",
"{",
"themename",
",",
"fileext",
",",
"resolve_filepath",
":",
"true",
"}",
")",
",",
"callback",
")",
";",
"}",
";",
"let",
"message",
"=",
"'CoreController.getPluginViewDefaultTemplate: Use CoreController.responder.render with a HTML adapter or CoreController._utility_responder.render instead'",
";",
"return",
"wrapWithDeprecationWarning",
".",
"call",
"(",
"this",
",",
"fn",
",",
"message",
")",
";",
"}"
]
| Creates a function that will resolve a template file path from a set of directories. Alias for CoreController._utility_responder.render
@return {Function} A function that will resolve a valid file path for a template | [
"Creates",
"a",
"function",
"that",
"will",
"resolve",
"a",
"template",
"file",
"path",
"from",
"a",
"set",
"of",
"directories",
".",
"Alias",
"for",
"CoreController",
".",
"_utility_responder",
".",
"render"
]
| b8e67db5958599fa71b0d5cd5d426dbe2264dfb6 | https://github.com/repetere/periodicjs.core.controller/blob/b8e67db5958599fa71b0d5cd5d426dbe2264dfb6/utility/aliased/aliased_protocol.js#L14-L33 |
|
40,449 | repetere/periodicjs.core.controller | utility/aliased/aliased_protocol.js | respondInKind | function respondInKind (opts = {}, callback) {
let { req, res, responseData, err } = opts;
opts.callback = (typeof opts.callback === 'function') ? opts.callback : callback;
if ((path.extname(req.originalUrl) === '.html' || req.is('html') || req.is('text/html') || path.extname(req.originalUrl) === '.htm') || typeof opts.callback === 'function') {
return this.protocol.respond(req, res, { data: responseData, err, return_response_data: true })
.try(result => {
if (typeof opts.callback === 'function') opts.callback(req, res, result);
else return Promisie.resolve(result);
})
.catch(e => {
if (typeof opts.callback === 'function') callback(e);
else return Promisie.reject(e);
});
}
else if (req.redirecturl) {
req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
return this.protocol.redirect(req, res);
}
else {
let settings = (this.protocol && this.protocol.settings) ? this.protocol.settings : false;
if (settings && settings.sessions && settings.sessions.enabled && req.session) req.flash = req.flash.bind(req);
else req.flash = null;
return this.protocol.respond(req, res, { data: responseData, err });
}
} | javascript | function respondInKind (opts = {}, callback) {
let { req, res, responseData, err } = opts;
opts.callback = (typeof opts.callback === 'function') ? opts.callback : callback;
if ((path.extname(req.originalUrl) === '.html' || req.is('html') || req.is('text/html') || path.extname(req.originalUrl) === '.htm') || typeof opts.callback === 'function') {
return this.protocol.respond(req, res, { data: responseData, err, return_response_data: true })
.try(result => {
if (typeof opts.callback === 'function') opts.callback(req, res, result);
else return Promisie.resolve(result);
})
.catch(e => {
if (typeof opts.callback === 'function') callback(e);
else return Promisie.reject(e);
});
}
else if (req.redirecturl) {
req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
return this.protocol.redirect(req, res);
}
else {
let settings = (this.protocol && this.protocol.settings) ? this.protocol.settings : false;
if (settings && settings.sessions && settings.sessions.enabled && req.session) req.flash = req.flash.bind(req);
else req.flash = null;
return this.protocol.respond(req, res, { data: responseData, err });
}
} | [
"function",
"respondInKind",
"(",
"opts",
"=",
"{",
"}",
",",
"callback",
")",
"{",
"let",
"{",
"req",
",",
"res",
",",
"responseData",
",",
"err",
"}",
"=",
"opts",
";",
"opts",
".",
"callback",
"=",
"(",
"typeof",
"opts",
".",
"callback",
"===",
"'function'",
")",
"?",
"opts",
".",
"callback",
":",
"callback",
";",
"if",
"(",
"(",
"path",
".",
"extname",
"(",
"req",
".",
"originalUrl",
")",
"===",
"'.html'",
"||",
"req",
".",
"is",
"(",
"'html'",
")",
"||",
"req",
".",
"is",
"(",
"'text/html'",
")",
"||",
"path",
".",
"extname",
"(",
"req",
".",
"originalUrl",
")",
"===",
"'.htm'",
")",
"||",
"typeof",
"opts",
".",
"callback",
"===",
"'function'",
")",
"{",
"return",
"this",
".",
"protocol",
".",
"respond",
"(",
"req",
",",
"res",
",",
"{",
"data",
":",
"responseData",
",",
"err",
",",
"return_response_data",
":",
"true",
"}",
")",
".",
"try",
"(",
"result",
"=>",
"{",
"if",
"(",
"typeof",
"opts",
".",
"callback",
"===",
"'function'",
")",
"opts",
".",
"callback",
"(",
"req",
",",
"res",
",",
"result",
")",
";",
"else",
"return",
"Promisie",
".",
"resolve",
"(",
"result",
")",
";",
"}",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"if",
"(",
"typeof",
"opts",
".",
"callback",
"===",
"'function'",
")",
"callback",
"(",
"e",
")",
";",
"else",
"return",
"Promisie",
".",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"req",
".",
"redirecturl",
")",
"{",
"req",
".",
"redirectpath",
"=",
"(",
"!",
"req",
".",
"redirectpath",
"&&",
"req",
".",
"redirecturl",
")",
"?",
"req",
".",
"redirecturl",
":",
"req",
".",
"redirectpath",
";",
"return",
"this",
".",
"protocol",
".",
"redirect",
"(",
"req",
",",
"res",
")",
";",
"}",
"else",
"{",
"let",
"settings",
"=",
"(",
"this",
".",
"protocol",
"&&",
"this",
".",
"protocol",
".",
"settings",
")",
"?",
"this",
".",
"protocol",
".",
"settings",
":",
"false",
";",
"if",
"(",
"settings",
"&&",
"settings",
".",
"sessions",
"&&",
"settings",
".",
"sessions",
".",
"enabled",
"&&",
"req",
".",
"session",
")",
"req",
".",
"flash",
"=",
"req",
".",
"flash",
".",
"bind",
"(",
"req",
")",
";",
"else",
"req",
".",
"flash",
"=",
"null",
";",
"return",
"this",
".",
"protocol",
".",
"respond",
"(",
"req",
",",
"res",
",",
"{",
"data",
":",
"responseData",
",",
"err",
"}",
")",
";",
"}",
"}"
]
| Sends response data to client or returns formatted response data
@param {Object} opts Configurable options (see periodicjs.core.protocols for more details)
@param {Function} opts.callback An optional callback. If this options is defined callback argument will be ignored
@param {*} opts.responseData Data to include in response object. If opts.err is defined this option will be ignored and the response will be treated as an error response
@param {*} opts.err Error data. If this option is defined response will always be an error response unless .ignore_error is true
@param {Object} opts.req Express request object
@param {Object} opts.res Express response object
@param {Function} [callback] Optional callback function
@return {Function} If callback is not defined optionally returns a Promise which will resolve response data | [
"Sends",
"response",
"data",
"to",
"client",
"or",
"returns",
"formatted",
"response",
"data"
]
| b8e67db5958599fa71b0d5cd5d426dbe2264dfb6 | https://github.com/repetere/periodicjs.core.controller/blob/b8e67db5958599fa71b0d5cd5d426dbe2264dfb6/utility/aliased/aliased_protocol.js#L51-L75 |
40,450 | repetere/periodicjs.core.controller | utility/aliased/aliased_protocol.js | function () {
/**
* Renders a view from template and sends data to client
* @param {Object} opts Configurable options (see periodicjs.core.responder for more details)
* @param {string} opts.extname Periodic extension which may have template in view folder
* @param {string} opts.viewname Name of template file
* @param {string} opts.themefileext Periodic theme which may have template in view folder
* @param {string} opts.viewfileext The file extension of the view file
* @param {Object} opts.req Express request object
* @param {Object} opts.res Express response object
* @param {Function} [callback] Optional callback function
* @return {Function} If callback is not defined returns a Promise which resolves with rendered template
*/
let fn = function handleDocumentQueryRender (opts = {}, callback) {
let { extname, viewname, themefileext, viewfileext, responseData } = opts;
let themename = this.theme;
let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext;
return this._utility_responder.render(responseData || {}, Object.assign(opts, { themename, fileext, skip_response: true }))
.then(result => {
this.protocol.respond(opts.req, opts.res, {
responder_override: result
});
if (typeof callback === 'function') callback(null, result);
else return Promisie.resolve(result);
})
.catch(e => {
this.protocol.error(opts.req, opts.res, { err: e });
if (typeof callback === 'function') callback(e);
else return Promisie.reject(e);
});
};
let message = 'CoreController.handleDocumentQueryRender: Use CoreController.responder.render with an HTML adapter or CoreController._utility_responder.render instead';
return wrapWithDeprecationWarning.call(this, fn, message);
} | javascript | function () {
/**
* Renders a view from template and sends data to client
* @param {Object} opts Configurable options (see periodicjs.core.responder for more details)
* @param {string} opts.extname Periodic extension which may have template in view folder
* @param {string} opts.viewname Name of template file
* @param {string} opts.themefileext Periodic theme which may have template in view folder
* @param {string} opts.viewfileext The file extension of the view file
* @param {Object} opts.req Express request object
* @param {Object} opts.res Express response object
* @param {Function} [callback] Optional callback function
* @return {Function} If callback is not defined returns a Promise which resolves with rendered template
*/
let fn = function handleDocumentQueryRender (opts = {}, callback) {
let { extname, viewname, themefileext, viewfileext, responseData } = opts;
let themename = this.theme;
let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext;
return this._utility_responder.render(responseData || {}, Object.assign(opts, { themename, fileext, skip_response: true }))
.then(result => {
this.protocol.respond(opts.req, opts.res, {
responder_override: result
});
if (typeof callback === 'function') callback(null, result);
else return Promisie.resolve(result);
})
.catch(e => {
this.protocol.error(opts.req, opts.res, { err: e });
if (typeof callback === 'function') callback(e);
else return Promisie.reject(e);
});
};
let message = 'CoreController.handleDocumentQueryRender: Use CoreController.responder.render with an HTML adapter or CoreController._utility_responder.render instead';
return wrapWithDeprecationWarning.call(this, fn, message);
} | [
"function",
"(",
")",
"{",
"/**\n * Renders a view from template and sends data to client\n * @param {Object} opts Configurable options (see periodicjs.core.responder for more details)\n * @param {string} opts.extname Periodic extension which may have template in view folder\n * @param {string} opts.viewname Name of template file\n * @param {string} opts.themefileext Periodic theme which may have template in view folder\n * @param {string} opts.viewfileext The file extension of the view file\n * @param {Object} opts.req Express request object\n * @param {Object} opts.res Express response object\n * @param {Function} [callback] Optional callback function\n * @return {Function} If callback is not defined returns a Promise which resolves with rendered template\n */",
"let",
"fn",
"=",
"function",
"handleDocumentQueryRender",
"(",
"opts",
"=",
"{",
"}",
",",
"callback",
")",
"{",
"let",
"{",
"extname",
",",
"viewname",
",",
"themefileext",
",",
"viewfileext",
",",
"responseData",
"}",
"=",
"opts",
";",
"let",
"themename",
"=",
"this",
".",
"theme",
";",
"let",
"fileext",
"=",
"(",
"typeof",
"themefileext",
"===",
"'string'",
")",
"?",
"themefileext",
":",
"viewfileext",
";",
"return",
"this",
".",
"_utility_responder",
".",
"render",
"(",
"responseData",
"||",
"{",
"}",
",",
"Object",
".",
"assign",
"(",
"opts",
",",
"{",
"themename",
",",
"fileext",
",",
"skip_response",
":",
"true",
"}",
")",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"this",
".",
"protocol",
".",
"respond",
"(",
"opts",
".",
"req",
",",
"opts",
".",
"res",
",",
"{",
"responder_override",
":",
"result",
"}",
")",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"callback",
"(",
"null",
",",
"result",
")",
";",
"else",
"return",
"Promisie",
".",
"resolve",
"(",
"result",
")",
";",
"}",
")",
".",
"catch",
"(",
"e",
"=>",
"{",
"this",
".",
"protocol",
".",
"error",
"(",
"opts",
".",
"req",
",",
"opts",
".",
"res",
",",
"{",
"err",
":",
"e",
"}",
")",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"callback",
"(",
"e",
")",
";",
"else",
"return",
"Promisie",
".",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
";",
"let",
"message",
"=",
"'CoreController.handleDocumentQueryRender: Use CoreController.responder.render with an HTML adapter or CoreController._utility_responder.render instead'",
";",
"return",
"wrapWithDeprecationWarning",
".",
"call",
"(",
"this",
",",
"fn",
",",
"message",
")",
";",
"}"
]
| Creates a function that will render a template and send HTTP response to client. Alias for CoreController._utility_responder.render
@return {Function} A function that will render a template and send data to client | [
"Creates",
"a",
"function",
"that",
"will",
"render",
"a",
"template",
"and",
"send",
"HTTP",
"response",
"to",
"client",
".",
"Alias",
"for",
"CoreController",
".",
"_utility_responder",
".",
"render"
]
| b8e67db5958599fa71b0d5cd5d426dbe2264dfb6 | https://github.com/repetere/periodicjs.core.controller/blob/b8e67db5958599fa71b0d5cd5d426dbe2264dfb6/utility/aliased/aliased_protocol.js#L84-L117 |
|
40,451 | repetere/periodicjs.core.controller | utility/aliased/aliased_protocol.js | function () {
/**
* Renders an error view from a template and sends data to client
* @param {Object} opts Configurable options (see periodicjs.core.responder for more details)
* @param {string|Object} opts.err Error details for response
* @param {Object} opts.req Express request object
* @param {Object} opts.res Express response object
* @param {Function} [callback] Optional callback function
* @return {Object} If callback is not defined returns a Promise which resolves after response has been sent
*/
let fn = function handleDocumentQueryErrorResponse (opts = {}, callback) {
let { err, req, res } = opts;
if (opts.use_warning) this.protocol.warn(req, res, { err });
else this.protocol.error(req, res, { err });
if (req.query.format === 'json' || req.params.ext === 'json' || path.extname(req.originalUrl) === '.json' || req.is('json') || req.params.callback || req.is('application/json')) {
return this.protocol.respond(req, res, { err });
}
else if (typeof callback === 'function') {
return this.responder.error(err)
.then(result => callback(null, result))
.catch(callback);
}
else if (req.redirecturl) {
req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
return this.protocol.redirect(req, res);
}
else {
return this._utility_responder.error(err, {})
.then(result => {
return this.protocol.respond(req, res, { responder_override: result });
}, err => {
return this.protocol.exception(req, res, { err });
});
}
};
let message = 'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead';
return wrapWithDeprecationWarning.call(this, fn, message);
} | javascript | function () {
/**
* Renders an error view from a template and sends data to client
* @param {Object} opts Configurable options (see periodicjs.core.responder for more details)
* @param {string|Object} opts.err Error details for response
* @param {Object} opts.req Express request object
* @param {Object} opts.res Express response object
* @param {Function} [callback] Optional callback function
* @return {Object} If callback is not defined returns a Promise which resolves after response has been sent
*/
let fn = function handleDocumentQueryErrorResponse (opts = {}, callback) {
let { err, req, res } = opts;
if (opts.use_warning) this.protocol.warn(req, res, { err });
else this.protocol.error(req, res, { err });
if (req.query.format === 'json' || req.params.ext === 'json' || path.extname(req.originalUrl) === '.json' || req.is('json') || req.params.callback || req.is('application/json')) {
return this.protocol.respond(req, res, { err });
}
else if (typeof callback === 'function') {
return this.responder.error(err)
.then(result => callback(null, result))
.catch(callback);
}
else if (req.redirecturl) {
req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
return this.protocol.redirect(req, res);
}
else {
return this._utility_responder.error(err, {})
.then(result => {
return this.protocol.respond(req, res, { responder_override: result });
}, err => {
return this.protocol.exception(req, res, { err });
});
}
};
let message = 'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead';
return wrapWithDeprecationWarning.call(this, fn, message);
} | [
"function",
"(",
")",
"{",
"/**\n * Renders an error view from a template and sends data to client\n * @param {Object} opts Configurable options (see periodicjs.core.responder for more details)\n * @param {string|Object} opts.err Error details for response\n * @param {Object} opts.req Express request object\n * @param {Object} opts.res Express response object\n * @param {Function} [callback] Optional callback function\n * @return {Object} If callback is not defined returns a Promise which resolves after response has been sent\n */",
"let",
"fn",
"=",
"function",
"handleDocumentQueryErrorResponse",
"(",
"opts",
"=",
"{",
"}",
",",
"callback",
")",
"{",
"let",
"{",
"err",
",",
"req",
",",
"res",
"}",
"=",
"opts",
";",
"if",
"(",
"opts",
".",
"use_warning",
")",
"this",
".",
"protocol",
".",
"warn",
"(",
"req",
",",
"res",
",",
"{",
"err",
"}",
")",
";",
"else",
"this",
".",
"protocol",
".",
"error",
"(",
"req",
",",
"res",
",",
"{",
"err",
"}",
")",
";",
"if",
"(",
"req",
".",
"query",
".",
"format",
"===",
"'json'",
"||",
"req",
".",
"params",
".",
"ext",
"===",
"'json'",
"||",
"path",
".",
"extname",
"(",
"req",
".",
"originalUrl",
")",
"===",
"'.json'",
"||",
"req",
".",
"is",
"(",
"'json'",
")",
"||",
"req",
".",
"params",
".",
"callback",
"||",
"req",
".",
"is",
"(",
"'application/json'",
")",
")",
"{",
"return",
"this",
".",
"protocol",
".",
"respond",
"(",
"req",
",",
"res",
",",
"{",
"err",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"return",
"this",
".",
"responder",
".",
"error",
"(",
"err",
")",
".",
"then",
"(",
"result",
"=>",
"callback",
"(",
"null",
",",
"result",
")",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"req",
".",
"redirecturl",
")",
"{",
"req",
".",
"redirectpath",
"=",
"(",
"!",
"req",
".",
"redirectpath",
"&&",
"req",
".",
"redirecturl",
")",
"?",
"req",
".",
"redirecturl",
":",
"req",
".",
"redirectpath",
";",
"return",
"this",
".",
"protocol",
".",
"redirect",
"(",
"req",
",",
"res",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"_utility_responder",
".",
"error",
"(",
"err",
",",
"{",
"}",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"return",
"this",
".",
"protocol",
".",
"respond",
"(",
"req",
",",
"res",
",",
"{",
"responder_override",
":",
"result",
"}",
")",
";",
"}",
",",
"err",
"=>",
"{",
"return",
"this",
".",
"protocol",
".",
"exception",
"(",
"req",
",",
"res",
",",
"{",
"err",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"let",
"message",
"=",
"'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead'",
";",
"return",
"wrapWithDeprecationWarning",
".",
"call",
"(",
"this",
",",
"fn",
",",
"message",
")",
";",
"}"
]
| Creates a function that will render an error view from a template. Alias for CoreController._utility_responder.error
@return {Function} A function that will render an error view from a template and send response | [
"Creates",
"a",
"function",
"that",
"will",
"render",
"an",
"error",
"view",
"from",
"a",
"template",
".",
"Alias",
"for",
"CoreController",
".",
"_utility_responder",
".",
"error"
]
| b8e67db5958599fa71b0d5cd5d426dbe2264dfb6 | https://github.com/repetere/periodicjs.core.controller/blob/b8e67db5958599fa71b0d5cd5d426dbe2264dfb6/utility/aliased/aliased_protocol.js#L123-L160 |
|
40,452 | repetere/periodicjs.core.controller | utility/aliased/aliased_protocol.js | function () {
/**
* Returns inflected values from a string ie. application => applications, Application, etc.
* @param {Object} options Configurable options
* @param {string} options.model_name String that should be inflected
* @return {Object} Object containing inflected values indexed by type of inflection
*/
return function getViewModelProperties (options = {}) {
let model_name = options.model_name;
let viewmodel = {
name: model_name,
name_plural: pluralize(model_name)
};
return Object.assign(viewmodel, {
capital_name: capitalize(model_name),
page_plural_title: capitalize(viewmodel.name_plural),
page_plural_count: `${ viewmodel.name_plural }count`,
page_plural_query: `${ viewmodel.name_plural }query`,
page_single_count: `${ model_name }count`,
page_pages: `${ model_name }pages`
});
};
} | javascript | function () {
/**
* Returns inflected values from a string ie. application => applications, Application, etc.
* @param {Object} options Configurable options
* @param {string} options.model_name String that should be inflected
* @return {Object} Object containing inflected values indexed by type of inflection
*/
return function getViewModelProperties (options = {}) {
let model_name = options.model_name;
let viewmodel = {
name: model_name,
name_plural: pluralize(model_name)
};
return Object.assign(viewmodel, {
capital_name: capitalize(model_name),
page_plural_title: capitalize(viewmodel.name_plural),
page_plural_count: `${ viewmodel.name_plural }count`,
page_plural_query: `${ viewmodel.name_plural }query`,
page_single_count: `${ model_name }count`,
page_pages: `${ model_name }pages`
});
};
} | [
"function",
"(",
")",
"{",
"/**\n * Returns inflected values from a string ie. application => applications, Application, etc.\n * @param {Object} options Configurable options\n * @param {string} options.model_name String that should be inflected\n * @return {Object} Object containing inflected values indexed by type of inflection\n */",
"return",
"function",
"getViewModelProperties",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"let",
"model_name",
"=",
"options",
".",
"model_name",
";",
"let",
"viewmodel",
"=",
"{",
"name",
":",
"model_name",
",",
"name_plural",
":",
"pluralize",
"(",
"model_name",
")",
"}",
";",
"return",
"Object",
".",
"assign",
"(",
"viewmodel",
",",
"{",
"capital_name",
":",
"capitalize",
"(",
"model_name",
")",
",",
"page_plural_title",
":",
"capitalize",
"(",
"viewmodel",
".",
"name_plural",
")",
",",
"page_plural_count",
":",
"`",
"${",
"viewmodel",
".",
"name_plural",
"}",
"`",
",",
"page_plural_query",
":",
"`",
"${",
"viewmodel",
".",
"name_plural",
"}",
"`",
",",
"page_single_count",
":",
"`",
"${",
"model_name",
"}",
"`",
",",
"page_pages",
":",
"`",
"${",
"model_name",
"}",
"`",
"}",
")",
";",
"}",
";",
"}"
]
| Creates a function that will get inflected values from a given string
@return {Function} A function that will get inflected values from a given string | [
"Creates",
"a",
"function",
"that",
"will",
"get",
"inflected",
"values",
"from",
"a",
"given",
"string"
]
| b8e67db5958599fa71b0d5cd5d426dbe2264dfb6 | https://github.com/repetere/periodicjs.core.controller/blob/b8e67db5958599fa71b0d5cd5d426dbe2264dfb6/utility/aliased/aliased_protocol.js#L307-L329 |
|
40,453 | winterstein/you-again | src/youagain.js | function(url, data, type) {
assert(Login.app, "You must set Login.app = my-app-name-as-registered-with-you-again");
data.app = Login.app;
data.withCredentials = true; // let the server know this is a with-credentials call
data.caller = ""+document.location; // provide some extra info
// add in local cookie auth
const cookies = Cookies.get();
let cbase = cookieBase();
for(let c in cookies) {
if (c.substr(0, cbase.length)===cbase) {
let cv = Cookies.get(c);
data[c] = cv;
}
}
return $.ajax({
dataType: "json", // not really needed but harmless
url: url,
data: data,
type: type || 'GET',
xhrFields: {withCredentials: true}
});
} | javascript | function(url, data, type) {
assert(Login.app, "You must set Login.app = my-app-name-as-registered-with-you-again");
data.app = Login.app;
data.withCredentials = true; // let the server know this is a with-credentials call
data.caller = ""+document.location; // provide some extra info
// add in local cookie auth
const cookies = Cookies.get();
let cbase = cookieBase();
for(let c in cookies) {
if (c.substr(0, cbase.length)===cbase) {
let cv = Cookies.get(c);
data[c] = cv;
}
}
return $.ajax({
dataType: "json", // not really needed but harmless
url: url,
data: data,
type: type || 'GET',
xhrFields: {withCredentials: true}
});
} | [
"function",
"(",
"url",
",",
"data",
",",
"type",
")",
"{",
"assert",
"(",
"Login",
".",
"app",
",",
"\"You must set Login.app = my-app-name-as-registered-with-you-again\"",
")",
";",
"data",
".",
"app",
"=",
"Login",
".",
"app",
";",
"data",
".",
"withCredentials",
"=",
"true",
";",
"// let the server know this is a with-credentials call",
"data",
".",
"caller",
"=",
"\"\"",
"+",
"document",
".",
"location",
";",
"// provide some extra info",
"// add in local cookie auth",
"const",
"cookies",
"=",
"Cookies",
".",
"get",
"(",
")",
";",
"let",
"cbase",
"=",
"cookieBase",
"(",
")",
";",
"for",
"(",
"let",
"c",
"in",
"cookies",
")",
"{",
"if",
"(",
"c",
".",
"substr",
"(",
"0",
",",
"cbase",
".",
"length",
")",
"===",
"cbase",
")",
"{",
"let",
"cv",
"=",
"Cookies",
".",
"get",
"(",
"c",
")",
";",
"data",
"[",
"c",
"]",
"=",
"cv",
";",
"}",
"}",
"return",
"$",
".",
"ajax",
"(",
"{",
"dataType",
":",
"\"json\"",
",",
"// not really needed but harmless",
"url",
":",
"url",
",",
"data",
":",
"data",
",",
"type",
":",
"type",
"||",
"'GET'",
",",
"xhrFields",
":",
"{",
"withCredentials",
":",
"true",
"}",
"}",
")",
";",
"}"
]
| convenience for ajax with cookies | [
"convenience",
"for",
"ajax",
"with",
"cookies"
]
| 0c745f6b8498798b9971773f7fb6a26e301f26a3 | https://github.com/winterstein/you-again/blob/0c745f6b8498798b9971773f7fb6a26e301f26a3/src/youagain.js#L556-L578 |
|
40,454 | right-track/right-track-core | modules/search/query.js | getTripsFromStop | function getTripsFromStop(db, stop, tripSearchDates, nextStops, callback) {
// List of Trips to Return
let rtn = [];
// Counters
let done = 0;
let count = tripSearchDates.length;
// Parse each TripSearchDate separately
for ( let i = 0; i < tripSearchDates.length; i++ ) {
_getTripsFromStop(db, stop, tripSearchDates[i], function(err, trips) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Check each of the Trips to add
for ( let j = 0; j < trips.length; j++ ) {
_addTrip(trips[j]);
}
// Finish the TSD
_finish();
});
}
/**
* Add the specified Trip to the return list, if it is not
* already present and it continues to one of the next stops
* @param {Trip} trip Trip to add
* @private
*/
function _addTrip(trip) {
// Make sure trip isn't already in list
let found = false;
for ( let i = 0; i < rtn.length; i++ ) {
if ( rtn[i].id === trip.id ) {
found = true;
}
}
// Process new trip
if ( !found ) {
// Make sure the trip stops at any of the next stops, after the current stop
let stopFound = false;
let add = false;
for ( let i = 0; i < trip.stopTimes.length; i++ ) {
let stopId = trip.stopTimes[i].stop.id;
if ( !stopFound && stopId === stop.id ) {
stopFound = true;
}
else if ( stopFound ) {
if ( nextStops.indexOf(stopId) > -1 ) {
add = true;
i = trip.stopTimes.length;
}
}
}
// Add Trip
if ( add ) {
rtn.push(trip);
}
}
}
/**
* Finish processing the Trip Search Dates
* @private
*/
function _finish() {
done++;
if ( done === count ) {
return callback(null, rtn);
}
}
} | javascript | function getTripsFromStop(db, stop, tripSearchDates, nextStops, callback) {
// List of Trips to Return
let rtn = [];
// Counters
let done = 0;
let count = tripSearchDates.length;
// Parse each TripSearchDate separately
for ( let i = 0; i < tripSearchDates.length; i++ ) {
_getTripsFromStop(db, stop, tripSearchDates[i], function(err, trips) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Check each of the Trips to add
for ( let j = 0; j < trips.length; j++ ) {
_addTrip(trips[j]);
}
// Finish the TSD
_finish();
});
}
/**
* Add the specified Trip to the return list, if it is not
* already present and it continues to one of the next stops
* @param {Trip} trip Trip to add
* @private
*/
function _addTrip(trip) {
// Make sure trip isn't already in list
let found = false;
for ( let i = 0; i < rtn.length; i++ ) {
if ( rtn[i].id === trip.id ) {
found = true;
}
}
// Process new trip
if ( !found ) {
// Make sure the trip stops at any of the next stops, after the current stop
let stopFound = false;
let add = false;
for ( let i = 0; i < trip.stopTimes.length; i++ ) {
let stopId = trip.stopTimes[i].stop.id;
if ( !stopFound && stopId === stop.id ) {
stopFound = true;
}
else if ( stopFound ) {
if ( nextStops.indexOf(stopId) > -1 ) {
add = true;
i = trip.stopTimes.length;
}
}
}
// Add Trip
if ( add ) {
rtn.push(trip);
}
}
}
/**
* Finish processing the Trip Search Dates
* @private
*/
function _finish() {
done++;
if ( done === count ) {
return callback(null, rtn);
}
}
} | [
"function",
"getTripsFromStop",
"(",
"db",
",",
"stop",
",",
"tripSearchDates",
",",
"nextStops",
",",
"callback",
")",
"{",
"// List of Trips to Return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Counters",
"let",
"done",
"=",
"0",
";",
"let",
"count",
"=",
"tripSearchDates",
".",
"length",
";",
"// Parse each TripSearchDate separately",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"tripSearchDates",
".",
"length",
";",
"i",
"++",
")",
"{",
"_getTripsFromStop",
"(",
"db",
",",
"stop",
",",
"tripSearchDates",
"[",
"i",
"]",
",",
"function",
"(",
"err",
",",
"trips",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Check each of the Trips to add",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"trips",
".",
"length",
";",
"j",
"++",
")",
"{",
"_addTrip",
"(",
"trips",
"[",
"j",
"]",
")",
";",
"}",
"// Finish the TSD",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"/**\n * Add the specified Trip to the return list, if it is not\n * already present and it continues to one of the next stops\n * @param {Trip} trip Trip to add\n * @private\n */",
"function",
"_addTrip",
"(",
"trip",
")",
"{",
"// Make sure trip isn't already in list",
"let",
"found",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"rtn",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rtn",
"[",
"i",
"]",
".",
"id",
"===",
"trip",
".",
"id",
")",
"{",
"found",
"=",
"true",
";",
"}",
"}",
"// Process new trip",
"if",
"(",
"!",
"found",
")",
"{",
"// Make sure the trip stops at any of the next stops, after the current stop",
"let",
"stopFound",
"=",
"false",
";",
"let",
"add",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trip",
".",
"stopTimes",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"stopId",
"=",
"trip",
".",
"stopTimes",
"[",
"i",
"]",
".",
"stop",
".",
"id",
";",
"if",
"(",
"!",
"stopFound",
"&&",
"stopId",
"===",
"stop",
".",
"id",
")",
"{",
"stopFound",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"stopFound",
")",
"{",
"if",
"(",
"nextStops",
".",
"indexOf",
"(",
"stopId",
")",
">",
"-",
"1",
")",
"{",
"add",
"=",
"true",
";",
"i",
"=",
"trip",
".",
"stopTimes",
".",
"length",
";",
"}",
"}",
"}",
"// Add Trip",
"if",
"(",
"add",
")",
"{",
"rtn",
".",
"push",
"(",
"trip",
")",
";",
"}",
"}",
"}",
"/**\n * Finish processing the Trip Search Dates\n * @private\n */",
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"done",
"===",
"count",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
"}",
"}"
]
| Get a list of Trips that operate during the specified TripSearchDates and
run from the specified Stop to at least one of the provided following Stops
@param {RightTrackDB} db The Right Track DB to query
@param {Stop} stop The reference Stop
@param {TripSearchDate[]} tripSearchDates List of Trip Search Dates
@param {String[]} nextStops List of following Stops (Stop IDs)
@param {function} callback Callback function
@param {Error} callback.err Database Query Error
@param {Trip[]} [callback.trips] List of matching Trips
@private | [
"Get",
"a",
"list",
"of",
"Trips",
"that",
"operate",
"during",
"the",
"specified",
"TripSearchDates",
"and",
"run",
"from",
"the",
"specified",
"Stop",
"to",
"at",
"least",
"one",
"of",
"the",
"provided",
"following",
"Stops"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/query.js#L28-L114 |
40,455 | right-track/right-track-core | modules/search/query.js | _addTrip | function _addTrip(trip) {
// Make sure trip isn't already in list
let found = false;
for ( let i = 0; i < rtn.length; i++ ) {
if ( rtn[i].id === trip.id ) {
found = true;
}
}
// Process new trip
if ( !found ) {
// Make sure the trip stops at any of the next stops, after the current stop
let stopFound = false;
let add = false;
for ( let i = 0; i < trip.stopTimes.length; i++ ) {
let stopId = trip.stopTimes[i].stop.id;
if ( !stopFound && stopId === stop.id ) {
stopFound = true;
}
else if ( stopFound ) {
if ( nextStops.indexOf(stopId) > -1 ) {
add = true;
i = trip.stopTimes.length;
}
}
}
// Add Trip
if ( add ) {
rtn.push(trip);
}
}
} | javascript | function _addTrip(trip) {
// Make sure trip isn't already in list
let found = false;
for ( let i = 0; i < rtn.length; i++ ) {
if ( rtn[i].id === trip.id ) {
found = true;
}
}
// Process new trip
if ( !found ) {
// Make sure the trip stops at any of the next stops, after the current stop
let stopFound = false;
let add = false;
for ( let i = 0; i < trip.stopTimes.length; i++ ) {
let stopId = trip.stopTimes[i].stop.id;
if ( !stopFound && stopId === stop.id ) {
stopFound = true;
}
else if ( stopFound ) {
if ( nextStops.indexOf(stopId) > -1 ) {
add = true;
i = trip.stopTimes.length;
}
}
}
// Add Trip
if ( add ) {
rtn.push(trip);
}
}
} | [
"function",
"_addTrip",
"(",
"trip",
")",
"{",
"// Make sure trip isn't already in list",
"let",
"found",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"rtn",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rtn",
"[",
"i",
"]",
".",
"id",
"===",
"trip",
".",
"id",
")",
"{",
"found",
"=",
"true",
";",
"}",
"}",
"// Process new trip",
"if",
"(",
"!",
"found",
")",
"{",
"// Make sure the trip stops at any of the next stops, after the current stop",
"let",
"stopFound",
"=",
"false",
";",
"let",
"add",
"=",
"false",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"trip",
".",
"stopTimes",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"stopId",
"=",
"trip",
".",
"stopTimes",
"[",
"i",
"]",
".",
"stop",
".",
"id",
";",
"if",
"(",
"!",
"stopFound",
"&&",
"stopId",
"===",
"stop",
".",
"id",
")",
"{",
"stopFound",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"stopFound",
")",
"{",
"if",
"(",
"nextStops",
".",
"indexOf",
"(",
"stopId",
")",
">",
"-",
"1",
")",
"{",
"add",
"=",
"true",
";",
"i",
"=",
"trip",
".",
"stopTimes",
".",
"length",
";",
"}",
"}",
"}",
"// Add Trip",
"if",
"(",
"add",
")",
"{",
"rtn",
".",
"push",
"(",
"trip",
")",
";",
"}",
"}",
"}"
]
| Add the specified Trip to the return list, if it is not
already present and it continues to one of the next stops
@param {Trip} trip Trip to add
@private | [
"Add",
"the",
"specified",
"Trip",
"to",
"the",
"return",
"list",
"if",
"it",
"is",
"not",
"already",
"present",
"and",
"it",
"continues",
"to",
"one",
"of",
"the",
"next",
"stops"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/query.js#L64-L100 |
40,456 | right-track/right-track-core | modules/search/query.js | _getTripsFromStop | function _getTripsFromStop(db, stop, tripSearchDate, callback) {
// List of trips to return
let rtn = [];
// Set counters
let done = 0;
let count = 0;
// Build Service ID String
let serviceIdString = "'" + tripSearchDate.serviceIds.join("', '") + "'";
// Get Trip IDs
let select = "SELECT gtfs_stop_times.trip_id " +
"FROM gtfs_stop_times " +
"INNER JOIN gtfs_trips ON gtfs_stop_times.trip_id=gtfs_trips.trip_id " +
"WHERE stop_id='" + stop.id + "' AND " +
"departure_time_seconds >= " + tripSearchDate.preSeconds + " AND departure_time_seconds <= " + tripSearchDate.postSeconds + " AND " +
"pickup_type <> " + StopTime.PICKUP_TYPE_NONE + " AND " +
"gtfs_trips.service_id IN (" + serviceIdString + ")";
// Select the Trip IDs
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(
new Error('Could not get Trip(s) from database')
);
}
// No Results
if ( results.length === 0 ) {
return callback(null, rtn);
}
// Set the counter
count = results.length;
// Build the Trips
for ( let i = 0; i < results.length; i++ ) {
TripsTable.getTrip(db, results[i].trip_id, tripSearchDate.date, function(err, trip) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add trip to list
rtn.push(trip);
// Finish Process the Trip
_finish();
});
}
});
/**
* Finished Processing Trip
* @private
*/
function _finish() {
done++;
if ( done === count ) {
return callback(null, rtn);
}
}
} | javascript | function _getTripsFromStop(db, stop, tripSearchDate, callback) {
// List of trips to return
let rtn = [];
// Set counters
let done = 0;
let count = 0;
// Build Service ID String
let serviceIdString = "'" + tripSearchDate.serviceIds.join("', '") + "'";
// Get Trip IDs
let select = "SELECT gtfs_stop_times.trip_id " +
"FROM gtfs_stop_times " +
"INNER JOIN gtfs_trips ON gtfs_stop_times.trip_id=gtfs_trips.trip_id " +
"WHERE stop_id='" + stop.id + "' AND " +
"departure_time_seconds >= " + tripSearchDate.preSeconds + " AND departure_time_seconds <= " + tripSearchDate.postSeconds + " AND " +
"pickup_type <> " + StopTime.PICKUP_TYPE_NONE + " AND " +
"gtfs_trips.service_id IN (" + serviceIdString + ")";
// Select the Trip IDs
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(
new Error('Could not get Trip(s) from database')
);
}
// No Results
if ( results.length === 0 ) {
return callback(null, rtn);
}
// Set the counter
count = results.length;
// Build the Trips
for ( let i = 0; i < results.length; i++ ) {
TripsTable.getTrip(db, results[i].trip_id, tripSearchDate.date, function(err, trip) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add trip to list
rtn.push(trip);
// Finish Process the Trip
_finish();
});
}
});
/**
* Finished Processing Trip
* @private
*/
function _finish() {
done++;
if ( done === count ) {
return callback(null, rtn);
}
}
} | [
"function",
"_getTripsFromStop",
"(",
"db",
",",
"stop",
",",
"tripSearchDate",
",",
"callback",
")",
"{",
"// List of trips to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Set counters",
"let",
"done",
"=",
"0",
";",
"let",
"count",
"=",
"0",
";",
"// Build Service ID String",
"let",
"serviceIdString",
"=",
"\"'\"",
"+",
"tripSearchDate",
".",
"serviceIds",
".",
"join",
"(",
"\"', '\"",
")",
"+",
"\"'\"",
";",
"// Get Trip IDs",
"let",
"select",
"=",
"\"SELECT gtfs_stop_times.trip_id \"",
"+",
"\"FROM gtfs_stop_times \"",
"+",
"\"INNER JOIN gtfs_trips ON gtfs_stop_times.trip_id=gtfs_trips.trip_id \"",
"+",
"\"WHERE stop_id='\"",
"+",
"stop",
".",
"id",
"+",
"\"' AND \"",
"+",
"\"departure_time_seconds >= \"",
"+",
"tripSearchDate",
".",
"preSeconds",
"+",
"\" AND departure_time_seconds <= \"",
"+",
"tripSearchDate",
".",
"postSeconds",
"+",
"\" AND \"",
"+",
"\"pickup_type <> \"",
"+",
"StopTime",
".",
"PICKUP_TYPE_NONE",
"+",
"\" AND \"",
"+",
"\"gtfs_trips.service_id IN (\"",
"+",
"serviceIdString",
"+",
"\")\"",
";",
"// Select the Trip IDs",
"db",
".",
"select",
"(",
"select",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Could not get Trip(s) from database'",
")",
")",
";",
"}",
"// No Results",
"if",
"(",
"results",
".",
"length",
"===",
"0",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
"// Set the counter",
"count",
"=",
"results",
".",
"length",
";",
"// Build the Trips",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"TripsTable",
".",
"getTrip",
"(",
"db",
",",
"results",
"[",
"i",
"]",
".",
"trip_id",
",",
"tripSearchDate",
".",
"date",
",",
"function",
"(",
"err",
",",
"trip",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add trip to list",
"rtn",
".",
"push",
"(",
"trip",
")",
";",
"// Finish Process the Trip",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"/**\n * Finished Processing Trip\n * @private\n */",
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"done",
"===",
"count",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
"}",
"}"
]
| Get the Trips within the TripSearchDate range from the specified Stop
@param {RightTrackDB} db The Right Track DB to query
@param {Stop} stop The reference Stop
@param {TripSearchDate} tripSearchDate The Trip Search Date
@param {function} callback Callback function(err, trips)
@private | [
"Get",
"the",
"Trips",
"within",
"the",
"TripSearchDate",
"range",
"from",
"the",
"specified",
"Stop"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/search/query.js#L125-L196 |
40,457 | right-track/right-track-core | modules/query/HolidayTable.js | getHoliday | function getHoliday(db, date, callback) {
// Check cache for Holiday
let cacheKey = db.id + "-" + date;
let cache = cache_holidayByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build the select statement
let select = "SELECT date, holiday_name, peak, service_info " +
"FROM rt_holidays WHERE date=" + date;
// Query the database
db.get(select, function(err, result) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Holiday to return
let holiday = undefined;
// Holiday was found...
if ( result !== undefined ) {
// Build the Holiday
holiday = new Holiday(
result.date,
result.holiday_name,
result.peak === 1,
result.service_info
);
}
// Add holiday to cache
cache_holidayByDate.put(cacheKey, holiday);
// Return the holiday
return callback(null, holiday);
})
} | javascript | function getHoliday(db, date, callback) {
// Check cache for Holiday
let cacheKey = db.id + "-" + date;
let cache = cache_holidayByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build the select statement
let select = "SELECT date, holiday_name, peak, service_info " +
"FROM rt_holidays WHERE date=" + date;
// Query the database
db.get(select, function(err, result) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Holiday to return
let holiday = undefined;
// Holiday was found...
if ( result !== undefined ) {
// Build the Holiday
holiday = new Holiday(
result.date,
result.holiday_name,
result.peak === 1,
result.service_info
);
}
// Add holiday to cache
cache_holidayByDate.put(cacheKey, holiday);
// Return the holiday
return callback(null, holiday);
})
} | [
"function",
"getHoliday",
"(",
"db",
",",
"date",
",",
"callback",
")",
"{",
"// Check cache for Holiday",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_holidayByDate",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Build the select statement",
"let",
"select",
"=",
"\"SELECT date, holiday_name, peak, service_info \"",
"+",
"\"FROM rt_holidays WHERE date=\"",
"+",
"date",
";",
"// Query the database",
"db",
".",
"get",
"(",
"select",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Holiday to return",
"let",
"holiday",
"=",
"undefined",
";",
"// Holiday was found...",
"if",
"(",
"result",
"!==",
"undefined",
")",
"{",
"// Build the Holiday",
"holiday",
"=",
"new",
"Holiday",
"(",
"result",
".",
"date",
",",
"result",
".",
"holiday_name",
",",
"result",
".",
"peak",
"===",
"1",
",",
"result",
".",
"service_info",
")",
";",
"}",
"// Add holiday to cache",
"cache_holidayByDate",
".",
"put",
"(",
"cacheKey",
",",
"holiday",
")",
";",
"// Return the holiday",
"return",
"callback",
"(",
"null",
",",
"holiday",
")",
";",
"}",
")",
"}"
]
| Get the Holiday for the specified date or 'undefined' if
there is no holiday on the date
@param {RightTrackDB} db The Right Track DB to query
@param {int} date the date (yyyymmdd)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Holiday} [callback.holiday] The selected Holiday | [
"Get",
"the",
"Holiday",
"for",
"the",
"specified",
"date",
"or",
"undefined",
"if",
"there",
"is",
"no",
"holiday",
"on",
"the",
"date"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/HolidayTable.js#L84-L129 |
40,458 | right-track/right-track-core | modules/query/HolidayTable.js | isHoliday | function isHoliday(db, date, callback) {
// Check cache for is holiday
let cacheKey = db.id + "-" + date;
let cache = cache_isHolidayByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Get matching holiday
let select = "SELECT date, holiday_name, peak, service_info " +
"FROM rt_holidays WHERE date=" + date;
// Query the database
db.get(select, function(err, result) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add result to cache
cache_isHolidayByDate.put(cacheKey, result !== undefined);
// Return if holiday is found with callback
return callback(null, result !== undefined);
});
} | javascript | function isHoliday(db, date, callback) {
// Check cache for is holiday
let cacheKey = db.id + "-" + date;
let cache = cache_isHolidayByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Get matching holiday
let select = "SELECT date, holiday_name, peak, service_info " +
"FROM rt_holidays WHERE date=" + date;
// Query the database
db.get(select, function(err, result) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add result to cache
cache_isHolidayByDate.put(cacheKey, result !== undefined);
// Return if holiday is found with callback
return callback(null, result !== undefined);
});
} | [
"function",
"isHoliday",
"(",
"db",
",",
"date",
",",
"callback",
")",
"{",
"// Check cache for is holiday",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_isHolidayByDate",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Get matching holiday",
"let",
"select",
"=",
"\"SELECT date, holiday_name, peak, service_info \"",
"+",
"\"FROM rt_holidays WHERE date=\"",
"+",
"date",
";",
"// Query the database",
"db",
".",
"get",
"(",
"select",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add result to cache",
"cache_isHolidayByDate",
".",
"put",
"(",
"cacheKey",
",",
"result",
"!==",
"undefined",
")",
";",
"// Return if holiday is found with callback",
"return",
"callback",
"(",
"null",
",",
"result",
"!==",
"undefined",
")",
";",
"}",
")",
";",
"}"
]
| Check if the specified date is a Holiday
@param {RightTrackDB} db The Right Track DB to query
@param {int} date The date to check (yyyymmdd)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {boolean} [callback.isHoliday] True if the specified date is a Holiday | [
"Check",
"if",
"the",
"specified",
"date",
"is",
"a",
"Holiday"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/HolidayTable.js#L141-L170 |
40,459 | bipio-server/bip-pod | index.js | function(src, noEscape) {
var attrLen, newKey;
if (helper.isArray(src)) {
var attrLen = src.length;
for (var i = 0; i < attrLen; i++) {
src[i] = helper.pasteurize(src[i], noEscape);
}
} else if (this.isString(src)) {
src = helper.scrub(src, noEscape);
} else if (helper.isObject(src)) {
var newSrc = {};
for (key in src) {
newKey = helper.scrub(key);
newSrc[newKey] = helper.pasteurize(src[key], noEscape);
}
src = newSrc;
}
return src;
} | javascript | function(src, noEscape) {
var attrLen, newKey;
if (helper.isArray(src)) {
var attrLen = src.length;
for (var i = 0; i < attrLen; i++) {
src[i] = helper.pasteurize(src[i], noEscape);
}
} else if (this.isString(src)) {
src = helper.scrub(src, noEscape);
} else if (helper.isObject(src)) {
var newSrc = {};
for (key in src) {
newKey = helper.scrub(key);
newSrc[newKey] = helper.pasteurize(src[key], noEscape);
}
src = newSrc;
}
return src;
} | [
"function",
"(",
"src",
",",
"noEscape",
")",
"{",
"var",
"attrLen",
",",
"newKey",
";",
"if",
"(",
"helper",
".",
"isArray",
"(",
"src",
")",
")",
"{",
"var",
"attrLen",
"=",
"src",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"attrLen",
";",
"i",
"++",
")",
"{",
"src",
"[",
"i",
"]",
"=",
"helper",
".",
"pasteurize",
"(",
"src",
"[",
"i",
"]",
",",
"noEscape",
")",
";",
"}",
"}",
"else",
"if",
"(",
"this",
".",
"isString",
"(",
"src",
")",
")",
"{",
"src",
"=",
"helper",
".",
"scrub",
"(",
"src",
",",
"noEscape",
")",
";",
"}",
"else",
"if",
"(",
"helper",
".",
"isObject",
"(",
"src",
")",
")",
"{",
"var",
"newSrc",
"=",
"{",
"}",
";",
"for",
"(",
"key",
"in",
"src",
")",
"{",
"newKey",
"=",
"helper",
".",
"scrub",
"(",
"key",
")",
";",
"newSrc",
"[",
"newKey",
"]",
"=",
"helper",
".",
"pasteurize",
"(",
"src",
"[",
"key",
"]",
",",
"noEscape",
")",
";",
"}",
"src",
"=",
"newSrc",
";",
"}",
"return",
"src",
";",
"}"
]
| Cleans an object thoroughly. Script scrubbed, html encoded. | [
"Cleans",
"an",
"object",
"thoroughly",
".",
"Script",
"scrubbed",
"html",
"encoded",
"."
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L215-L234 |
|
40,460 | bipio-server/bip-pod | index.js | function(host, whitelist, next) {
var blacklist = this.options.blacklist;
helper.resolveHost(host, function(err, aRecords, resolvedHost) {
var inBlacklist = false;
if (!err) {
if (whitelist) {
if (_.intersection(aRecords, whitelist).length ) {
next(err, [], aRecords);
return;
} else {
for (var i = 0; i < whitelist.length; i++) {
if (resolvedHost === whitelist[i]) {
next(err, [], aRecords);
return;
}
}
}
}
inBlacklist = _.intersection(aRecords, blacklist)
}
next(err, inBlacklist, aRecords);
});
} | javascript | function(host, whitelist, next) {
var blacklist = this.options.blacklist;
helper.resolveHost(host, function(err, aRecords, resolvedHost) {
var inBlacklist = false;
if (!err) {
if (whitelist) {
if (_.intersection(aRecords, whitelist).length ) {
next(err, [], aRecords);
return;
} else {
for (var i = 0; i < whitelist.length; i++) {
if (resolvedHost === whitelist[i]) {
next(err, [], aRecords);
return;
}
}
}
}
inBlacklist = _.intersection(aRecords, blacklist)
}
next(err, inBlacklist, aRecords);
});
} | [
"function",
"(",
"host",
",",
"whitelist",
",",
"next",
")",
"{",
"var",
"blacklist",
"=",
"this",
".",
"options",
".",
"blacklist",
";",
"helper",
".",
"resolveHost",
"(",
"host",
",",
"function",
"(",
"err",
",",
"aRecords",
",",
"resolvedHost",
")",
"{",
"var",
"inBlacklist",
"=",
"false",
";",
"if",
"(",
"!",
"err",
")",
"{",
"if",
"(",
"whitelist",
")",
"{",
"if",
"(",
"_",
".",
"intersection",
"(",
"aRecords",
",",
"whitelist",
")",
".",
"length",
")",
"{",
"next",
"(",
"err",
",",
"[",
"]",
",",
"aRecords",
")",
";",
"return",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"whitelist",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"resolvedHost",
"===",
"whitelist",
"[",
"i",
"]",
")",
"{",
"next",
"(",
"err",
",",
"[",
"]",
",",
"aRecords",
")",
";",
"return",
";",
"}",
"}",
"}",
"}",
"inBlacklist",
"=",
"_",
".",
"intersection",
"(",
"aRecords",
",",
"blacklist",
")",
"}",
"next",
"(",
"err",
",",
"inBlacklist",
",",
"aRecords",
")",
";",
"}",
")",
";",
"}"
]
| tests whether host is in blacklist | [
"tests",
"whether",
"host",
"is",
"in",
"blacklist"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L587-L610 |
|
40,461 | bipio-server/bip-pod | index.js | function(id, period, callback) {
var self = this;
if (this.$resource.cron) {
if (!this.crons[id]) {
self._logger.call(self, 'POD:Registering Cron:' + self.getName() + ':' + id);
self.crons[id] = new self.$resource.cron.CronJob(
period,
callback,
null,
true,
self.options.timezone
);
}
}
} | javascript | function(id, period, callback) {
var self = this;
if (this.$resource.cron) {
if (!this.crons[id]) {
self._logger.call(self, 'POD:Registering Cron:' + self.getName() + ':' + id);
self.crons[id] = new self.$resource.cron.CronJob(
period,
callback,
null,
true,
self.options.timezone
);
}
}
} | [
"function",
"(",
"id",
",",
"period",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"this",
".",
"$resource",
".",
"cron",
")",
"{",
"if",
"(",
"!",
"this",
".",
"crons",
"[",
"id",
"]",
")",
"{",
"self",
".",
"_logger",
".",
"call",
"(",
"self",
",",
"'POD:Registering Cron:'",
"+",
"self",
".",
"getName",
"(",
")",
"+",
"':'",
"+",
"id",
")",
";",
"self",
".",
"crons",
"[",
"id",
"]",
"=",
"new",
"self",
".",
"$resource",
".",
"cron",
".",
"CronJob",
"(",
"period",
",",
"callback",
",",
"null",
",",
"true",
",",
"self",
".",
"options",
".",
"timezone",
")",
";",
"}",
"}",
"}"
]
| provide a scheduler service | [
"provide",
"a",
"scheduler",
"service"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L859-L874 |
|
40,462 | bipio-server/bip-pod | index.js | function(message, channel, level) {
if (helper.isObject(message)) {
this._logger.call(this,
channel.action
+ ':'
+ (channel.owner_id ? channel.owner_id : 'system'),
level);
if (message.message) {
message = message;
}
this._logger.call(this, message, level);
} else {
this._logger.call(this,
channel.action
+ ':'
+ (channel.owner_id ? channel.owner_id : 'system')
+ ':'
+ message,
level);
}
} | javascript | function(message, channel, level) {
if (helper.isObject(message)) {
this._logger.call(this,
channel.action
+ ':'
+ (channel.owner_id ? channel.owner_id : 'system'),
level);
if (message.message) {
message = message;
}
this._logger.call(this, message, level);
} else {
this._logger.call(this,
channel.action
+ ':'
+ (channel.owner_id ? channel.owner_id : 'system')
+ ':'
+ message,
level);
}
} | [
"function",
"(",
"message",
",",
"channel",
",",
"level",
")",
"{",
"if",
"(",
"helper",
".",
"isObject",
"(",
"message",
")",
")",
"{",
"this",
".",
"_logger",
".",
"call",
"(",
"this",
",",
"channel",
".",
"action",
"+",
"':'",
"+",
"(",
"channel",
".",
"owner_id",
"?",
"channel",
".",
"owner_id",
":",
"'system'",
")",
",",
"level",
")",
";",
"if",
"(",
"message",
".",
"message",
")",
"{",
"message",
"=",
"message",
";",
"}",
"this",
".",
"_logger",
".",
"call",
"(",
"this",
",",
"message",
",",
"level",
")",
";",
"}",
"else",
"{",
"this",
".",
"_logger",
".",
"call",
"(",
"this",
",",
"channel",
".",
"action",
"+",
"':'",
"+",
"(",
"channel",
".",
"owner_id",
"?",
"channel",
".",
"owner_id",
":",
"'system'",
")",
"+",
"':'",
"+",
"message",
",",
"level",
")",
";",
"}",
"}"
]
| Logs a message | [
"Logs",
"a",
"message"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L909-L931 |
|
40,463 | bipio-server/bip-pod | index.js | function(owner_id, next) {
var self = this,
podName = this.getName(),
filter = {
owner_id : owner_id,
type : this.getAuthType(),
oauth_provider : this.getName()
};
this._dao.find('account_auth', filter, function(err, result) {
var model, authStruct;
if (result) {
// normalize oauth representation
authStruct = {
oauth_provider : result.oauth_provider,
repr : self._profileRepr(result)
}
}
next(err, podName, filter.type, authStruct);
});
} | javascript | function(owner_id, next) {
var self = this,
podName = this.getName(),
filter = {
owner_id : owner_id,
type : this.getAuthType(),
oauth_provider : this.getName()
};
this._dao.find('account_auth', filter, function(err, result) {
var model, authStruct;
if (result) {
// normalize oauth representation
authStruct = {
oauth_provider : result.oauth_provider,
repr : self._profileRepr(result)
}
}
next(err, podName, filter.type, authStruct);
});
} | [
"function",
"(",
"owner_id",
",",
"next",
")",
"{",
"var",
"self",
"=",
"this",
",",
"podName",
"=",
"this",
".",
"getName",
"(",
")",
",",
"filter",
"=",
"{",
"owner_id",
":",
"owner_id",
",",
"type",
":",
"this",
".",
"getAuthType",
"(",
")",
",",
"oauth_provider",
":",
"this",
".",
"getName",
"(",
")",
"}",
";",
"this",
".",
"_dao",
".",
"find",
"(",
"'account_auth'",
",",
"filter",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"var",
"model",
",",
"authStruct",
";",
"if",
"(",
"result",
")",
"{",
"// normalize oauth representation",
"authStruct",
"=",
"{",
"oauth_provider",
":",
"result",
".",
"oauth_provider",
",",
"repr",
":",
"self",
".",
"_profileRepr",
"(",
"result",
")",
"}",
"}",
"next",
"(",
"err",
",",
"podName",
",",
"filter",
".",
"type",
",",
"authStruct",
")",
";",
"}",
")",
";",
"}"
]
| passes oAuth result set if one exists | [
"passes",
"oAuth",
"result",
"set",
"if",
"one",
"exists"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L1183-L1204 |
|
40,464 | bipio-server/bip-pod | index.js | function(channel, next) {
var filter = {
channel_id : channel.id
},
modelName = this.getDataSourceName('dup');
this._dao.removeFilter(modelName, filter, next);
} | javascript | function(channel, next) {
var filter = {
channel_id : channel.id
},
modelName = this.getDataSourceName('dup');
this._dao.removeFilter(modelName, filter, next);
} | [
"function",
"(",
"channel",
",",
"next",
")",
"{",
"var",
"filter",
"=",
"{",
"channel_id",
":",
"channel",
".",
"id",
"}",
",",
"modelName",
"=",
"this",
".",
"getDataSourceName",
"(",
"'dup'",
")",
";",
"this",
".",
"_dao",
".",
"removeFilter",
"(",
"modelName",
",",
"filter",
",",
"next",
")",
";",
"}"
]
| tries to drop any duplicates from db | [
"tries",
"to",
"drop",
"any",
"duplicates",
"from",
"db"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L1707-L1714 |
|
40,465 | bipio-server/bip-pod | index.js | function(action, channel, accountInfo, auth, next) {
var self = this, config = this.getConfig();
if (!next && 'function' === typeof auth) {
next = auth;
} else {
if (self.isOAuth()) {
if (!auth.oauth) {
auth.oauth = {};
}
_.each(config.oauth, function(value, key) {
auth.oauth[key] = value;
});
}
accountInfo._setupAuth = auth;
}
if (this.actions[action] && this.actions[action].teardown) {
if (this.getTrackDuplicates()) {
// confirm teardown and drop any dup tracking from database
this.actions[action].teardown(channel, accountInfo, function(err) {
if (err) {
self.log(err, channel, 'error');
}
next(err);
self._dupTeardown(channel);
});
} else {
this.actions[action].teardown(channel, accountInfo, function(err) {
if (err) {
self.log(err, channel, 'error');
}
next(err);
});
}
} else {
if (this.getTrackDuplicates()) {
self._dupTeardown(channel);
}
next(false);
}
} | javascript | function(action, channel, accountInfo, auth, next) {
var self = this, config = this.getConfig();
if (!next && 'function' === typeof auth) {
next = auth;
} else {
if (self.isOAuth()) {
if (!auth.oauth) {
auth.oauth = {};
}
_.each(config.oauth, function(value, key) {
auth.oauth[key] = value;
});
}
accountInfo._setupAuth = auth;
}
if (this.actions[action] && this.actions[action].teardown) {
if (this.getTrackDuplicates()) {
// confirm teardown and drop any dup tracking from database
this.actions[action].teardown(channel, accountInfo, function(err) {
if (err) {
self.log(err, channel, 'error');
}
next(err);
self._dupTeardown(channel);
});
} else {
this.actions[action].teardown(channel, accountInfo, function(err) {
if (err) {
self.log(err, channel, 'error');
}
next(err);
});
}
} else {
if (this.getTrackDuplicates()) {
self._dupTeardown(channel);
}
next(false);
}
} | [
"function",
"(",
"action",
",",
"channel",
",",
"accountInfo",
",",
"auth",
",",
"next",
")",
"{",
"var",
"self",
"=",
"this",
",",
"config",
"=",
"this",
".",
"getConfig",
"(",
")",
";",
"if",
"(",
"!",
"next",
"&&",
"'function'",
"===",
"typeof",
"auth",
")",
"{",
"next",
"=",
"auth",
";",
"}",
"else",
"{",
"if",
"(",
"self",
".",
"isOAuth",
"(",
")",
")",
"{",
"if",
"(",
"!",
"auth",
".",
"oauth",
")",
"{",
"auth",
".",
"oauth",
"=",
"{",
"}",
";",
"}",
"_",
".",
"each",
"(",
"config",
".",
"oauth",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"auth",
".",
"oauth",
"[",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"}",
"accountInfo",
".",
"_setupAuth",
"=",
"auth",
";",
"}",
"if",
"(",
"this",
".",
"actions",
"[",
"action",
"]",
"&&",
"this",
".",
"actions",
"[",
"action",
"]",
".",
"teardown",
")",
"{",
"if",
"(",
"this",
".",
"getTrackDuplicates",
"(",
")",
")",
"{",
"// confirm teardown and drop any dup tracking from database",
"this",
".",
"actions",
"[",
"action",
"]",
".",
"teardown",
"(",
"channel",
",",
"accountInfo",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"self",
".",
"log",
"(",
"err",
",",
"channel",
",",
"'error'",
")",
";",
"}",
"next",
"(",
"err",
")",
";",
"self",
".",
"_dupTeardown",
"(",
"channel",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"actions",
"[",
"action",
"]",
".",
"teardown",
"(",
"channel",
",",
"accountInfo",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"self",
".",
"log",
"(",
"err",
",",
"channel",
",",
"'error'",
")",
";",
"}",
"next",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"getTrackDuplicates",
"(",
")",
")",
"{",
"self",
".",
"_dupTeardown",
"(",
"channel",
")",
";",
"}",
"next",
"(",
"false",
")",
";",
"}",
"}"
]
| Runs the teardown for a pod action if one exists | [
"Runs",
"the",
"teardown",
"for",
"a",
"pod",
"action",
"if",
"one",
"exists"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L1734-L1776 |
|
40,466 | bipio-server/bip-pod | index.js | function(action, method, sysImports, options, channel, req, res) {
var self = this;
if (this.actions[action] && (this.actions[action].rpc || 'invoke' === method)) {
if ('invoke' === method) {
var imports = (req.method === 'GET' ? req.query : req.body);
// @todo add files support
this.actions[action].invoke(imports, channel, sysImports, [], function(err, exports) {
if (err) {
self.log(err, channel, 'error');
}
res.contentType(DEFS.CONTENTTYPE_JSON);
if (err) {
res.send(err, 500);
} else {
res.send(exports);
}
});
} else {
this.actions[action].rpc(method, sysImports, options, channel, req, res);
}
} else {
res.send(404);
}
} | javascript | function(action, method, sysImports, options, channel, req, res) {
var self = this;
if (this.actions[action] && (this.actions[action].rpc || 'invoke' === method)) {
if ('invoke' === method) {
var imports = (req.method === 'GET' ? req.query : req.body);
// @todo add files support
this.actions[action].invoke(imports, channel, sysImports, [], function(err, exports) {
if (err) {
self.log(err, channel, 'error');
}
res.contentType(DEFS.CONTENTTYPE_JSON);
if (err) {
res.send(err, 500);
} else {
res.send(exports);
}
});
} else {
this.actions[action].rpc(method, sysImports, options, channel, req, res);
}
} else {
res.send(404);
}
} | [
"function",
"(",
"action",
",",
"method",
",",
"sysImports",
",",
"options",
",",
"channel",
",",
"req",
",",
"res",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"this",
".",
"actions",
"[",
"action",
"]",
"&&",
"(",
"this",
".",
"actions",
"[",
"action",
"]",
".",
"rpc",
"||",
"'invoke'",
"===",
"method",
")",
")",
"{",
"if",
"(",
"'invoke'",
"===",
"method",
")",
"{",
"var",
"imports",
"=",
"(",
"req",
".",
"method",
"===",
"'GET'",
"?",
"req",
".",
"query",
":",
"req",
".",
"body",
")",
";",
"// @todo add files support",
"this",
".",
"actions",
"[",
"action",
"]",
".",
"invoke",
"(",
"imports",
",",
"channel",
",",
"sysImports",
",",
"[",
"]",
",",
"function",
"(",
"err",
",",
"exports",
")",
"{",
"if",
"(",
"err",
")",
"{",
"self",
".",
"log",
"(",
"err",
",",
"channel",
",",
"'error'",
")",
";",
"}",
"res",
".",
"contentType",
"(",
"DEFS",
".",
"CONTENTTYPE_JSON",
")",
";",
"if",
"(",
"err",
")",
"{",
"res",
".",
"send",
"(",
"err",
",",
"500",
")",
";",
"}",
"else",
"{",
"res",
".",
"send",
"(",
"exports",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"actions",
"[",
"action",
"]",
".",
"rpc",
"(",
"method",
",",
"sysImports",
",",
"options",
",",
"channel",
",",
"req",
",",
"res",
")",
";",
"}",
"}",
"else",
"{",
"res",
".",
"send",
"(",
"404",
")",
";",
"}",
"}"
]
| RPC's are direct calls into a pod, so its up to the pod
to properly authenticate data etc. | [
"RPC",
"s",
"are",
"direct",
"calls",
"into",
"a",
"pod",
"so",
"its",
"up",
"to",
"the",
"pod",
"to",
"properly",
"authenticate",
"data",
"etc",
"."
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L2007-L2033 |
|
40,467 | bipio-server/bip-pod | index.js | function(accountInfo) {
var self = this,
rpcs = this.getRPCs(),
schema = {
'name' : this.getName(),
'title' : this.getTitle(),
'description' : this.getDescription(),
'icon' : this.getIcon(accountInfo),
'auth' : this.getAuth(),
'rpcs' : this.getRPCs(),
'url' : this.getBPMAttr('url'),
'actions' : this.formatActions(),
'tags' : this.getTags()
},
authType = this.getAuth().strategy;
// attach auth binders
if (authType == 'oauth') {
schema.auth.scopes = this.getConfig().oauth.scopes || [];
schema.auth._href = self.options.baseUrl + '/rpc/oauth/' + this.getName() + '/auth';
} else if (authType == 'issuer_token') {
schema.auth._href = self.options.baseUrl + '/rpc/issuer_token/' + this.getName() + '/set';
}
schema.auth.properties = this.getAuthProperties();
return schema;
} | javascript | function(accountInfo) {
var self = this,
rpcs = this.getRPCs(),
schema = {
'name' : this.getName(),
'title' : this.getTitle(),
'description' : this.getDescription(),
'icon' : this.getIcon(accountInfo),
'auth' : this.getAuth(),
'rpcs' : this.getRPCs(),
'url' : this.getBPMAttr('url'),
'actions' : this.formatActions(),
'tags' : this.getTags()
},
authType = this.getAuth().strategy;
// attach auth binders
if (authType == 'oauth') {
schema.auth.scopes = this.getConfig().oauth.scopes || [];
schema.auth._href = self.options.baseUrl + '/rpc/oauth/' + this.getName() + '/auth';
} else if (authType == 'issuer_token') {
schema.auth._href = self.options.baseUrl + '/rpc/issuer_token/' + this.getName() + '/set';
}
schema.auth.properties = this.getAuthProperties();
return schema;
} | [
"function",
"(",
"accountInfo",
")",
"{",
"var",
"self",
"=",
"this",
",",
"rpcs",
"=",
"this",
".",
"getRPCs",
"(",
")",
",",
"schema",
"=",
"{",
"'name'",
":",
"this",
".",
"getName",
"(",
")",
",",
"'title'",
":",
"this",
".",
"getTitle",
"(",
")",
",",
"'description'",
":",
"this",
".",
"getDescription",
"(",
")",
",",
"'icon'",
":",
"this",
".",
"getIcon",
"(",
"accountInfo",
")",
",",
"'auth'",
":",
"this",
".",
"getAuth",
"(",
")",
",",
"'rpcs'",
":",
"this",
".",
"getRPCs",
"(",
")",
",",
"'url'",
":",
"this",
".",
"getBPMAttr",
"(",
"'url'",
")",
",",
"'actions'",
":",
"this",
".",
"formatActions",
"(",
")",
",",
"'tags'",
":",
"this",
".",
"getTags",
"(",
")",
"}",
",",
"authType",
"=",
"this",
".",
"getAuth",
"(",
")",
".",
"strategy",
";",
"// attach auth binders",
"if",
"(",
"authType",
"==",
"'oauth'",
")",
"{",
"schema",
".",
"auth",
".",
"scopes",
"=",
"this",
".",
"getConfig",
"(",
")",
".",
"oauth",
".",
"scopes",
"||",
"[",
"]",
";",
"schema",
".",
"auth",
".",
"_href",
"=",
"self",
".",
"options",
".",
"baseUrl",
"+",
"'/rpc/oauth/'",
"+",
"this",
".",
"getName",
"(",
")",
"+",
"'/auth'",
";",
"}",
"else",
"if",
"(",
"authType",
"==",
"'issuer_token'",
")",
"{",
"schema",
".",
"auth",
".",
"_href",
"=",
"self",
".",
"options",
".",
"baseUrl",
"+",
"'/rpc/issuer_token/'",
"+",
"this",
".",
"getName",
"(",
")",
"+",
"'/set'",
";",
"}",
"schema",
".",
"auth",
".",
"properties",
"=",
"this",
".",
"getAuthProperties",
"(",
")",
";",
"return",
"schema",
";",
"}"
]
| Creates a json-schema-ish 'public' view of this Pod | [
"Creates",
"a",
"json",
"-",
"schema",
"-",
"ish",
"public",
"view",
"of",
"this",
"Pod"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L2168-L2195 |
|
40,468 | bipio-server/bip-pod | index.js | function(channel, next) {
var filter = {
channel_id : channel.id,
owner_id : channel.owner_id
};
this._dao.findFilter('channel_pod_tracking', filter, function(err, result) {
next(err || !result, result && result.length > 0 ? result[0].last_poll : null);
});
} | javascript | function(channel, next) {
var filter = {
channel_id : channel.id,
owner_id : channel.owner_id
};
this._dao.findFilter('channel_pod_tracking', filter, function(err, result) {
next(err || !result, result && result.length > 0 ? result[0].last_poll : null);
});
} | [
"function",
"(",
"channel",
",",
"next",
")",
"{",
"var",
"filter",
"=",
"{",
"channel_id",
":",
"channel",
".",
"id",
",",
"owner_id",
":",
"channel",
".",
"owner_id",
"}",
";",
"this",
".",
"_dao",
".",
"findFilter",
"(",
"'channel_pod_tracking'",
",",
"filter",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"next",
"(",
"err",
"||",
"!",
"result",
",",
"result",
"&&",
"result",
".",
"length",
">",
"0",
"?",
"result",
"[",
"0",
"]",
".",
"last_poll",
":",
"null",
")",
";",
"}",
")",
";",
"}"
]
| get last poll time for tracker | [
"get",
"last",
"poll",
"time",
"for",
"tracker"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L2308-L2317 |
|
40,469 | bipio-server/bip-pod | index.js | function(channel, next) {
var filter = {
channel_id : channel.id,
owner_id : channel.owner_id
},
self = this,
props = {
last_poll : helper.nowUTCSeconds()
}
this._dao.updateColumn(
'channel_pod_tracking',
filter,
props,
function(err) {
if (err) {
self.log(err, 'error');
}
next(err, props.last_poll);
}
);
} | javascript | function(channel, next) {
var filter = {
channel_id : channel.id,
owner_id : channel.owner_id
},
self = this,
props = {
last_poll : helper.nowUTCSeconds()
}
this._dao.updateColumn(
'channel_pod_tracking',
filter,
props,
function(err) {
if (err) {
self.log(err, 'error');
}
next(err, props.last_poll);
}
);
} | [
"function",
"(",
"channel",
",",
"next",
")",
"{",
"var",
"filter",
"=",
"{",
"channel_id",
":",
"channel",
".",
"id",
",",
"owner_id",
":",
"channel",
".",
"owner_id",
"}",
",",
"self",
"=",
"this",
",",
"props",
"=",
"{",
"last_poll",
":",
"helper",
".",
"nowUTCSeconds",
"(",
")",
"}",
"this",
".",
"_dao",
".",
"updateColumn",
"(",
"'channel_pod_tracking'",
",",
"filter",
",",
"props",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"self",
".",
"log",
"(",
"err",
",",
"'error'",
")",
";",
"}",
"next",
"(",
"err",
",",
"props",
".",
"last_poll",
")",
";",
"}",
")",
";",
"}"
]
| set last poll time | [
"set",
"last",
"poll",
"time"
]
| 360e283f2ec61b163d992fb294dd99e00f84ca46 | https://github.com/bipio-server/bip-pod/blob/360e283f2ec61b163d992fb294dd99e00f84ca46/index.js#L2320-L2341 |
|
40,470 | right-track/right-track-core | modules/query/StopsTable.js | getStopByName | function getStopByName(db, name, callback) {
// Check cache for Stop
let cacheKey = db.id + "-" + name;
let cache = cache_stopByName.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Different queries to lookup stop by name
let queries = [
"SELECT stop_id FROM gtfs_stops WHERE stop_name='" + name + "' COLLATE NOCASE;",
"SELECT stop_id FROM rt_alt_stop_names WHERE alt_stop_name='" + name + "' COLLATE NOCASE;",
"SELECT stop_id FROM rt_stops_extra WHERE display_name='" + name + "' COLLATE NOCASE;"
];
// Test each query for the stop name
let found = false;
let count = 0;
for ( let i = 0; i < queries.length; i++ ) {
// Perform the specified query
_queryForStopByName(db, queries[i], function(stop) {
// Return the result: if not already found and the query was successful
if ( !found && stop !== undefined ) {
found = true;
cache_stopByName.put(cacheKey, stop);
return callback(null, stop);
}
// Return after all queries have finished
count ++;
if ( count === queries.length ) {
return callback(null, undefined);
}
});
}
} | javascript | function getStopByName(db, name, callback) {
// Check cache for Stop
let cacheKey = db.id + "-" + name;
let cache = cache_stopByName.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Different queries to lookup stop by name
let queries = [
"SELECT stop_id FROM gtfs_stops WHERE stop_name='" + name + "' COLLATE NOCASE;",
"SELECT stop_id FROM rt_alt_stop_names WHERE alt_stop_name='" + name + "' COLLATE NOCASE;",
"SELECT stop_id FROM rt_stops_extra WHERE display_name='" + name + "' COLLATE NOCASE;"
];
// Test each query for the stop name
let found = false;
let count = 0;
for ( let i = 0; i < queries.length; i++ ) {
// Perform the specified query
_queryForStopByName(db, queries[i], function(stop) {
// Return the result: if not already found and the query was successful
if ( !found && stop !== undefined ) {
found = true;
cache_stopByName.put(cacheKey, stop);
return callback(null, stop);
}
// Return after all queries have finished
count ++;
if ( count === queries.length ) {
return callback(null, undefined);
}
});
}
} | [
"function",
"getStopByName",
"(",
"db",
",",
"name",
",",
"callback",
")",
"{",
"// Check cache for Stop",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"name",
";",
"let",
"cache",
"=",
"cache_stopByName",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Different queries to lookup stop by name",
"let",
"queries",
"=",
"[",
"\"SELECT stop_id FROM gtfs_stops WHERE stop_name='\"",
"+",
"name",
"+",
"\"' COLLATE NOCASE;\"",
",",
"\"SELECT stop_id FROM rt_alt_stop_names WHERE alt_stop_name='\"",
"+",
"name",
"+",
"\"' COLLATE NOCASE;\"",
",",
"\"SELECT stop_id FROM rt_stops_extra WHERE display_name='\"",
"+",
"name",
"+",
"\"' COLLATE NOCASE;\"",
"]",
";",
"// Test each query for the stop name",
"let",
"found",
"=",
"false",
";",
"let",
"count",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"queries",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Perform the specified query",
"_queryForStopByName",
"(",
"db",
",",
"queries",
"[",
"i",
"]",
",",
"function",
"(",
"stop",
")",
"{",
"// Return the result: if not already found and the query was successful",
"if",
"(",
"!",
"found",
"&&",
"stop",
"!==",
"undefined",
")",
"{",
"found",
"=",
"true",
";",
"cache_stopByName",
".",
"put",
"(",
"cacheKey",
",",
"stop",
")",
";",
"return",
"callback",
"(",
"null",
",",
"stop",
")",
";",
"}",
"// Return after all queries have finished",
"count",
"++",
";",
"if",
"(",
"count",
"===",
"queries",
".",
"length",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Get the Stop specified by name from the passed database
@param {RightTrackDB} db The Right Track Database to query
@param {string} name Stop Name (found in either gtfs_stops, rt_alt_stop_names or rt_stops_extra tables)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Stop} [callback.stop] The selected Stop | [
"Get",
"the",
"Stop",
"specified",
"by",
"name",
"from",
"the",
"passed",
"database"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/StopsTable.js#L142-L182 |
40,471 | right-track/right-track-core | modules/query/StopsTable.js | _queryForStopByName | function _queryForStopByName(db, query, callback) {
// Perform the search query
db.get(query, function(err, result) {
// No stop found, return undefined
if ( result === undefined ) {
return callback(undefined);
}
// Stop found, return the Stop from it's ID
getStop(db, result.stop_id, function(err, stop) {
return callback(stop);
});
});
} | javascript | function _queryForStopByName(db, query, callback) {
// Perform the search query
db.get(query, function(err, result) {
// No stop found, return undefined
if ( result === undefined ) {
return callback(undefined);
}
// Stop found, return the Stop from it's ID
getStop(db, result.stop_id, function(err, stop) {
return callback(stop);
});
});
} | [
"function",
"_queryForStopByName",
"(",
"db",
",",
"query",
",",
"callback",
")",
"{",
"// Perform the search query",
"db",
".",
"get",
"(",
"query",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"// No stop found, return undefined",
"if",
"(",
"result",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"undefined",
")",
";",
"}",
"// Stop found, return the Stop from it's ID",
"getStop",
"(",
"db",
",",
"result",
".",
"stop_id",
",",
"function",
"(",
"err",
",",
"stop",
")",
"{",
"return",
"callback",
"(",
"stop",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Perform a query searching for Stop by it's name
@param {RightTrackDB} db The Right Track Database to query
@param {string} query The full SELECT query to perform
@param {function} callback Callback function(Stop)
@private | [
"Perform",
"a",
"query",
"searching",
"for",
"Stop",
"by",
"it",
"s",
"name"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/StopsTable.js#L191-L208 |
40,472 | right-track/right-track-core | modules/query/StopsTable.js | getStopByStatusId | function getStopByStatusId(db, statusId, callback) {
// Make sure statusId is not -1
if ( statusId === "-1" ) {
return callback(
new Error('Stop does not have a valid Status ID')
);
}
// Check cache for stop
let cacheKey = db.id + "-" + statusId;
let cache = cache_stopByStatusId.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build select statement
let select = "SELECT gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, " +
"gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, " +
"rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id " +
"FROM gtfs_stops, rt_stops_extra " +
"WHERE gtfs_stops.stop_id=rt_stops_extra.stop_id AND " +
"rt_stops_extra.status_id='" + statusId + "';";
// Query the database
db.get(select, function(err, result) {
// Database Error
if ( err ) {
return callback(err);
}
// No Stop found...
if ( result === undefined ) {
return callback(null, undefined);
}
// Use rt display_name if provided
let final_name = result.stop_name;
if ( result.display_name !== undefined && result.display_name !== "" ) {
final_name = result.display_name;
}
// Get zone_id from rt_stops_extra if not defined in gtfs_stops
let zone_id = result.gtfs_zone_id;
if ( zone_id === null || zone_id === undefined ) {
zone_id = result.rt_zone_id;
}
// build the Stop
let stop = new Stop(
result.stop_id,
final_name,
result.stop_lat,
result.stop_lon,
{
code: result.stop_code,
description: result.stop_desc,
zoneId: zone_id,
url: result.stop_url,
locationType: result.location_type,
parentStation: result.parent_station,
timezone: result.stop_timezone,
wheelchairBoarding: result.wheelchair_boarding,
statusId: result.status_id,
transferWeight: result.transfer_weight
}
);
// Add Stop to cache
cache_stopByStatusId.put(cacheKey, stop);
// return the Stop in the callback
return callback(null, stop);
});
} | javascript | function getStopByStatusId(db, statusId, callback) {
// Make sure statusId is not -1
if ( statusId === "-1" ) {
return callback(
new Error('Stop does not have a valid Status ID')
);
}
// Check cache for stop
let cacheKey = db.id + "-" + statusId;
let cache = cache_stopByStatusId.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build select statement
let select = "SELECT gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, " +
"gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, " +
"rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id " +
"FROM gtfs_stops, rt_stops_extra " +
"WHERE gtfs_stops.stop_id=rt_stops_extra.stop_id AND " +
"rt_stops_extra.status_id='" + statusId + "';";
// Query the database
db.get(select, function(err, result) {
// Database Error
if ( err ) {
return callback(err);
}
// No Stop found...
if ( result === undefined ) {
return callback(null, undefined);
}
// Use rt display_name if provided
let final_name = result.stop_name;
if ( result.display_name !== undefined && result.display_name !== "" ) {
final_name = result.display_name;
}
// Get zone_id from rt_stops_extra if not defined in gtfs_stops
let zone_id = result.gtfs_zone_id;
if ( zone_id === null || zone_id === undefined ) {
zone_id = result.rt_zone_id;
}
// build the Stop
let stop = new Stop(
result.stop_id,
final_name,
result.stop_lat,
result.stop_lon,
{
code: result.stop_code,
description: result.stop_desc,
zoneId: zone_id,
url: result.stop_url,
locationType: result.location_type,
parentStation: result.parent_station,
timezone: result.stop_timezone,
wheelchairBoarding: result.wheelchair_boarding,
statusId: result.status_id,
transferWeight: result.transfer_weight
}
);
// Add Stop to cache
cache_stopByStatusId.put(cacheKey, stop);
// return the Stop in the callback
return callback(null, stop);
});
} | [
"function",
"getStopByStatusId",
"(",
"db",
",",
"statusId",
",",
"callback",
")",
"{",
"// Make sure statusId is not -1",
"if",
"(",
"statusId",
"===",
"\"-1\"",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Stop does not have a valid Status ID'",
")",
")",
";",
"}",
"// Check cache for stop",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"statusId",
";",
"let",
"cache",
"=",
"cache_stopByStatusId",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Build select statement",
"let",
"select",
"=",
"\"SELECT gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, \"",
"+",
"\"gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, \"",
"+",
"\"rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id \"",
"+",
"\"FROM gtfs_stops, rt_stops_extra \"",
"+",
"\"WHERE gtfs_stops.stop_id=rt_stops_extra.stop_id AND \"",
"+",
"\"rt_stops_extra.status_id='\"",
"+",
"statusId",
"+",
"\"';\"",
";",
"// Query the database",
"db",
".",
"get",
"(",
"select",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"// Database Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// No Stop found...",
"if",
"(",
"result",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"// Use rt display_name if provided",
"let",
"final_name",
"=",
"result",
".",
"stop_name",
";",
"if",
"(",
"result",
".",
"display_name",
"!==",
"undefined",
"&&",
"result",
".",
"display_name",
"!==",
"\"\"",
")",
"{",
"final_name",
"=",
"result",
".",
"display_name",
";",
"}",
"// Get zone_id from rt_stops_extra if not defined in gtfs_stops",
"let",
"zone_id",
"=",
"result",
".",
"gtfs_zone_id",
";",
"if",
"(",
"zone_id",
"===",
"null",
"||",
"zone_id",
"===",
"undefined",
")",
"{",
"zone_id",
"=",
"result",
".",
"rt_zone_id",
";",
"}",
"// build the Stop",
"let",
"stop",
"=",
"new",
"Stop",
"(",
"result",
".",
"stop_id",
",",
"final_name",
",",
"result",
".",
"stop_lat",
",",
"result",
".",
"stop_lon",
",",
"{",
"code",
":",
"result",
".",
"stop_code",
",",
"description",
":",
"result",
".",
"stop_desc",
",",
"zoneId",
":",
"zone_id",
",",
"url",
":",
"result",
".",
"stop_url",
",",
"locationType",
":",
"result",
".",
"location_type",
",",
"parentStation",
":",
"result",
".",
"parent_station",
",",
"timezone",
":",
"result",
".",
"stop_timezone",
",",
"wheelchairBoarding",
":",
"result",
".",
"wheelchair_boarding",
",",
"statusId",
":",
"result",
".",
"status_id",
",",
"transferWeight",
":",
"result",
".",
"transfer_weight",
"}",
")",
";",
"// Add Stop to cache",
"cache_stopByStatusId",
".",
"put",
"(",
"cacheKey",
",",
"stop",
")",
";",
"// return the Stop in the callback",
"return",
"callback",
"(",
"null",
",",
"stop",
")",
";",
"}",
")",
";",
"}"
]
| Get the Stop specified by status id from the passed database
@param {RightTrackDB} db The Right Track Database to query
@param {string} statusId the status id of the Stop
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Stop} [callback.stop] The selected Stop | [
"Get",
"the",
"Stop",
"specified",
"by",
"status",
"id",
"from",
"the",
"passed",
"database"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/StopsTable.js#L220-L298 |
40,473 | right-track/right-track-core | modules/query/StopsTable.js | _parseStopsByLocation | function _parseStopsByLocation(stops, lat, lon, count, distance, callback) {
// Calc distance to/from each stop
for ( let i = 0; i < stops.length; i++ ) {
stops[i].setDistance(lat, lon);
}
// Sort by distance
stops.sort(Stop.sortByDistance);
// Filter the stops to return
let rtn = [];
// Return 'count' stops
if ( count !== -1 ) {
for ( let i = 0; i < count; i++ ) {
if ( stops.length > i ) {
rtn.push(stops[i]);
}
}
}
// No 'count' specified, add all stops
else {
rtn = stops;
}
// Filter by distance
if ( distance !== -1 ) {
let temp = [];
for ( let i = 0; i < rtn.length; i++ ) {
if ( rtn[i].distance <= distance ) {
temp.push(rtn[i]);
}
}
rtn = temp;
}
// Return the Stops
return callback(null, rtn);
} | javascript | function _parseStopsByLocation(stops, lat, lon, count, distance, callback) {
// Calc distance to/from each stop
for ( let i = 0; i < stops.length; i++ ) {
stops[i].setDistance(lat, lon);
}
// Sort by distance
stops.sort(Stop.sortByDistance);
// Filter the stops to return
let rtn = [];
// Return 'count' stops
if ( count !== -1 ) {
for ( let i = 0; i < count; i++ ) {
if ( stops.length > i ) {
rtn.push(stops[i]);
}
}
}
// No 'count' specified, add all stops
else {
rtn = stops;
}
// Filter by distance
if ( distance !== -1 ) {
let temp = [];
for ( let i = 0; i < rtn.length; i++ ) {
if ( rtn[i].distance <= distance ) {
temp.push(rtn[i]);
}
}
rtn = temp;
}
// Return the Stops
return callback(null, rtn);
} | [
"function",
"_parseStopsByLocation",
"(",
"stops",
",",
"lat",
",",
"lon",
",",
"count",
",",
"distance",
",",
"callback",
")",
"{",
"// Calc distance to/from each stop",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"stops",
".",
"length",
";",
"i",
"++",
")",
"{",
"stops",
"[",
"i",
"]",
".",
"setDistance",
"(",
"lat",
",",
"lon",
")",
";",
"}",
"// Sort by distance",
"stops",
".",
"sort",
"(",
"Stop",
".",
"sortByDistance",
")",
";",
"// Filter the stops to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Return 'count' stops",
"if",
"(",
"count",
"!==",
"-",
"1",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"{",
"if",
"(",
"stops",
".",
"length",
">",
"i",
")",
"{",
"rtn",
".",
"push",
"(",
"stops",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"// No 'count' specified, add all stops",
"else",
"{",
"rtn",
"=",
"stops",
";",
"}",
"// Filter by distance",
"if",
"(",
"distance",
"!==",
"-",
"1",
")",
"{",
"let",
"temp",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"rtn",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rtn",
"[",
"i",
"]",
".",
"distance",
"<=",
"distance",
")",
"{",
"temp",
".",
"push",
"(",
"rtn",
"[",
"i",
"]",
")",
";",
"}",
"}",
"rtn",
"=",
"temp",
";",
"}",
"// Return the Stops",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}"
]
| Parse the Stops by the Location Information
@param {Stop[]} stops List of Stops to parse
@param {number} lat Location Latitude
@param {number} lon Location Longitude
@param {int} count Max number of stops to return (-1 for unlimited)
@param {number} distance Max distance from location (-1 for no limit)
@param {function} callback Callback function(err, stops)
@private | [
"Parse",
"the",
"Stops",
"by",
"the",
"Location",
"Information"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/StopsTable.js#L566-L611 |
40,474 | right-track/right-track-core | modules/query/StopsTable.js | clearCache | function clearCache() {
cache_stopById.clear();
cache_stopByName.clear();
cache_stopByStatusId.clear();
cache_stops.clear();
cache_stopsByRoute.clear();
} | javascript | function clearCache() {
cache_stopById.clear();
cache_stopByName.clear();
cache_stopByStatusId.clear();
cache_stops.clear();
cache_stopsByRoute.clear();
} | [
"function",
"clearCache",
"(",
")",
"{",
"cache_stopById",
".",
"clear",
"(",
")",
";",
"cache_stopByName",
".",
"clear",
"(",
")",
";",
"cache_stopByStatusId",
".",
"clear",
"(",
")",
";",
"cache_stops",
".",
"clear",
"(",
")",
";",
"cache_stopsByRoute",
".",
"clear",
"(",
")",
";",
"}"
]
| Clear the StopsTable caches
@private | [
"Clear",
"the",
"StopsTable",
"caches"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/StopsTable.js#L626-L632 |
40,475 | right-track/right-track-core | modules/utils/calc.js | distance | function distance(lat1, lon1, lat2, lon2) {
let R = 6371; // Radius of the earth in km
let dLat = _deg2rad(lat2-lat1); // deg2rad below
let dLon = _deg2rad(lon2-lon1);
let a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(_deg2rad(lat1)) * Math.cos(_deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
let d = R * c; // Distance in km
return d * 0.621371; // Return distance in miles
} | javascript | function distance(lat1, lon1, lat2, lon2) {
let R = 6371; // Radius of the earth in km
let dLat = _deg2rad(lat2-lat1); // deg2rad below
let dLon = _deg2rad(lon2-lon1);
let a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(_deg2rad(lat1)) * Math.cos(_deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
let d = R * c; // Distance in km
return d * 0.621371; // Return distance in miles
} | [
"function",
"distance",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
")",
"{",
"let",
"R",
"=",
"6371",
";",
"// Radius of the earth in km",
"let",
"dLat",
"=",
"_deg2rad",
"(",
"lat2",
"-",
"lat1",
")",
";",
"// deg2rad below",
"let",
"dLon",
"=",
"_deg2rad",
"(",
"lon2",
"-",
"lon1",
")",
";",
"let",
"a",
"=",
"Math",
".",
"sin",
"(",
"dLat",
"/",
"2",
")",
"*",
"Math",
".",
"sin",
"(",
"dLat",
"/",
"2",
")",
"+",
"Math",
".",
"cos",
"(",
"_deg2rad",
"(",
"lat1",
")",
")",
"*",
"Math",
".",
"cos",
"(",
"_deg2rad",
"(",
"lat2",
")",
")",
"*",
"Math",
".",
"sin",
"(",
"dLon",
"/",
"2",
")",
"*",
"Math",
".",
"sin",
"(",
"dLon",
"/",
"2",
")",
";",
"let",
"c",
"=",
"2",
"*",
"Math",
".",
"atan2",
"(",
"Math",
".",
"sqrt",
"(",
"a",
")",
",",
"Math",
".",
"sqrt",
"(",
"1",
"-",
"a",
")",
")",
";",
"let",
"d",
"=",
"R",
"*",
"c",
";",
"// Distance in km",
"return",
"d",
"*",
"0.621371",
";",
"// Return distance in miles",
"}"
]
| Right Track calculation helper functions
@module utils/calc
Calculate the (Great-Circle) Distance between two points
@param {number} lat1 Latitude of Point 1
@param {number} lon1 Longitude of Point 1
@param {number} lat2 Latitude of Point 2
@param {number} lon2 Longitude of Point 2
@returns {number} distance between points in miles | [
"Right",
"Track",
"calculation",
"helper",
"functions"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/utils/calc.js#L17-L29 |
40,476 | right-track/right-track-core | modules/query/LineGraphTable.js | getPaths | function getPaths(db, originId, destinationId, callback) {
// Get Graph
buildGraph(db, function(err, graph) {
if ( err ) {
return callback(err);
}
// Paths to return
let rtn = [];
// Search the Graph
for ( let it = graph.paths(originId, destinationId), kv; !(kv = it.next()).done;) {
let path = [];
for ( let i = 0; i < kv.value.length; i++ ) {
let stop = graph.vertexValue(kv.value[i]);
path.push({
id: stop.id,
weight: stop.transferWeight
});
}
rtn.push(path);
}
// Return the paths
return callback(null, rtn);
});
} | javascript | function getPaths(db, originId, destinationId, callback) {
// Get Graph
buildGraph(db, function(err, graph) {
if ( err ) {
return callback(err);
}
// Paths to return
let rtn = [];
// Search the Graph
for ( let it = graph.paths(originId, destinationId), kv; !(kv = it.next()).done;) {
let path = [];
for ( let i = 0; i < kv.value.length; i++ ) {
let stop = graph.vertexValue(kv.value[i]);
path.push({
id: stop.id,
weight: stop.transferWeight
});
}
rtn.push(path);
}
// Return the paths
return callback(null, rtn);
});
} | [
"function",
"getPaths",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"callback",
")",
"{",
"// Get Graph",
"buildGraph",
"(",
"db",
",",
"function",
"(",
"err",
",",
"graph",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Paths to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Search the Graph",
"for",
"(",
"let",
"it",
"=",
"graph",
".",
"paths",
"(",
"originId",
",",
"destinationId",
")",
",",
"kv",
";",
"!",
"(",
"kv",
"=",
"it",
".",
"next",
"(",
")",
")",
".",
"done",
";",
")",
"{",
"let",
"path",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"kv",
".",
"value",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"stop",
"=",
"graph",
".",
"vertexValue",
"(",
"kv",
".",
"value",
"[",
"i",
"]",
")",
";",
"path",
".",
"push",
"(",
"{",
"id",
":",
"stop",
".",
"id",
",",
"weight",
":",
"stop",
".",
"transferWeight",
"}",
")",
";",
"}",
"rtn",
".",
"push",
"(",
"path",
")",
";",
"}",
"// Return the paths",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
")",
";",
"}"
]
| Get all possible paths from the origin to the destination following the
Agency Line Graph
@param {RightTrackDB} db The Right Track DB to Query
@param {String} originId Origin Stop ID
@param {String} destinationId Destination Stop ID
@param {function} callback Callback Function
@param {Error} callback.err Database Query Error
@param {Object[][]} [callback.paths] Route Paths
@param {String} callback.paths[].id Stop ID
@param {int} callback.paths[].weight Stop Transfer Weight | [
"Get",
"all",
"possible",
"paths",
"from",
"the",
"origin",
"to",
"the",
"destination",
"following",
"the",
"Agency",
"Line",
"Graph"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/LineGraphTable.js#L122-L151 |
40,477 | right-track/right-track-core | modules/query/LineGraphTable.js | buildGraph | function buildGraph(db, callback) {
// Check cache for graph
let cacheKey = db.id + "-graph";
let cache = cache_graph.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build Graph
let graph = new Graph();
// Add the Vertices
_addGraphVertices(db, graph, function(err, graph) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add Graph Edges
_addGraphEdges(db, graph, function(err, graph) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Return the finished graph
cache_graph.put(cacheKey, graph);
return callback(null, graph);
});
});
} | javascript | function buildGraph(db, callback) {
// Check cache for graph
let cacheKey = db.id + "-graph";
let cache = cache_graph.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build Graph
let graph = new Graph();
// Add the Vertices
_addGraphVertices(db, graph, function(err, graph) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add Graph Edges
_addGraphEdges(db, graph, function(err, graph) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Return the finished graph
cache_graph.put(cacheKey, graph);
return callback(null, graph);
});
});
} | [
"function",
"buildGraph",
"(",
"db",
",",
"callback",
")",
"{",
"// Check cache for graph",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-graph\"",
";",
"let",
"cache",
"=",
"cache_graph",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Build Graph",
"let",
"graph",
"=",
"new",
"Graph",
"(",
")",
";",
"// Add the Vertices",
"_addGraphVertices",
"(",
"db",
",",
"graph",
",",
"function",
"(",
"err",
",",
"graph",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add Graph Edges",
"_addGraphEdges",
"(",
"db",
",",
"graph",
",",
"function",
"(",
"err",
",",
"graph",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Return the finished graph",
"cache_graph",
".",
"put",
"(",
"cacheKey",
",",
"graph",
")",
";",
"return",
"callback",
"(",
"null",
",",
"graph",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Build the entire Agency Line Graph
@param {RightTrackDB} db The Right Track DB to query
@param {function} callback Callback function
@param {Error} callback.err Database Query Error
@param {Graph} [callback.graph] Agency Graph
@see {@link https://www.npmjs.com/package/graph.js|graph.js package} | [
"Build",
"the",
"entire",
"Agency",
"Line",
"Graph"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/LineGraphTable.js#L163-L199 |
40,478 | right-track/right-track-core | modules/query/LineGraphTable.js | _addGraphVertices | function _addGraphVertices(db, graph, callback) {
// Get all Stops
StopsTable.getStops(db, function(err, stops) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add each Stop as a Vertex
for ( let i = 0; i < stops.length; i++ ) {
graph.addNewVertex(stops[i].id, stops[i]);
}
// Return the Graph
return callback(null, graph);
});
} | javascript | function _addGraphVertices(db, graph, callback) {
// Get all Stops
StopsTable.getStops(db, function(err, stops) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add each Stop as a Vertex
for ( let i = 0; i < stops.length; i++ ) {
graph.addNewVertex(stops[i].id, stops[i]);
}
// Return the Graph
return callback(null, graph);
});
} | [
"function",
"_addGraphVertices",
"(",
"db",
",",
"graph",
",",
"callback",
")",
"{",
"// Get all Stops",
"StopsTable",
".",
"getStops",
"(",
"db",
",",
"function",
"(",
"err",
",",
"stops",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add each Stop as a Vertex",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"stops",
".",
"length",
";",
"i",
"++",
")",
"{",
"graph",
".",
"addNewVertex",
"(",
"stops",
"[",
"i",
"]",
".",
"id",
",",
"stops",
"[",
"i",
"]",
")",
";",
"}",
"// Return the Graph",
"return",
"callback",
"(",
"null",
",",
"graph",
")",
";",
"}",
")",
";",
"}"
]
| Add all Stops as Vertices to the Graph
@param {RightTrackDB} db The Right Track DB to query
@param {Graph} graph The Graph to add vertices to
@param {function} callback Callback function(err, graph)
@private | [
"Add",
"all",
"Stops",
"as",
"Vertices",
"to",
"the",
"Graph"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/LineGraphTable.js#L209-L229 |
40,479 | right-track/right-track-core | modules/query/LineGraphTable.js | _addGraphEdges | function _addGraphEdges(db, graph, callback) {
// Counters
let done = 0;
let count = graph.vertexCount();
// Loop through each Vertex in the Graph
for ( let [stopId, stop] of graph ) {
// Get the Edges for the Vertex
_getStopEdges(db, stopId, function(err, edges) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add each edge to the Graph
for ( let i = 0; i < edges.length; i++ ) {
graph.ensureEdge(stopId, edges[i]);
graph.ensureEdge(edges[i], stopId);
}
// Finish the Vertex
_finish();
});
}
// Keep track of finished vertices
function _finish() {
done++;
if ( done === count ) {
return callback(null, graph);
}
}
} | javascript | function _addGraphEdges(db, graph, callback) {
// Counters
let done = 0;
let count = graph.vertexCount();
// Loop through each Vertex in the Graph
for ( let [stopId, stop] of graph ) {
// Get the Edges for the Vertex
_getStopEdges(db, stopId, function(err, edges) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add each edge to the Graph
for ( let i = 0; i < edges.length; i++ ) {
graph.ensureEdge(stopId, edges[i]);
graph.ensureEdge(edges[i], stopId);
}
// Finish the Vertex
_finish();
});
}
// Keep track of finished vertices
function _finish() {
done++;
if ( done === count ) {
return callback(null, graph);
}
}
} | [
"function",
"_addGraphEdges",
"(",
"db",
",",
"graph",
",",
"callback",
")",
"{",
"// Counters",
"let",
"done",
"=",
"0",
";",
"let",
"count",
"=",
"graph",
".",
"vertexCount",
"(",
")",
";",
"// Loop through each Vertex in the Graph",
"for",
"(",
"let",
"[",
"stopId",
",",
"stop",
"]",
"of",
"graph",
")",
"{",
"// Get the Edges for the Vertex",
"_getStopEdges",
"(",
"db",
",",
"stopId",
",",
"function",
"(",
"err",
",",
"edges",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add each edge to the Graph",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"edges",
".",
"length",
";",
"i",
"++",
")",
"{",
"graph",
".",
"ensureEdge",
"(",
"stopId",
",",
"edges",
"[",
"i",
"]",
")",
";",
"graph",
".",
"ensureEdge",
"(",
"edges",
"[",
"i",
"]",
",",
"stopId",
")",
";",
"}",
"// Finish the Vertex",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"// Keep track of finished vertices",
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"done",
"===",
"count",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"graph",
")",
";",
"}",
"}",
"}"
]
| Add edges to each Vertex in the Graph
@param {RightTrackDB} db The Right Track DB to query
@param {Graph} graph The Graph to add edges to
@param {function} callback Callback function(err, graph)
@private | [
"Add",
"edges",
"to",
"each",
"Vertex",
"in",
"the",
"Graph"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/LineGraphTable.js#L238-L276 |
40,480 | joyent/node-zsock | lib/zsock.js | createZoneSocket | function createZoneSocket(options, callback) {
if (!options) throw new TypeError('options required');
if (!(options instanceof Object)) {
throw new TypeError('options must be an Object');
}
if (!options.zone) throw new TypeError('options.zone required');
if (!options.path) throw new TypeError('options.path required');
if (!callback) throw new TypeError('callback required');
if (!(callback instanceof Function)) {
throw new TypeError('callback must be a Function');
}
var backlog = options.backlog ? options.backlog : 5;
bindings.zsocket(options.zone, options.path, backlog, callback);
} | javascript | function createZoneSocket(options, callback) {
if (!options) throw new TypeError('options required');
if (!(options instanceof Object)) {
throw new TypeError('options must be an Object');
}
if (!options.zone) throw new TypeError('options.zone required');
if (!options.path) throw new TypeError('options.path required');
if (!callback) throw new TypeError('callback required');
if (!(callback instanceof Function)) {
throw new TypeError('callback must be a Function');
}
var backlog = options.backlog ? options.backlog : 5;
bindings.zsocket(options.zone, options.path, backlog, callback);
} | [
"function",
"createZoneSocket",
"(",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"options",
")",
"throw",
"new",
"TypeError",
"(",
"'options required'",
")",
";",
"if",
"(",
"!",
"(",
"options",
"instanceof",
"Object",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'options must be an Object'",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"zone",
")",
"throw",
"new",
"TypeError",
"(",
"'options.zone required'",
")",
";",
"if",
"(",
"!",
"options",
".",
"path",
")",
"throw",
"new",
"TypeError",
"(",
"'options.path required'",
")",
";",
"if",
"(",
"!",
"callback",
")",
"throw",
"new",
"TypeError",
"(",
"'callback required'",
")",
";",
"if",
"(",
"!",
"(",
"callback",
"instanceof",
"Function",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'callback must be a Function'",
")",
";",
"}",
"var",
"backlog",
"=",
"options",
".",
"backlog",
"?",
"options",
".",
"backlog",
":",
"5",
";",
"bindings",
".",
"zsocket",
"(",
"options",
".",
"zone",
",",
"options",
".",
"path",
",",
"backlog",
",",
"callback",
")",
";",
"}"
]
| Creates a Unix Domain Socket in the specified Zone, and returns a node.js
Socket object, suitable for use in a net server.
Zone must _not_ be the global zone, and the zone must be running.
@param {Object} options an object containg the following parameters:
- zone {String} name of the zone in which to create UDS
- path {String} Path under which to create UDS
- backlog {Integer} OPTIONAL: listen backlog (default=5)
@param {Function} callback of form function(error, fd). fd is an int.
@throws {Error} any number of reasons...
@return {Undefined} | [
"Creates",
"a",
"Unix",
"Domain",
"Socket",
"in",
"the",
"specified",
"Zone",
"and",
"returns",
"a",
"node",
".",
"js",
"Socket",
"object",
"suitable",
"for",
"use",
"in",
"a",
"net",
"server",
"."
]
| ca821b9b2af80336b663a67d9a0aa8a8cb584341 | https://github.com/joyent/node-zsock/blob/ca821b9b2af80336b663a67d9a0aa8a8cb584341/lib/zsock.js#L40-L54 |
40,481 | right-track/right-track-core | modules/query/StopTimesTable.js | getStopTimeByTripStop | function getStopTimeByTripStop(db, tripId, stopId, date, callback) {
// Cache Cache for StopTimes
let cacheKey = db.id + "-" + tripId + "-" + stopId + "-" + date;
let cache = cache_stoptimesByTripStop.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build the select statement
let select = "SELECT " +
"gtfs_stop_times.arrival_time, departure_time, stop_sequence, pickup_type, drop_off_type, stop_headsign, shape_dist_traveled, timepoint, " +
"gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, " +
"gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, " +
"rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id " +
"FROM gtfs_stop_times " +
"INNER JOIN gtfs_stops ON gtfs_stop_times.stop_id=gtfs_stops.stop_id " +
"INNER JOIN rt_stops_extra ON gtfs_stops.stop_id=rt_stops_extra.stop_id " +
"WHERE gtfs_stop_times.trip_id='" + tripId + "' " +
"AND gtfs_stop_times.stop_id='" + stopId + "';";
// Query the database
db.get(select, function(err, result) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Stop Not Found
if ( result === undefined ) {
return callback(null, undefined);
}
// Use the stop_name by default unless display_name is set
let stop_name = result.stop_name;
if ( result.display_name !== undefined && result.display_name !== null && result.display_name !== "" ) {
stop_name = result.display_name;
}
// Get zone_id from rt_stops_extra if not defined if gtfs_stops
let zone_id = result.gtfs_zone_id;
if ( zone_id === null || zone_id === undefined ) {
zone_id = result.rt_zone_id;
}
// Build Stop
let stop = new Stop(
result.stop_id,
stop_name,
result.stop_lat,
result.stop_lon,
{
code: result.stop_code,
description: result.stop_desc,
zoneId: zone_id,
url: result.stop_url,
locationType: result.location_type,
parentStation: result.parent_station,
timezone: result.stop_timezone,
wheelchairBoarding: result.wheelchair_boarding,
statusId: result.status_id,
transferWeight: result.transfer_weight
}
);
// Build StopTime
let stopTime = new StopTime(
stop,
result.arrival_time,
result.departure_time,
result.stop_sequence,
{
headsign: result.stop_headsign,
pickupType: result.pickup_type,
dropOffType: result.drop_off_type,
shapeDistanceTraveled: result.shape_dist_traveled,
timepoint: result.timepoint,
date: date
}
);
// Add StopTimes to Cache
cache_stoptimesByTripStop.put(cacheKey, stopTime);
// Return the StopTimes with the callback
return callback(null, stopTime);
});
} | javascript | function getStopTimeByTripStop(db, tripId, stopId, date, callback) {
// Cache Cache for StopTimes
let cacheKey = db.id + "-" + tripId + "-" + stopId + "-" + date;
let cache = cache_stoptimesByTripStop.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Build the select statement
let select = "SELECT " +
"gtfs_stop_times.arrival_time, departure_time, stop_sequence, pickup_type, drop_off_type, stop_headsign, shape_dist_traveled, timepoint, " +
"gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, " +
"gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, " +
"rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id " +
"FROM gtfs_stop_times " +
"INNER JOIN gtfs_stops ON gtfs_stop_times.stop_id=gtfs_stops.stop_id " +
"INNER JOIN rt_stops_extra ON gtfs_stops.stop_id=rt_stops_extra.stop_id " +
"WHERE gtfs_stop_times.trip_id='" + tripId + "' " +
"AND gtfs_stop_times.stop_id='" + stopId + "';";
// Query the database
db.get(select, function(err, result) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Stop Not Found
if ( result === undefined ) {
return callback(null, undefined);
}
// Use the stop_name by default unless display_name is set
let stop_name = result.stop_name;
if ( result.display_name !== undefined && result.display_name !== null && result.display_name !== "" ) {
stop_name = result.display_name;
}
// Get zone_id from rt_stops_extra if not defined if gtfs_stops
let zone_id = result.gtfs_zone_id;
if ( zone_id === null || zone_id === undefined ) {
zone_id = result.rt_zone_id;
}
// Build Stop
let stop = new Stop(
result.stop_id,
stop_name,
result.stop_lat,
result.stop_lon,
{
code: result.stop_code,
description: result.stop_desc,
zoneId: zone_id,
url: result.stop_url,
locationType: result.location_type,
parentStation: result.parent_station,
timezone: result.stop_timezone,
wheelchairBoarding: result.wheelchair_boarding,
statusId: result.status_id,
transferWeight: result.transfer_weight
}
);
// Build StopTime
let stopTime = new StopTime(
stop,
result.arrival_time,
result.departure_time,
result.stop_sequence,
{
headsign: result.stop_headsign,
pickupType: result.pickup_type,
dropOffType: result.drop_off_type,
shapeDistanceTraveled: result.shape_dist_traveled,
timepoint: result.timepoint,
date: date
}
);
// Add StopTimes to Cache
cache_stoptimesByTripStop.put(cacheKey, stopTime);
// Return the StopTimes with the callback
return callback(null, stopTime);
});
} | [
"function",
"getStopTimeByTripStop",
"(",
"db",
",",
"tripId",
",",
"stopId",
",",
"date",
",",
"callback",
")",
"{",
"// Cache Cache for StopTimes",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"tripId",
"+",
"\"-\"",
"+",
"stopId",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_stoptimesByTripStop",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Build the select statement",
"let",
"select",
"=",
"\"SELECT \"",
"+",
"\"gtfs_stop_times.arrival_time, departure_time, stop_sequence, pickup_type, drop_off_type, stop_headsign, shape_dist_traveled, timepoint, \"",
"+",
"\"gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, \"",
"+",
"\"gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, \"",
"+",
"\"rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id \"",
"+",
"\"FROM gtfs_stop_times \"",
"+",
"\"INNER JOIN gtfs_stops ON gtfs_stop_times.stop_id=gtfs_stops.stop_id \"",
"+",
"\"INNER JOIN rt_stops_extra ON gtfs_stops.stop_id=rt_stops_extra.stop_id \"",
"+",
"\"WHERE gtfs_stop_times.trip_id='\"",
"+",
"tripId",
"+",
"\"' \"",
"+",
"\"AND gtfs_stop_times.stop_id='\"",
"+",
"stopId",
"+",
"\"';\"",
";",
"// Query the database",
"db",
".",
"get",
"(",
"select",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Stop Not Found",
"if",
"(",
"result",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"// Use the stop_name by default unless display_name is set",
"let",
"stop_name",
"=",
"result",
".",
"stop_name",
";",
"if",
"(",
"result",
".",
"display_name",
"!==",
"undefined",
"&&",
"result",
".",
"display_name",
"!==",
"null",
"&&",
"result",
".",
"display_name",
"!==",
"\"\"",
")",
"{",
"stop_name",
"=",
"result",
".",
"display_name",
";",
"}",
"// Get zone_id from rt_stops_extra if not defined if gtfs_stops",
"let",
"zone_id",
"=",
"result",
".",
"gtfs_zone_id",
";",
"if",
"(",
"zone_id",
"===",
"null",
"||",
"zone_id",
"===",
"undefined",
")",
"{",
"zone_id",
"=",
"result",
".",
"rt_zone_id",
";",
"}",
"// Build Stop",
"let",
"stop",
"=",
"new",
"Stop",
"(",
"result",
".",
"stop_id",
",",
"stop_name",
",",
"result",
".",
"stop_lat",
",",
"result",
".",
"stop_lon",
",",
"{",
"code",
":",
"result",
".",
"stop_code",
",",
"description",
":",
"result",
".",
"stop_desc",
",",
"zoneId",
":",
"zone_id",
",",
"url",
":",
"result",
".",
"stop_url",
",",
"locationType",
":",
"result",
".",
"location_type",
",",
"parentStation",
":",
"result",
".",
"parent_station",
",",
"timezone",
":",
"result",
".",
"stop_timezone",
",",
"wheelchairBoarding",
":",
"result",
".",
"wheelchair_boarding",
",",
"statusId",
":",
"result",
".",
"status_id",
",",
"transferWeight",
":",
"result",
".",
"transfer_weight",
"}",
")",
";",
"// Build StopTime",
"let",
"stopTime",
"=",
"new",
"StopTime",
"(",
"stop",
",",
"result",
".",
"arrival_time",
",",
"result",
".",
"departure_time",
",",
"result",
".",
"stop_sequence",
",",
"{",
"headsign",
":",
"result",
".",
"stop_headsign",
",",
"pickupType",
":",
"result",
".",
"pickup_type",
",",
"dropOffType",
":",
"result",
".",
"drop_off_type",
",",
"shapeDistanceTraveled",
":",
"result",
".",
"shape_dist_traveled",
",",
"timepoint",
":",
"result",
".",
"timepoint",
",",
"date",
":",
"date",
"}",
")",
";",
"// Add StopTimes to Cache",
"cache_stoptimesByTripStop",
".",
"put",
"(",
"cacheKey",
",",
"stopTime",
")",
";",
"// Return the StopTimes with the callback",
"return",
"callback",
"(",
"null",
",",
"stopTime",
")",
";",
"}",
")",
";",
"}"
]
| Get the StopTime for the specified Trip and the
specified Stop from the passed database
@param {RightTrackDB} db The Right Track DB to query
@param {string} tripId Trip ID
@param {string} stopId Stop ID
@param {int} date The date (yyyymmdd) the the Trip operates on
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {StopTime} [callback.stoptime] The selected StopTime | [
"Get",
"the",
"StopTime",
"for",
"the",
"specified",
"Trip",
"and",
"the",
"specified",
"Stop",
"from",
"the",
"passed",
"database"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/StopTimesTable.js#L140-L230 |
40,482 | right-track/right-track-core | modules/query/TripsTable.js | getTripByShortName | function getTripByShortName(db, shortName, date, callback) {
// Check Cache for Trip
let cacheKey = db.id + "-" + shortName + "-" + date;
let cache = cache_tripsByShortName.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Get effective service ids
_buildEffectiveServiceIDString(db, date, function(err, serviceIdString) {
if ( err ) {
return callback(err);
}
// Get Trip ID
let select = "SELECT trip_id FROM gtfs_trips WHERE trip_short_name = '" +
shortName + "' AND service_id IN " + serviceIdString + ";";
// Query database
db.get(select, function(err, result) {
if ( err ) {
return callback(err);
}
// No Trip Found
if ( result === undefined ) {
return callback(null, undefined);
}
// Get the Trip
getTrip(db, result.trip_id, date, function(err, trip) {
// Add Trip to Cache
cache_tripsByShortName.put(cacheKey, trip);
// Return Trip
return callback(err, trip);
});
});
});
} | javascript | function getTripByShortName(db, shortName, date, callback) {
// Check Cache for Trip
let cacheKey = db.id + "-" + shortName + "-" + date;
let cache = cache_tripsByShortName.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Get effective service ids
_buildEffectiveServiceIDString(db, date, function(err, serviceIdString) {
if ( err ) {
return callback(err);
}
// Get Trip ID
let select = "SELECT trip_id FROM gtfs_trips WHERE trip_short_name = '" +
shortName + "' AND service_id IN " + serviceIdString + ";";
// Query database
db.get(select, function(err, result) {
if ( err ) {
return callback(err);
}
// No Trip Found
if ( result === undefined ) {
return callback(null, undefined);
}
// Get the Trip
getTrip(db, result.trip_id, date, function(err, trip) {
// Add Trip to Cache
cache_tripsByShortName.put(cacheKey, trip);
// Return Trip
return callback(err, trip);
});
});
});
} | [
"function",
"getTripByShortName",
"(",
"db",
",",
"shortName",
",",
"date",
",",
"callback",
")",
"{",
"// Check Cache for Trip",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"shortName",
"+",
"\"-\"",
"+",
"date",
";",
"let",
"cache",
"=",
"cache_tripsByShortName",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Get effective service ids",
"_buildEffectiveServiceIDString",
"(",
"db",
",",
"date",
",",
"function",
"(",
"err",
",",
"serviceIdString",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Get Trip ID",
"let",
"select",
"=",
"\"SELECT trip_id FROM gtfs_trips WHERE trip_short_name = '\"",
"+",
"shortName",
"+",
"\"' AND service_id IN \"",
"+",
"serviceIdString",
"+",
"\";\"",
";",
"// Query database",
"db",
".",
"get",
"(",
"select",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// No Trip Found",
"if",
"(",
"result",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"// Get the Trip",
"getTrip",
"(",
"db",
",",
"result",
".",
"trip_id",
",",
"date",
",",
"function",
"(",
"err",
",",
"trip",
")",
"{",
"// Add Trip to Cache",
"cache_tripsByShortName",
".",
"put",
"(",
"cacheKey",
",",
"trip",
")",
";",
"// Return Trip",
"return",
"callback",
"(",
"err",
",",
"trip",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Get the Trip specified by the Trip short name that operates on the specified date
@param {RightTrackDB} db The Right Track DB to query
@param {string} shortName Trip short name
@param {int} date Date Integer (yyyymmdd)
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Trip} [callback.trip] The selected Trip | [
"Get",
"the",
"Trip",
"specified",
"by",
"the",
"Trip",
"short",
"name",
"that",
"operates",
"on",
"the",
"specified",
"date"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L247-L292 |
40,483 | right-track/right-track-core | modules/query/TripsTable.js | getTripByDeparture | function getTripByDeparture(db, originId, destinationId, departure, callback) {
// Check cache for trip
let cacheKey = db.id + "-" + originId + "-" + destinationId + "-" + departure.getTimeSeconds() + "-" + departure.getDateInt();
let cache = cache_tripsByDeparture.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Check to make sure both origin and destination have IDs set
if ( originId === "" || originId === undefined ||
destinationId === "" || destinationId === undefined ) {
return callback(
new Error('Could not get Trip, origin and/or destination id not set')
);
}
// ORIGINAL DEPARTURE DATE
_getTripByDeparture(db, originId, destinationId, departure, function(err, trip) {
if ( err ) {
return callback(err);
}
// Trip Found...
if ( trip !== undefined ) {
cache_tripsByDeparture.put(cacheKey, trip);
return callback(null, trip);
}
// PREVIOUS DEPARTURE DATE, +24 HOUR TIME
let prev = DateTime.create(
departure.getTimeSeconds() + 86400,
departure.clone().deltaDays(-1).getDateInt()
);
_getTripByDeparture(db, originId, destinationId, prev, function(err, trip) {
// Return results
cache_tripsByDeparture.put(cacheKey, trip);
return callback(err, trip);
});
});
} | javascript | function getTripByDeparture(db, originId, destinationId, departure, callback) {
// Check cache for trip
let cacheKey = db.id + "-" + originId + "-" + destinationId + "-" + departure.getTimeSeconds() + "-" + departure.getDateInt();
let cache = cache_tripsByDeparture.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// Check to make sure both origin and destination have IDs set
if ( originId === "" || originId === undefined ||
destinationId === "" || destinationId === undefined ) {
return callback(
new Error('Could not get Trip, origin and/or destination id not set')
);
}
// ORIGINAL DEPARTURE DATE
_getTripByDeparture(db, originId, destinationId, departure, function(err, trip) {
if ( err ) {
return callback(err);
}
// Trip Found...
if ( trip !== undefined ) {
cache_tripsByDeparture.put(cacheKey, trip);
return callback(null, trip);
}
// PREVIOUS DEPARTURE DATE, +24 HOUR TIME
let prev = DateTime.create(
departure.getTimeSeconds() + 86400,
departure.clone().deltaDays(-1).getDateInt()
);
_getTripByDeparture(db, originId, destinationId, prev, function(err, trip) {
// Return results
cache_tripsByDeparture.put(cacheKey, trip);
return callback(err, trip);
});
});
} | [
"function",
"getTripByDeparture",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"departure",
",",
"callback",
")",
"{",
"// Check cache for trip",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"originId",
"+",
"\"-\"",
"+",
"destinationId",
"+",
"\"-\"",
"+",
"departure",
".",
"getTimeSeconds",
"(",
")",
"+",
"\"-\"",
"+",
"departure",
".",
"getDateInt",
"(",
")",
";",
"let",
"cache",
"=",
"cache_tripsByDeparture",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// Check to make sure both origin and destination have IDs set",
"if",
"(",
"originId",
"===",
"\"\"",
"||",
"originId",
"===",
"undefined",
"||",
"destinationId",
"===",
"\"\"",
"||",
"destinationId",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Could not get Trip, origin and/or destination id not set'",
")",
")",
";",
"}",
"// ORIGINAL DEPARTURE DATE",
"_getTripByDeparture",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"departure",
",",
"function",
"(",
"err",
",",
"trip",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Trip Found...",
"if",
"(",
"trip",
"!==",
"undefined",
")",
"{",
"cache_tripsByDeparture",
".",
"put",
"(",
"cacheKey",
",",
"trip",
")",
";",
"return",
"callback",
"(",
"null",
",",
"trip",
")",
";",
"}",
"// PREVIOUS DEPARTURE DATE, +24 HOUR TIME",
"let",
"prev",
"=",
"DateTime",
".",
"create",
"(",
"departure",
".",
"getTimeSeconds",
"(",
")",
"+",
"86400",
",",
"departure",
".",
"clone",
"(",
")",
".",
"deltaDays",
"(",
"-",
"1",
")",
".",
"getDateInt",
"(",
")",
")",
";",
"_getTripByDeparture",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"prev",
",",
"function",
"(",
"err",
",",
"trip",
")",
"{",
"// Return results",
"cache_tripsByDeparture",
".",
"put",
"(",
"cacheKey",
",",
"trip",
")",
";",
"return",
"callback",
"(",
"err",
",",
"trip",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Find the Trip that leaves the specified origin Stop for the specified
destination Stop at the departure time specified by the DateTime
@param {RightTrackDB} db The Right Track DB to query
@param {string} originId Origin Stop ID
@param {string} destinationId Destination Stop ID
@param {DateTime} departure DateTime of trip departure
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Trip} [callback.trip] The selected Trip | [
"Find",
"the",
"Trip",
"that",
"leaves",
"the",
"specified",
"origin",
"Stop",
"for",
"the",
"specified",
"destination",
"Stop",
"at",
"the",
"departure",
"time",
"specified",
"by",
"the",
"DateTime"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L306-L354 |
40,484 | right-track/right-track-core | modules/query/TripsTable.js | _getTripByDeparture | function _getTripByDeparture(db, originId, destinationId, departure, callback) {
// Get Effective Services for departure date
_buildEffectiveServiceIDString(db, departure.getDateInt(), function(err, serviceIdString) {
if ( err ) {
return callback(err);
}
// Find a matching trip
_getMatchingTripId(db, originId, destinationId, departure, serviceIdString, function(err, tripId) {
if ( err ) {
return callback(err);
}
// --> No matching trip found
if ( tripId === undefined ) {
return callback(null, undefined);
}
// Build the matching trip...
getTrip(db, tripId, departure.getDateInt(), function(err, trip) {
if ( err ) {
return callback(err);
}
// --> Return the matching trip
return callback(err, trip);
});
});
});
} | javascript | function _getTripByDeparture(db, originId, destinationId, departure, callback) {
// Get Effective Services for departure date
_buildEffectiveServiceIDString(db, departure.getDateInt(), function(err, serviceIdString) {
if ( err ) {
return callback(err);
}
// Find a matching trip
_getMatchingTripId(db, originId, destinationId, departure, serviceIdString, function(err, tripId) {
if ( err ) {
return callback(err);
}
// --> No matching trip found
if ( tripId === undefined ) {
return callback(null, undefined);
}
// Build the matching trip...
getTrip(db, tripId, departure.getDateInt(), function(err, trip) {
if ( err ) {
return callback(err);
}
// --> Return the matching trip
return callback(err, trip);
});
});
});
} | [
"function",
"_getTripByDeparture",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"departure",
",",
"callback",
")",
"{",
"// Get Effective Services for departure date",
"_buildEffectiveServiceIDString",
"(",
"db",
",",
"departure",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"err",
",",
"serviceIdString",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Find a matching trip",
"_getMatchingTripId",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"departure",
",",
"serviceIdString",
",",
"function",
"(",
"err",
",",
"tripId",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// --> No matching trip found",
"if",
"(",
"tripId",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"// Build the matching trip...",
"getTrip",
"(",
"db",
",",
"tripId",
",",
"departure",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"err",
",",
"trip",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// --> Return the matching trip",
"return",
"callback",
"(",
"err",
",",
"trip",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Get the Trip that matches the origin, destination and departure information
@param {RightTrackDB} db The Right Track DB to query
@param {string} originId Origin Stop ID
@param {string} destinationId Destination Stop ID
@param {DateTime} departure Departure DateTime
@param {function} callback getTrip callback function(err, trip)
@private | [
"Get",
"the",
"Trip",
"that",
"matches",
"the",
"origin",
"destination",
"and",
"departure",
"information"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L365-L399 |
40,485 | right-track/right-track-core | modules/query/TripsTable.js | _buildEffectiveServiceIDString | function _buildEffectiveServiceIDString(db, date, callback) {
// Query the Calendar for effective services
CalendarTable.getServicesEffective(db, date, function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Build Service ID String
let serviceIds = [];
for ( let i = 0; i < services.length; i++ ) {
serviceIds.push(services[i].id);
}
let serviceIdString = "('" + serviceIds.join("', '") + "')";
// Return Service ID String
return callback(null, serviceIdString);
});
} | javascript | function _buildEffectiveServiceIDString(db, date, callback) {
// Query the Calendar for effective services
CalendarTable.getServicesEffective(db, date, function(err, services) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Build Service ID String
let serviceIds = [];
for ( let i = 0; i < services.length; i++ ) {
serviceIds.push(services[i].id);
}
let serviceIdString = "('" + serviceIds.join("', '") + "')";
// Return Service ID String
return callback(null, serviceIdString);
});
} | [
"function",
"_buildEffectiveServiceIDString",
"(",
"db",
",",
"date",
",",
"callback",
")",
"{",
"// Query the Calendar for effective services",
"CalendarTable",
".",
"getServicesEffective",
"(",
"db",
",",
"date",
",",
"function",
"(",
"err",
",",
"services",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Build Service ID String",
"let",
"serviceIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"services",
".",
"length",
";",
"i",
"++",
")",
"{",
"serviceIds",
".",
"push",
"(",
"services",
"[",
"i",
"]",
".",
"id",
")",
";",
"}",
"let",
"serviceIdString",
"=",
"\"('\"",
"+",
"serviceIds",
".",
"join",
"(",
"\"', '\"",
")",
"+",
"\"')\"",
";",
"// Return Service ID String",
"return",
"callback",
"(",
"null",
",",
"serviceIdString",
")",
";",
"}",
")",
";",
"}"
]
| Build the Effective Service ID String for SELECT query
@param {RightTrackDB} db The Right Track DB to query
@param {int} date Date Integer (yyyymmdd)
@param {function} callback Callback function(err, serviceIdString)
@private | [
"Build",
"the",
"Effective",
"Service",
"ID",
"String",
"for",
"SELECT",
"query"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L408-L430 |
40,486 | right-track/right-track-core | modules/query/TripsTable.js | _getMatchingTripId | function _getMatchingTripId(db, originId, destinationId, departure, serviceIdString, callback) {
// Find a matching trip in the gtfs_stop_times table
let select = "SELECT trip_id FROM gtfs_trips " +
"WHERE service_id IN " + serviceIdString + " " +
"AND trip_id IN (" +
"SELECT trip_id FROM gtfs_stop_times WHERE stop_id='" + destinationId + "' " +
"AND trip_id IN (" +
"SELECT trip_id FROM gtfs_stop_times " +
"WHERE stop_id='" + originId + "' AND departure_time_seconds=" + departure.getTimeSeconds() +
"));";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// No results found
if ( results.length === 0 ) {
return callback(null, undefined);
}
// Find the best match
let found = false;
let count = 0;
for ( let j = 0; j < results.length; j++ ) {
let row = results[j];
// Get StopTimes for origin and destination
StopTimesTable.getStopTimeByTripStop(db, row.trip_id, originId, departure.getDateInt(), function(orErr, originStopTime) {
StopTimesTable.getStopTimeByTripStop(db, row.trip_id, destinationId, departure.getDateInt(), function(deErr, destinationStopTime) {
if ( orErr ) {
return callback(orErr);
}
if ( deErr ) {
return callback(deErr);
}
// Check stop sequence
// If origin comes before destination, use that trip
if ( originStopTime.stopSequence <= destinationStopTime.stopSequence ) {
found = true;
return callback(null, row.trip_id);
}
// No match found
count ++;
if ( !found && count === results.length ) {
return callback(null, undefined);
}
});
});
}
});
} | javascript | function _getMatchingTripId(db, originId, destinationId, departure, serviceIdString, callback) {
// Find a matching trip in the gtfs_stop_times table
let select = "SELECT trip_id FROM gtfs_trips " +
"WHERE service_id IN " + serviceIdString + " " +
"AND trip_id IN (" +
"SELECT trip_id FROM gtfs_stop_times WHERE stop_id='" + destinationId + "' " +
"AND trip_id IN (" +
"SELECT trip_id FROM gtfs_stop_times " +
"WHERE stop_id='" + originId + "' AND departure_time_seconds=" + departure.getTimeSeconds() +
"));";
// Query the database
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// No results found
if ( results.length === 0 ) {
return callback(null, undefined);
}
// Find the best match
let found = false;
let count = 0;
for ( let j = 0; j < results.length; j++ ) {
let row = results[j];
// Get StopTimes for origin and destination
StopTimesTable.getStopTimeByTripStop(db, row.trip_id, originId, departure.getDateInt(), function(orErr, originStopTime) {
StopTimesTable.getStopTimeByTripStop(db, row.trip_id, destinationId, departure.getDateInt(), function(deErr, destinationStopTime) {
if ( orErr ) {
return callback(orErr);
}
if ( deErr ) {
return callback(deErr);
}
// Check stop sequence
// If origin comes before destination, use that trip
if ( originStopTime.stopSequence <= destinationStopTime.stopSequence ) {
found = true;
return callback(null, row.trip_id);
}
// No match found
count ++;
if ( !found && count === results.length ) {
return callback(null, undefined);
}
});
});
}
});
} | [
"function",
"_getMatchingTripId",
"(",
"db",
",",
"originId",
",",
"destinationId",
",",
"departure",
",",
"serviceIdString",
",",
"callback",
")",
"{",
"// Find a matching trip in the gtfs_stop_times table",
"let",
"select",
"=",
"\"SELECT trip_id FROM gtfs_trips \"",
"+",
"\"WHERE service_id IN \"",
"+",
"serviceIdString",
"+",
"\" \"",
"+",
"\"AND trip_id IN (\"",
"+",
"\"SELECT trip_id FROM gtfs_stop_times WHERE stop_id='\"",
"+",
"destinationId",
"+",
"\"' \"",
"+",
"\"AND trip_id IN (\"",
"+",
"\"SELECT trip_id FROM gtfs_stop_times \"",
"+",
"\"WHERE stop_id='\"",
"+",
"originId",
"+",
"\"' AND departure_time_seconds=\"",
"+",
"departure",
".",
"getTimeSeconds",
"(",
")",
"+",
"\"));\"",
";",
"// Query the database",
"db",
".",
"select",
"(",
"select",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// No results found",
"if",
"(",
"results",
".",
"length",
"===",
"0",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"// Find the best match",
"let",
"found",
"=",
"false",
";",
"let",
"count",
"=",
"0",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"results",
".",
"length",
";",
"j",
"++",
")",
"{",
"let",
"row",
"=",
"results",
"[",
"j",
"]",
";",
"// Get StopTimes for origin and destination",
"StopTimesTable",
".",
"getStopTimeByTripStop",
"(",
"db",
",",
"row",
".",
"trip_id",
",",
"originId",
",",
"departure",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"orErr",
",",
"originStopTime",
")",
"{",
"StopTimesTable",
".",
"getStopTimeByTripStop",
"(",
"db",
",",
"row",
".",
"trip_id",
",",
"destinationId",
",",
"departure",
".",
"getDateInt",
"(",
")",
",",
"function",
"(",
"deErr",
",",
"destinationStopTime",
")",
"{",
"if",
"(",
"orErr",
")",
"{",
"return",
"callback",
"(",
"orErr",
")",
";",
"}",
"if",
"(",
"deErr",
")",
"{",
"return",
"callback",
"(",
"deErr",
")",
";",
"}",
"// Check stop sequence",
"// If origin comes before destination, use that trip",
"if",
"(",
"originStopTime",
".",
"stopSequence",
"<=",
"destinationStopTime",
".",
"stopSequence",
")",
"{",
"found",
"=",
"true",
";",
"return",
"callback",
"(",
"null",
",",
"row",
".",
"trip_id",
")",
";",
"}",
"// No match found",
"count",
"++",
";",
"if",
"(",
"!",
"found",
"&&",
"count",
"===",
"results",
".",
"length",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Get the Trip ID of the trip matching the origin, destination, and departure information
@param {RightTrackDB} db The Right Track DB to query
@param {string} originId Origin Stop ID
@param {string} destinationId Destination Stop ID
@param {DateTime} departure DateTime of departure
@param {string} serviceIdString Effective Service ID string
@param {function} callback Callback function(err, tripId)
@private | [
"Get",
"the",
"Trip",
"ID",
"of",
"the",
"trip",
"matching",
"the",
"origin",
"destination",
"and",
"departure",
"information"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L442-L503 |
40,487 | right-track/right-track-core | modules/query/TripsTable.js | getTripsByDate | function getTripsByDate(db, date, opts, callback) {
// Parse Args
if ( callback === undefined && typeof opts === 'function' ) {
callback = opts;
opts = {}
}
// Check cache for trips
let cacheKey = db.id + "-" + date + "-" + opts.routeId + "-" + opts.stopId;
let cache = cache_tripsByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// List of Trips to return
let rtn = [];
// Counters
let done = 0;
let count = 0;
// Get the Effective Service IDs
_buildEffectiveServiceIDString(db, date, function(err, serviceIdString) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Build Select Statement
let select = "";
// Get Trips By Stop
if ( opts.stopId !== undefined ) {
select = select + "SELECT trip_id FROM gtfs_stop_times WHERE stop_id='" + opts.stopId + "' AND trip_id IN (";
}
// Get Trips By Date
select = select + "SELECT DISTINCT trip_id FROM gtfs_trips WHERE service_id IN " + serviceIdString;
// Filter By Route, if provided
if ( opts.routeId !== undefined ) {
select = select + " AND route_id='" + opts.routeId + "'";
}
// Close Outer Select
if ( opts.stopId !== undefined ) {
select = select + ")";
}
// Query the DB
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Set the counter
count = results.length;
// No Stops Found
if ( results.length === 0 ) {
_finish();
}
// Build the Trips
for ( let i = 0; i < results.length; i++ ) {
getTrip(db, results[i].trip_id, date, function(err, trip) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add reference stop, if provided
if ( opts.stopId ) {
trip._referenceStopId = opts.stopId;
}
// Add Trip to Result
rtn.push(trip);
// Finish
_finish();
});
}
});
});
/**
* Finish Parsing Trip
* @private
*/
function _finish() {
done++;
if ( count === 0 || done === count ) {
rtn.sort(Trip.sortByDepartureTime);
return callback(null, rtn);
}
}
} | javascript | function getTripsByDate(db, date, opts, callback) {
// Parse Args
if ( callback === undefined && typeof opts === 'function' ) {
callback = opts;
opts = {}
}
// Check cache for trips
let cacheKey = db.id + "-" + date + "-" + opts.routeId + "-" + opts.stopId;
let cache = cache_tripsByDate.get(cacheKey);
if ( cache !== null ) {
return callback(null, cache);
}
// List of Trips to return
let rtn = [];
// Counters
let done = 0;
let count = 0;
// Get the Effective Service IDs
_buildEffectiveServiceIDString(db, date, function(err, serviceIdString) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Build Select Statement
let select = "";
// Get Trips By Stop
if ( opts.stopId !== undefined ) {
select = select + "SELECT trip_id FROM gtfs_stop_times WHERE stop_id='" + opts.stopId + "' AND trip_id IN (";
}
// Get Trips By Date
select = select + "SELECT DISTINCT trip_id FROM gtfs_trips WHERE service_id IN " + serviceIdString;
// Filter By Route, if provided
if ( opts.routeId !== undefined ) {
select = select + " AND route_id='" + opts.routeId + "'";
}
// Close Outer Select
if ( opts.stopId !== undefined ) {
select = select + ")";
}
// Query the DB
db.select(select, function(err, results) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Set the counter
count = results.length;
// No Stops Found
if ( results.length === 0 ) {
_finish();
}
// Build the Trips
for ( let i = 0; i < results.length; i++ ) {
getTrip(db, results[i].trip_id, date, function(err, trip) {
// Database Query Error
if ( err ) {
return callback(err);
}
// Add reference stop, if provided
if ( opts.stopId ) {
trip._referenceStopId = opts.stopId;
}
// Add Trip to Result
rtn.push(trip);
// Finish
_finish();
});
}
});
});
/**
* Finish Parsing Trip
* @private
*/
function _finish() {
done++;
if ( count === 0 || done === count ) {
rtn.sort(Trip.sortByDepartureTime);
return callback(null, rtn);
}
}
} | [
"function",
"getTripsByDate",
"(",
"db",
",",
"date",
",",
"opts",
",",
"callback",
")",
"{",
"// Parse Args",
"if",
"(",
"callback",
"===",
"undefined",
"&&",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"callback",
"=",
"opts",
";",
"opts",
"=",
"{",
"}",
"}",
"// Check cache for trips",
"let",
"cacheKey",
"=",
"db",
".",
"id",
"+",
"\"-\"",
"+",
"date",
"+",
"\"-\"",
"+",
"opts",
".",
"routeId",
"+",
"\"-\"",
"+",
"opts",
".",
"stopId",
";",
"let",
"cache",
"=",
"cache_tripsByDate",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"cache",
"!==",
"null",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"cache",
")",
";",
"}",
"// List of Trips to return",
"let",
"rtn",
"=",
"[",
"]",
";",
"// Counters",
"let",
"done",
"=",
"0",
";",
"let",
"count",
"=",
"0",
";",
"// Get the Effective Service IDs",
"_buildEffectiveServiceIDString",
"(",
"db",
",",
"date",
",",
"function",
"(",
"err",
",",
"serviceIdString",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Build Select Statement",
"let",
"select",
"=",
"\"\"",
";",
"// Get Trips By Stop",
"if",
"(",
"opts",
".",
"stopId",
"!==",
"undefined",
")",
"{",
"select",
"=",
"select",
"+",
"\"SELECT trip_id FROM gtfs_stop_times WHERE stop_id='\"",
"+",
"opts",
".",
"stopId",
"+",
"\"' AND trip_id IN (\"",
";",
"}",
"// Get Trips By Date",
"select",
"=",
"select",
"+",
"\"SELECT DISTINCT trip_id FROM gtfs_trips WHERE service_id IN \"",
"+",
"serviceIdString",
";",
"// Filter By Route, if provided",
"if",
"(",
"opts",
".",
"routeId",
"!==",
"undefined",
")",
"{",
"select",
"=",
"select",
"+",
"\" AND route_id='\"",
"+",
"opts",
".",
"routeId",
"+",
"\"'\"",
";",
"}",
"// Close Outer Select",
"if",
"(",
"opts",
".",
"stopId",
"!==",
"undefined",
")",
"{",
"select",
"=",
"select",
"+",
"\")\"",
";",
"}",
"// Query the DB",
"db",
".",
"select",
"(",
"select",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Set the counter",
"count",
"=",
"results",
".",
"length",
";",
"// No Stops Found",
"if",
"(",
"results",
".",
"length",
"===",
"0",
")",
"{",
"_finish",
"(",
")",
";",
"}",
"// Build the Trips",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"getTrip",
"(",
"db",
",",
"results",
"[",
"i",
"]",
".",
"trip_id",
",",
"date",
",",
"function",
"(",
"err",
",",
"trip",
")",
"{",
"// Database Query Error",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Add reference stop, if provided",
"if",
"(",
"opts",
".",
"stopId",
")",
"{",
"trip",
".",
"_referenceStopId",
"=",
"opts",
".",
"stopId",
";",
"}",
"// Add Trip to Result",
"rtn",
".",
"push",
"(",
"trip",
")",
";",
"// Finish",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"/**\n * Finish Parsing Trip\n * @private\n */",
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"count",
"===",
"0",
"||",
"done",
"===",
"count",
")",
"{",
"rtn",
".",
"sort",
"(",
"Trip",
".",
"sortByDepartureTime",
")",
";",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
"}",
"}"
]
| Get all Trips effectively running on the specified date
@param {RightTrackDB} db The Right Track DB to query
@param {int} date Date in YYYYMMDD format
@param {Object} [opts] Query Options
@param {string} [opts.routeId] GTFS Route ID - get Trips that run on this Route
@param {string} [opts.stopId] GTFS Stop ID - get Trips that stop at this Stop
@param {function} callback Callback function
@param {Error} callback.error Database Query Error
@param {Trip[]} [callback.trips] List of Trips | [
"Get",
"all",
"Trips",
"effectively",
"running",
"on",
"the",
"specified",
"date"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L517-L624 |
40,488 | right-track/right-track-core | modules/query/TripsTable.js | _finish | function _finish() {
done++;
if ( count === 0 || done === count ) {
rtn.sort(Trip.sortByDepartureTime);
return callback(null, rtn);
}
} | javascript | function _finish() {
done++;
if ( count === 0 || done === count ) {
rtn.sort(Trip.sortByDepartureTime);
return callback(null, rtn);
}
} | [
"function",
"_finish",
"(",
")",
"{",
"done",
"++",
";",
"if",
"(",
"count",
"===",
"0",
"||",
"done",
"===",
"count",
")",
"{",
"rtn",
".",
"sort",
"(",
"Trip",
".",
"sortByDepartureTime",
")",
";",
"return",
"callback",
"(",
"null",
",",
"rtn",
")",
";",
"}",
"}"
]
| Finish Parsing Trip
@private | [
"Finish",
"Parsing",
"Trip"
]
| 667c7718b9895067794980280e03d8c5e63b7e41 | https://github.com/right-track/right-track-core/blob/667c7718b9895067794980280e03d8c5e63b7e41/modules/query/TripsTable.js#L616-L622 |
40,489 | svgdotjs/svg.pathmorphing.js | dist/svg.pathmorphing.js | simplyfy | function simplyfy(val){
switch(val[0]){
case 'z': // shorthand line to start
case 'Z':
val[0] = 'L'
val[1] = this.start[0]
val[2] = this.start[1]
break
case 'H': // shorthand horizontal line
val[0] = 'L'
val[2] = this.pos[1]
break
case 'V': // shorthand vertical line
val[0] = 'L'
val[2] = val[1]
val[1] = this.pos[0]
break
case 'T': // shorthand quadratic beziere
val[0] = 'Q'
val[3] = val[1]
val[4] = val[2]
val[1] = this.reflection[1]
val[2] = this.reflection[0]
break
case 'S': // shorthand cubic beziere
val[0] = 'C'
val[6] = val[4]
val[5] = val[3]
val[4] = val[2]
val[3] = val[1]
val[2] = this.reflection[1]
val[1] = this.reflection[0]
break
}
return val
} | javascript | function simplyfy(val){
switch(val[0]){
case 'z': // shorthand line to start
case 'Z':
val[0] = 'L'
val[1] = this.start[0]
val[2] = this.start[1]
break
case 'H': // shorthand horizontal line
val[0] = 'L'
val[2] = this.pos[1]
break
case 'V': // shorthand vertical line
val[0] = 'L'
val[2] = val[1]
val[1] = this.pos[0]
break
case 'T': // shorthand quadratic beziere
val[0] = 'Q'
val[3] = val[1]
val[4] = val[2]
val[1] = this.reflection[1]
val[2] = this.reflection[0]
break
case 'S': // shorthand cubic beziere
val[0] = 'C'
val[6] = val[4]
val[5] = val[3]
val[4] = val[2]
val[3] = val[1]
val[2] = this.reflection[1]
val[1] = this.reflection[0]
break
}
return val
} | [
"function",
"simplyfy",
"(",
"val",
")",
"{",
"switch",
"(",
"val",
"[",
"0",
"]",
")",
"{",
"case",
"'z'",
":",
"// shorthand line to start",
"case",
"'Z'",
":",
"val",
"[",
"0",
"]",
"=",
"'L'",
"val",
"[",
"1",
"]",
"=",
"this",
".",
"start",
"[",
"0",
"]",
"val",
"[",
"2",
"]",
"=",
"this",
".",
"start",
"[",
"1",
"]",
"break",
"case",
"'H'",
":",
"// shorthand horizontal line",
"val",
"[",
"0",
"]",
"=",
"'L'",
"val",
"[",
"2",
"]",
"=",
"this",
".",
"pos",
"[",
"1",
"]",
"break",
"case",
"'V'",
":",
"// shorthand vertical line",
"val",
"[",
"0",
"]",
"=",
"'L'",
"val",
"[",
"2",
"]",
"=",
"val",
"[",
"1",
"]",
"val",
"[",
"1",
"]",
"=",
"this",
".",
"pos",
"[",
"0",
"]",
"break",
"case",
"'T'",
":",
"// shorthand quadratic beziere",
"val",
"[",
"0",
"]",
"=",
"'Q'",
"val",
"[",
"3",
"]",
"=",
"val",
"[",
"1",
"]",
"val",
"[",
"4",
"]",
"=",
"val",
"[",
"2",
"]",
"val",
"[",
"1",
"]",
"=",
"this",
".",
"reflection",
"[",
"1",
"]",
"val",
"[",
"2",
"]",
"=",
"this",
".",
"reflection",
"[",
"0",
"]",
"break",
"case",
"'S'",
":",
"// shorthand cubic beziere",
"val",
"[",
"0",
"]",
"=",
"'C'",
"val",
"[",
"6",
"]",
"=",
"val",
"[",
"4",
"]",
"val",
"[",
"5",
"]",
"=",
"val",
"[",
"3",
"]",
"val",
"[",
"4",
"]",
"=",
"val",
"[",
"2",
"]",
"val",
"[",
"3",
"]",
"=",
"val",
"[",
"1",
"]",
"val",
"[",
"2",
"]",
"=",
"this",
".",
"reflection",
"[",
"1",
"]",
"val",
"[",
"1",
"]",
"=",
"this",
".",
"reflection",
"[",
"0",
"]",
"break",
"}",
"return",
"val",
"}"
]
| converts shorthand types to long form | [
"converts",
"shorthand",
"types",
"to",
"long",
"form"
]
| 5cae2d7120fed801e47e216ab0286f44427c5f01 | https://github.com/svgdotjs/svg.pathmorphing.js/blob/5cae2d7120fed801e47e216ab0286f44427c5f01/dist/svg.pathmorphing.js#L156-L194 |
40,490 | svgdotjs/svg.pathmorphing.js | dist/svg.pathmorphing.js | setPosAndReflection | function setPosAndReflection(val){
var len = val.length
this.pos = [ val[len-2], val[len-1] ]
if('SCQT'.indexOf(val[0]) != -1)
this.reflection = [ 2 * this.pos[0] - val[len-4], 2 * this.pos[1] - val[len-3] ]
return val
} | javascript | function setPosAndReflection(val){
var len = val.length
this.pos = [ val[len-2], val[len-1] ]
if('SCQT'.indexOf(val[0]) != -1)
this.reflection = [ 2 * this.pos[0] - val[len-4], 2 * this.pos[1] - val[len-3] ]
return val
} | [
"function",
"setPosAndReflection",
"(",
"val",
")",
"{",
"var",
"len",
"=",
"val",
".",
"length",
"this",
".",
"pos",
"=",
"[",
"val",
"[",
"len",
"-",
"2",
"]",
",",
"val",
"[",
"len",
"-",
"1",
"]",
"]",
"if",
"(",
"'SCQT'",
".",
"indexOf",
"(",
"val",
"[",
"0",
"]",
")",
"!=",
"-",
"1",
")",
"this",
".",
"reflection",
"=",
"[",
"2",
"*",
"this",
".",
"pos",
"[",
"0",
"]",
"-",
"val",
"[",
"len",
"-",
"4",
"]",
",",
"2",
"*",
"this",
".",
"pos",
"[",
"1",
"]",
"-",
"val",
"[",
"len",
"-",
"3",
"]",
"]",
"return",
"val",
"}"
]
| updates reflection point and current position | [
"updates",
"reflection",
"point",
"and",
"current",
"position"
]
| 5cae2d7120fed801e47e216ab0286f44427c5f01 | https://github.com/svgdotjs/svg.pathmorphing.js/blob/5cae2d7120fed801e47e216ab0286f44427c5f01/dist/svg.pathmorphing.js#L197-L207 |
40,491 | svgdotjs/svg.pathmorphing.js | dist/svg.pathmorphing.js | toBeziere | function toBeziere(val){
var retVal = [val]
switch(val[0]){
case 'M': // special handling for M
this.pos = this.start = [val[1], val[2]]
return retVal
case 'L':
val[5] = val[3] = val[1]
val[6] = val[4] = val[2]
val[1] = this.pos[0]
val[2] = this.pos[1]
break
case 'Q':
val[6] = val[4]
val[5] = val[3]
val[4] = val[4] * 1/3 + val[2] * 2/3
val[3] = val[3] * 1/3 + val[1] * 2/3
val[2] = this.pos[1] * 1/3 + val[2] * 2/3
val[1] = this.pos[0] * 1/3 + val[1] * 2/3
break
case 'A':
retVal = arcToBeziere(this.pos, val)
val = retVal[0]
break
}
val[0] = 'C'
this.pos = [val[5], val[6]]
this.reflection = [2 * val[5] - val[3], 2 * val[6] - val[4]]
return retVal
} | javascript | function toBeziere(val){
var retVal = [val]
switch(val[0]){
case 'M': // special handling for M
this.pos = this.start = [val[1], val[2]]
return retVal
case 'L':
val[5] = val[3] = val[1]
val[6] = val[4] = val[2]
val[1] = this.pos[0]
val[2] = this.pos[1]
break
case 'Q':
val[6] = val[4]
val[5] = val[3]
val[4] = val[4] * 1/3 + val[2] * 2/3
val[3] = val[3] * 1/3 + val[1] * 2/3
val[2] = this.pos[1] * 1/3 + val[2] * 2/3
val[1] = this.pos[0] * 1/3 + val[1] * 2/3
break
case 'A':
retVal = arcToBeziere(this.pos, val)
val = retVal[0]
break
}
val[0] = 'C'
this.pos = [val[5], val[6]]
this.reflection = [2 * val[5] - val[3], 2 * val[6] - val[4]]
return retVal
} | [
"function",
"toBeziere",
"(",
"val",
")",
"{",
"var",
"retVal",
"=",
"[",
"val",
"]",
"switch",
"(",
"val",
"[",
"0",
"]",
")",
"{",
"case",
"'M'",
":",
"// special handling for M",
"this",
".",
"pos",
"=",
"this",
".",
"start",
"=",
"[",
"val",
"[",
"1",
"]",
",",
"val",
"[",
"2",
"]",
"]",
"return",
"retVal",
"case",
"'L'",
":",
"val",
"[",
"5",
"]",
"=",
"val",
"[",
"3",
"]",
"=",
"val",
"[",
"1",
"]",
"val",
"[",
"6",
"]",
"=",
"val",
"[",
"4",
"]",
"=",
"val",
"[",
"2",
"]",
"val",
"[",
"1",
"]",
"=",
"this",
".",
"pos",
"[",
"0",
"]",
"val",
"[",
"2",
"]",
"=",
"this",
".",
"pos",
"[",
"1",
"]",
"break",
"case",
"'Q'",
":",
"val",
"[",
"6",
"]",
"=",
"val",
"[",
"4",
"]",
"val",
"[",
"5",
"]",
"=",
"val",
"[",
"3",
"]",
"val",
"[",
"4",
"]",
"=",
"val",
"[",
"4",
"]",
"*",
"1",
"/",
"3",
"+",
"val",
"[",
"2",
"]",
"*",
"2",
"/",
"3",
"val",
"[",
"3",
"]",
"=",
"val",
"[",
"3",
"]",
"*",
"1",
"/",
"3",
"+",
"val",
"[",
"1",
"]",
"*",
"2",
"/",
"3",
"val",
"[",
"2",
"]",
"=",
"this",
".",
"pos",
"[",
"1",
"]",
"*",
"1",
"/",
"3",
"+",
"val",
"[",
"2",
"]",
"*",
"2",
"/",
"3",
"val",
"[",
"1",
"]",
"=",
"this",
".",
"pos",
"[",
"0",
"]",
"*",
"1",
"/",
"3",
"+",
"val",
"[",
"1",
"]",
"*",
"2",
"/",
"3",
"break",
"case",
"'A'",
":",
"retVal",
"=",
"arcToBeziere",
"(",
"this",
".",
"pos",
",",
"val",
")",
"val",
"=",
"retVal",
"[",
"0",
"]",
"break",
"}",
"val",
"[",
"0",
"]",
"=",
"'C'",
"this",
".",
"pos",
"=",
"[",
"val",
"[",
"5",
"]",
",",
"val",
"[",
"6",
"]",
"]",
"this",
".",
"reflection",
"=",
"[",
"2",
"*",
"val",
"[",
"5",
"]",
"-",
"val",
"[",
"3",
"]",
",",
"2",
"*",
"val",
"[",
"6",
"]",
"-",
"val",
"[",
"4",
"]",
"]",
"return",
"retVal",
"}"
]
| converts all types to cubic beziere | [
"converts",
"all",
"types",
"to",
"cubic",
"beziere"
]
| 5cae2d7120fed801e47e216ab0286f44427c5f01 | https://github.com/svgdotjs/svg.pathmorphing.js/blob/5cae2d7120fed801e47e216ab0286f44427c5f01/dist/svg.pathmorphing.js#L210-L243 |
40,492 | svgdotjs/svg.pathmorphing.js | dist/svg.pathmorphing.js | findNextM | function findNextM(arr, offset){
if(offset === false) return false
for(var i = offset, len = arr.length;i < len;++i){
if(arr[i][0] == 'M') return i
}
return false
} | javascript | function findNextM(arr, offset){
if(offset === false) return false
for(var i = offset, len = arr.length;i < len;++i){
if(arr[i][0] == 'M') return i
}
return false
} | [
"function",
"findNextM",
"(",
"arr",
",",
"offset",
")",
"{",
"if",
"(",
"offset",
"===",
"false",
")",
"return",
"false",
"for",
"(",
"var",
"i",
"=",
"offset",
",",
"len",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"if",
"(",
"arr",
"[",
"i",
"]",
"[",
"0",
"]",
"==",
"'M'",
")",
"return",
"i",
"}",
"return",
"false",
"}"
]
| finds the next position of type M | [
"finds",
"the",
"next",
"position",
"of",
"type",
"M"
]
| 5cae2d7120fed801e47e216ab0286f44427c5f01 | https://github.com/svgdotjs/svg.pathmorphing.js/blob/5cae2d7120fed801e47e216ab0286f44427c5f01/dist/svg.pathmorphing.js#L246-L257 |
40,493 | JamesMGreene/document.currentScript | karma.conf-ci.js | getFriendlyBrowser | function getFriendlyBrowser(browserName) {
browserName = browserName || "";
if (typeof browserName === "string" && browserName) {
if (browserName === "MicrosoftEdge") {
browserName = "edge";
}
if (browserName === "internet explorer") {
browserName = "ie";
}
else if (browserName === "iphone") {
browserName = "safari";
}
else if (browserName === "android") {
browserName = "browser";
}
}
return browserName;
} | javascript | function getFriendlyBrowser(browserName) {
browserName = browserName || "";
if (typeof browserName === "string" && browserName) {
if (browserName === "MicrosoftEdge") {
browserName = "edge";
}
if (browserName === "internet explorer") {
browserName = "ie";
}
else if (browserName === "iphone") {
browserName = "safari";
}
else if (browserName === "android") {
browserName = "browser";
}
}
return browserName;
} | [
"function",
"getFriendlyBrowser",
"(",
"browserName",
")",
"{",
"browserName",
"=",
"browserName",
"||",
"\"\"",
";",
"if",
"(",
"typeof",
"browserName",
"===",
"\"string\"",
"&&",
"browserName",
")",
"{",
"if",
"(",
"browserName",
"===",
"\"MicrosoftEdge\"",
")",
"{",
"browserName",
"=",
"\"edge\"",
";",
"}",
"if",
"(",
"browserName",
"===",
"\"internet explorer\"",
")",
"{",
"browserName",
"=",
"\"ie\"",
";",
"}",
"else",
"if",
"(",
"browserName",
"===",
"\"iphone\"",
")",
"{",
"browserName",
"=",
"\"safari\"",
";",
"}",
"else",
"if",
"(",
"browserName",
"===",
"\"android\"",
")",
"{",
"browserName",
"=",
"\"browser\"",
";",
"}",
"}",
"return",
"browserName",
";",
"}"
]
| UTILITY & GENERATION CODE | [
"UTILITY",
"&",
"GENERATION",
"CODE"
]
| e4a726e58ac3d58e56770437c40f3ffc00c8a194 | https://github.com/JamesMGreene/document.currentScript/blob/e4a726e58ac3d58e56770437c40f3ffc00c8a194/karma.conf-ci.js#L130-L147 |
40,494 | micromatch/glob-fs | index.js | Glob | function Glob(options) {
if (!(this instanceof Glob)) {
return new Glob(options);
}
Emitter.call(this);
this.handler = new Handler(this);
this.init(options);
} | javascript | function Glob(options) {
if (!(this instanceof Glob)) {
return new Glob(options);
}
Emitter.call(this);
this.handler = new Handler(this);
this.init(options);
} | [
"function",
"Glob",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Glob",
")",
")",
"{",
"return",
"new",
"Glob",
"(",
"options",
")",
";",
"}",
"Emitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"handler",
"=",
"new",
"Handler",
"(",
"this",
")",
";",
"this",
".",
"init",
"(",
"options",
")",
";",
"}"
]
| Optionally create an instance of `Glob` with the given `options`.
```js
var Glob = require('glob-fs').Glob;
var glob = new Glob();
```
@param {Object} `options`
@api public | [
"Optionally",
"create",
"an",
"instance",
"of",
"Glob",
"with",
"the",
"given",
"options",
"."
]
| 9419fb8a112ca6554af0448cbb801c00953af8e5 | https://github.com/micromatch/glob-fs/blob/9419fb8a112ca6554af0448cbb801c00953af8e5/index.js#L42-L50 |
40,495 | micromatch/glob-fs | index.js | function (opts) {
this.options = opts || {};
this.pattern = null;
this.middleware = {};
this.includes = {};
this.excludes = {};
this.files = [];
this.fns = [];
options(this);
iterators(this);
symlinks(this);
readers(this);
} | javascript | function (opts) {
this.options = opts || {};
this.pattern = null;
this.middleware = {};
this.includes = {};
this.excludes = {};
this.files = [];
this.fns = [];
options(this);
iterators(this);
symlinks(this);
readers(this);
} | [
"function",
"(",
"opts",
")",
"{",
"this",
".",
"options",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"pattern",
"=",
"null",
";",
"this",
".",
"middleware",
"=",
"{",
"}",
";",
"this",
".",
"includes",
"=",
"{",
"}",
";",
"this",
".",
"excludes",
"=",
"{",
"}",
";",
"this",
".",
"files",
"=",
"[",
"]",
";",
"this",
".",
"fns",
"=",
"[",
"]",
";",
"options",
"(",
"this",
")",
";",
"iterators",
"(",
"this",
")",
";",
"symlinks",
"(",
"this",
")",
";",
"readers",
"(",
"this",
")",
";",
"}"
]
| Initialize private objects. | [
"Initialize",
"private",
"objects",
"."
]
| 9419fb8a112ca6554af0448cbb801c00953af8e5 | https://github.com/micromatch/glob-fs/blob/9419fb8a112ca6554af0448cbb801c00953af8e5/index.js#L62-L75 |
|
40,496 | micromatch/glob-fs | index.js | function (glob, opts) {
if (opts.ignore) {
this.map('exclude', opts.ignore, opts);
}
if (opts.exclude) {
this.map('exclude', opts.exclude, opts);
}
if (opts.include) {
this.map('include', opts.include, opts);
}
// if not disabled by the user, run the built-ins
if (!this.disabled('builtins')) {
if (!this.disabled('npm')) {
this.use(npm(opts));
}
if (!this.disabled('dotfiles')) {
this.use(dotfiles()(opts));
}
if (!this.disabled('gitignore')) {
this.use(gitignore()(opts));
}
}
} | javascript | function (glob, opts) {
if (opts.ignore) {
this.map('exclude', opts.ignore, opts);
}
if (opts.exclude) {
this.map('exclude', opts.exclude, opts);
}
if (opts.include) {
this.map('include', opts.include, opts);
}
// if not disabled by the user, run the built-ins
if (!this.disabled('builtins')) {
if (!this.disabled('npm')) {
this.use(npm(opts));
}
if (!this.disabled('dotfiles')) {
this.use(dotfiles()(opts));
}
if (!this.disabled('gitignore')) {
this.use(gitignore()(opts));
}
}
} | [
"function",
"(",
"glob",
",",
"opts",
")",
"{",
"if",
"(",
"opts",
".",
"ignore",
")",
"{",
"this",
".",
"map",
"(",
"'exclude'",
",",
"opts",
".",
"ignore",
",",
"opts",
")",
";",
"}",
"if",
"(",
"opts",
".",
"exclude",
")",
"{",
"this",
".",
"map",
"(",
"'exclude'",
",",
"opts",
".",
"exclude",
",",
"opts",
")",
";",
"}",
"if",
"(",
"opts",
".",
"include",
")",
"{",
"this",
".",
"map",
"(",
"'include'",
",",
"opts",
".",
"include",
",",
"opts",
")",
";",
"}",
"// if not disabled by the user, run the built-ins",
"if",
"(",
"!",
"this",
".",
"disabled",
"(",
"'builtins'",
")",
")",
"{",
"if",
"(",
"!",
"this",
".",
"disabled",
"(",
"'npm'",
")",
")",
"{",
"this",
".",
"use",
"(",
"npm",
"(",
"opts",
")",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"disabled",
"(",
"'dotfiles'",
")",
")",
"{",
"this",
".",
"use",
"(",
"dotfiles",
"(",
")",
"(",
"opts",
")",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"disabled",
"(",
"'gitignore'",
")",
")",
"{",
"this",
".",
"use",
"(",
"gitignore",
"(",
")",
"(",
"opts",
")",
")",
";",
"}",
"}",
"}"
]
| Set configuration defaults. | [
"Set",
"configuration",
"defaults",
"."
]
| 9419fb8a112ca6554af0448cbb801c00953af8e5 | https://github.com/micromatch/glob-fs/blob/9419fb8a112ca6554af0448cbb801c00953af8e5/index.js#L81-L104 |
|
40,497 | micromatch/glob-fs | index.js | function (pattern, options) {
options = options || {};
this.pattern = new Pattern(pattern, options);
this.recurse = this.shouldRecurse(this.pattern, options);
// if middleware are registered, use the glob, otherwise regex
var glob = this.fns.length
? this.pattern.glob
: this.pattern.regex;
this.defaults(glob, options);
this.include(glob, options);
return this;
} | javascript | function (pattern, options) {
options = options || {};
this.pattern = new Pattern(pattern, options);
this.recurse = this.shouldRecurse(this.pattern, options);
// if middleware are registered, use the glob, otherwise regex
var glob = this.fns.length
? this.pattern.glob
: this.pattern.regex;
this.defaults(glob, options);
this.include(glob, options);
return this;
} | [
"function",
"(",
"pattern",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"pattern",
"=",
"new",
"Pattern",
"(",
"pattern",
",",
"options",
")",
";",
"this",
".",
"recurse",
"=",
"this",
".",
"shouldRecurse",
"(",
"this",
".",
"pattern",
",",
"options",
")",
";",
"// if middleware are registered, use the glob, otherwise regex",
"var",
"glob",
"=",
"this",
".",
"fns",
".",
"length",
"?",
"this",
".",
"pattern",
".",
"glob",
":",
"this",
".",
"pattern",
".",
"regex",
";",
"this",
".",
"defaults",
"(",
"glob",
",",
"options",
")",
";",
"this",
".",
"include",
"(",
"glob",
",",
"options",
")",
";",
"return",
"this",
";",
"}"
]
| Create an instance of `Pattern` from the current glob pattern.
@param {String} `pattern`
@param {Object} `options` | [
"Create",
"an",
"instance",
"of",
"Pattern",
"from",
"the",
"current",
"glob",
"pattern",
"."
]
| 9419fb8a112ca6554af0448cbb801c00953af8e5 | https://github.com/micromatch/glob-fs/blob/9419fb8a112ca6554af0448cbb801c00953af8e5/index.js#L113-L126 |
|
40,498 | micromatch/glob-fs | index.js | function (file) {
return new File({
pattern: this.pattern,
recurse: this.recurse,
dirname: file.dirname,
segment: file.segment,
path: file.path
});
} | javascript | function (file) {
return new File({
pattern: this.pattern,
recurse: this.recurse,
dirname: file.dirname,
segment: file.segment,
path: file.path
});
} | [
"function",
"(",
"file",
")",
"{",
"return",
"new",
"File",
"(",
"{",
"pattern",
":",
"this",
".",
"pattern",
",",
"recurse",
":",
"this",
".",
"recurse",
",",
"dirname",
":",
"file",
".",
"dirname",
",",
"segment",
":",
"file",
".",
"segment",
",",
"path",
":",
"file",
".",
"path",
"}",
")",
";",
"}"
]
| Create a file object with properties that will be used
by middleware.
@param {String} `file`
@return {Object} | [
"Create",
"a",
"file",
"object",
"with",
"properties",
"that",
"will",
"be",
"used",
"by",
"middleware",
"."
]
| 9419fb8a112ca6554af0448cbb801c00953af8e5 | https://github.com/micromatch/glob-fs/blob/9419fb8a112ca6554af0448cbb801c00953af8e5/index.js#L136-L144 |
|
40,499 | micromatch/glob-fs | index.js | function(pattern, options) {
var opts = this.setDefaults(options);
if (typeof opts.recurse === 'boolean') {
return opts.recurse;
}
return pattern.isGlobstar;
} | javascript | function(pattern, options) {
var opts = this.setDefaults(options);
if (typeof opts.recurse === 'boolean') {
return opts.recurse;
}
return pattern.isGlobstar;
} | [
"function",
"(",
"pattern",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"this",
".",
"setDefaults",
"(",
"options",
")",
";",
"if",
"(",
"typeof",
"opts",
".",
"recurse",
"===",
"'boolean'",
")",
"{",
"return",
"opts",
".",
"recurse",
";",
"}",
"return",
"pattern",
".",
"isGlobstar",
";",
"}"
]
| Return `true` if the iterator should recurse, based
on the given glob pattern and options.
@param {String} `pattern`
@param {Object} `options` | [
"Return",
"true",
"if",
"the",
"iterator",
"should",
"recurse",
"based",
"on",
"the",
"given",
"glob",
"pattern",
"and",
"options",
"."
]
| 9419fb8a112ca6554af0448cbb801c00953af8e5 | https://github.com/micromatch/glob-fs/blob/9419fb8a112ca6554af0448cbb801c00953af8e5/index.js#L154-L160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.