repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
nyteshade/ne-tag-fns | dist/functions.js | cautiouslyApplyEach | function cautiouslyApplyEach(
array,
fns,
log = true,
keepOldValueOnFalseyReturn = false)
{
let items = Array.from(array);
if (items && Array.isArray(items) && fns && Array.isArray(fns)) {
items.forEach((item, itemIndex, itemArray) => {
let newItem = item;
fns.forEach(fn => {
try {
let bindFunctor = Array.isArray(fn) && fn[1];
let functor = bindFunctor ?
fn[0].bind(newItem) :
Array.isArray(fn) ? fn[0] : fn;
if (keepOldValueOnFalseyReturn)
newItem = functor(newItem, itemIndex, itemArray) || newItem;else
newItem = functor(newItem, itemIndex, itemArray);
}
catch (error) {
if (log) {
console.error(error);
}
}
});
items[itemIndex] = newItem;
});
}
return items;
} | javascript | function cautiouslyApplyEach(
array,
fns,
log = true,
keepOldValueOnFalseyReturn = false)
{
let items = Array.from(array);
if (items && Array.isArray(items) && fns && Array.isArray(fns)) {
items.forEach((item, itemIndex, itemArray) => {
let newItem = item;
fns.forEach(fn => {
try {
let bindFunctor = Array.isArray(fn) && fn[1];
let functor = bindFunctor ?
fn[0].bind(newItem) :
Array.isArray(fn) ? fn[0] : fn;
if (keepOldValueOnFalseyReturn)
newItem = functor(newItem, itemIndex, itemArray) || newItem;else
newItem = functor(newItem, itemIndex, itemArray);
}
catch (error) {
if (log) {
console.error(error);
}
}
});
items[itemIndex] = newItem;
});
}
return items;
} | [
"function",
"cautiouslyApplyEach",
"(",
"array",
",",
"fns",
",",
"log",
"=",
"true",
",",
"keepOldValueOnFalseyReturn",
"=",
"false",
")",
"{",
"let",
"items",
"=",
"Array",
".",
"from",
"(",
"array",
")",
";",
"if",
"(",
"items",
"&&",
"Array",
".",
"isArray",
"(",
"items",
")",
"&&",
"fns",
"&&",
"Array",
".",
"isArray",
"(",
"fns",
")",
")",
"{",
"items",
".",
"forEach",
"(",
"(",
"item",
",",
"itemIndex",
",",
"itemArray",
")",
"=>",
"{",
"let",
"newItem",
"=",
"item",
";",
"fns",
".",
"forEach",
"(",
"fn",
"=>",
"{",
"try",
"{",
"let",
"bindFunctor",
"=",
"Array",
".",
"isArray",
"(",
"fn",
")",
"&&",
"fn",
"[",
"1",
"]",
";",
"let",
"functor",
"=",
"bindFunctor",
"?",
"fn",
"[",
"0",
"]",
".",
"bind",
"(",
"newItem",
")",
":",
"Array",
".",
"isArray",
"(",
"fn",
")",
"?",
"fn",
"[",
"0",
"]",
":",
"fn",
";",
"if",
"(",
"keepOldValueOnFalseyReturn",
")",
"newItem",
"=",
"functor",
"(",
"newItem",
",",
"itemIndex",
",",
"itemArray",
")",
"||",
"newItem",
";",
"else",
"newItem",
"=",
"functor",
"(",
"newItem",
",",
"itemIndex",
",",
"itemArray",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"log",
")",
"{",
"console",
".",
"error",
"(",
"error",
")",
";",
"}",
"}",
"}",
")",
";",
"items",
"[",
"itemIndex",
"]",
"=",
"newItem",
";",
"}",
")",
";",
"}",
"return",
"items",
";",
"}"
] | Nearly identical to `cautiouslyApply`, this function works on an array of
items rather than a single item. The only other difference is that the
supplied functors receive the index of the item and the array the item is
contained within as second and third parameters, respectively.
@param {Array<mixed>} array an array of values to apply each functor to
@param {Array<Function>} fns an array of `Function` objects that are to be
executed with the supplied `item` as its input and the new value as its
output. An error or fals
@param {boolean} log true if any errors caused by function execution should
be logged
@param {boolean} keepOldValueOnFalseyReturn if true and the functor returns
a falsey value, the value passed to it as a parameter is used instead
@return {Array<mixed>} a copy of the array passed as `array` but with
potentially modified internal values | [
"Nearly",
"identical",
"to",
"cautiouslyApply",
"this",
"function",
"works",
"on",
"an",
"array",
"of",
"items",
"rather",
"than",
"a",
"single",
"item",
".",
"The",
"only",
"other",
"difference",
"is",
"that",
"the",
"supplied",
"functors",
"receive",
"the",
"index",
"of",
"the",
"item",
"and",
"the",
"array",
"the",
"item",
"is",
"contained",
"within",
"as",
"second",
"and",
"third",
"parameters",
"respectively",
"."
] | f851cb7b72fbbfbfe4e38edeb91d90c04035ee74 | https://github.com/nyteshade/ne-tag-fns/blob/f851cb7b72fbbfbfe4e38edeb91d90c04035ee74/dist/functions.js#L69-L105 | train |
nyteshade/ne-tag-fns | dist/functions.js | cautiouslyApply | function cautiouslyApply(
item,
fns,
log = true,
keepOldValueOnFalseyReturn = false)
{
if (fns && Array.isArray(fns)) {
fns.forEach(fn => {
try {
let bindFunctor = Array.isArray(fn) && fn[1];
let functor = bindFunctor ?
fn[0].bind(item) :
Array.isArray(fn) ? fn[0] : fn;
if (keepOldValueOnFalseyReturn)
item = functor(item) || item;else
item = functor(item);
}
catch (error) {
if (log) {
console.error(error);
}
}
});
}
return item;
} | javascript | function cautiouslyApply(
item,
fns,
log = true,
keepOldValueOnFalseyReturn = false)
{
if (fns && Array.isArray(fns)) {
fns.forEach(fn => {
try {
let bindFunctor = Array.isArray(fn) && fn[1];
let functor = bindFunctor ?
fn[0].bind(item) :
Array.isArray(fn) ? fn[0] : fn;
if (keepOldValueOnFalseyReturn)
item = functor(item) || item;else
item = functor(item);
}
catch (error) {
if (log) {
console.error(error);
}
}
});
}
return item;
} | [
"function",
"cautiouslyApply",
"(",
"item",
",",
"fns",
",",
"log",
"=",
"true",
",",
"keepOldValueOnFalseyReturn",
"=",
"false",
")",
"{",
"if",
"(",
"fns",
"&&",
"Array",
".",
"isArray",
"(",
"fns",
")",
")",
"{",
"fns",
".",
"forEach",
"(",
"fn",
"=>",
"{",
"try",
"{",
"let",
"bindFunctor",
"=",
"Array",
".",
"isArray",
"(",
"fn",
")",
"&&",
"fn",
"[",
"1",
"]",
";",
"let",
"functor",
"=",
"bindFunctor",
"?",
"fn",
"[",
"0",
"]",
".",
"bind",
"(",
"item",
")",
":",
"Array",
".",
"isArray",
"(",
"fn",
")",
"?",
"fn",
"[",
"0",
"]",
":",
"fn",
";",
"if",
"(",
"keepOldValueOnFalseyReturn",
")",
"item",
"=",
"functor",
"(",
"item",
")",
"||",
"item",
";",
"else",
"item",
"=",
"functor",
"(",
"item",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"log",
")",
"{",
"console",
".",
"error",
"(",
"error",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"return",
"item",
";",
"}"
] | Given an item that needs to be modified or replaced, the function takes
an array of functions to run in order, each receiving the last state of the
item. If an exception occurs during function execution the value passed is
the value that is kept.
Optionally, when the function executes and returns the newly modified state
of the object in question, if that value is falsey it can be replaced with
the original value passed to the function instead. This is not true by
default
`fns` is an array of functions, but any of the functions in the list are
actually a tuple matching [Function, boolean] **and** the boolean value is
true then the function within will be bound to the item it is operating on
as the `this` context for its execution before processing the value. It will
still receive the item as the first parameter as well.
**NOTE: this will not work on big arrow functions**
@param {mixed} item any JavaScript value
@param {Array<Function>} fns an array of `Function` objects that are to be
executed with the supplied `item` as its input and the new value as its
output. An error or fals
@param {boolean} log true if any errors caused by function execution should
be logged
@param {boolean} keepOldValueOnFalseyReturn if true and the functor returns
a falsey value, the value passed to it as a parameter is used instead
@return {mixed} the new value to replace the one supplied as `item` | [
"Given",
"an",
"item",
"that",
"needs",
"to",
"be",
"modified",
"or",
"replaced",
"the",
"function",
"takes",
"an",
"array",
"of",
"functions",
"to",
"run",
"in",
"order",
"each",
"receiving",
"the",
"last",
"state",
"of",
"the",
"item",
".",
"If",
"an",
"exception",
"occurs",
"during",
"function",
"execution",
"the",
"value",
"passed",
"is",
"the",
"value",
"that",
"is",
"kept",
"."
] | f851cb7b72fbbfbfe4e38edeb91d90c04035ee74 | https://github.com/nyteshade/ne-tag-fns/blob/f851cb7b72fbbfbfe4e38edeb91d90c04035ee74/dist/functions.js#L136-L164 | train |
nyteshade/ne-tag-fns | dist/functions.js | measureIndents | function measureIndents(
string,
config = {
preWork: [],
perLine: [],
postWork: [] },
whitespace = /[ \t]/)
{
let regexp = new RegExp(`(^${whitespace.source}*)`);
let strings;
let indents;
if (Array.isArray(string)) {
string = string.join('\n');
}
string = cautiouslyApply(string, config.preWork, true, true);
strings = string.split(/\r?\n/);
indents = strings.map((s, i, a) => {
let search;
s = cautiouslyApply(s, config.perLine, true, false);
search = regexp.exec(s);
return search && search[1].length || 0;
});
return cautiouslyApply([strings, indents], config.postWork);
} | javascript | function measureIndents(
string,
config = {
preWork: [],
perLine: [],
postWork: [] },
whitespace = /[ \t]/)
{
let regexp = new RegExp(`(^${whitespace.source}*)`);
let strings;
let indents;
if (Array.isArray(string)) {
string = string.join('\n');
}
string = cautiouslyApply(string, config.preWork, true, true);
strings = string.split(/\r?\n/);
indents = strings.map((s, i, a) => {
let search;
s = cautiouslyApply(s, config.perLine, true, false);
search = regexp.exec(s);
return search && search[1].length || 0;
});
return cautiouslyApply([strings, indents], config.postWork);
} | [
"function",
"measureIndents",
"(",
"string",
",",
"config",
"=",
"{",
"preWork",
":",
"[",
"]",
",",
"perLine",
":",
"[",
"]",
",",
"postWork",
":",
"[",
"]",
"}",
",",
"whitespace",
"=",
"/",
"[ \\t]",
"/",
")",
"{",
"let",
"regexp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"whitespace",
".",
"source",
"}",
"`",
")",
";",
"let",
"strings",
";",
"let",
"indents",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"string",
")",
")",
"{",
"string",
"=",
"string",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
"\\n",
"string",
"=",
"cautiouslyApply",
"(",
"string",
",",
"config",
".",
"preWork",
",",
"true",
",",
"true",
")",
";",
"strings",
"=",
"string",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
";",
"indents",
"=",
"strings",
".",
"map",
"(",
"(",
"s",
",",
"i",
",",
"a",
")",
"=>",
"{",
"let",
"search",
";",
"s",
"=",
"cautiouslyApply",
"(",
"s",
",",
"config",
".",
"perLine",
",",
"true",
",",
"false",
")",
";",
"search",
"=",
"regexp",
".",
"exec",
"(",
"s",
")",
";",
"return",
"search",
"&&",
"search",
"[",
"1",
"]",
".",
"length",
"||",
"0",
";",
"}",
")",
";",
"}"
] | Measure indents is something that may be of use for any tag function. Its
purpose is to take a string, split it into separate lines and count the
leading whitespace of each line. Once finished, it returns an array of
two items; the list of strings and the matching list of indents which are
related to each other via index.
The function also receives a config object which allows you to specify up
to three lists worth of functions.
`preWork` is a list of functions that receive the following arguments in
each callback and are meant as a pluggable way to modify the initial string
programmatically by the consuming developer. Examples might be to prune
empty initial and final lines if they contain only whitespace
```
preWorkFn(string: string): string
- string: the supplied string to be modified by the function with the
new version to be used as the returned value. If null or undefined is
returned instead, the value supplied to the function will be used
```
`perLine` is list of functions that receive the following arguments in
each callback and are meant as a pluggable way to modify the line in
question. The expected return value is the newly modified string from which
to measure the indent of. Each item in the list will receive the modified
string returned by its predecessor. Effectively this is a map function
```
perLine(string: string, index: number, array: Array<string>): string
```
`postWork` is a list of functions that get called in order and receive
the final results in the form of an array containing two elements. The
first is the list of strings and the second is the list of measuredIndents.
The format of the supplied value (i.e. array of two arrays) is expected as
a return value. Failure to do so will likely end up as a bug someplace
```
postWork(
array: Array<Array<string>, Array<number>>
): Array<Array<string>, Array<number>>
```
All functions supplied to these arrays, if wrapped in an array with a
second parameter of true, will cause the function in question to be bound
with the item it is working on as the `this` context.
@param {string} string see above
@param {Object} config see above
@param {RegExp} whitespace the defintion for whitespaced used within
@return {Array<Array<string>, Array<number>>} an array containing two
arrays; the first being an array of one line per index and the second being
an index matched array of numbered offsets indicating the amount of white
space that line is prefixed with | [
"Measure",
"indents",
"is",
"something",
"that",
"may",
"be",
"of",
"use",
"for",
"any",
"tag",
"function",
".",
"Its",
"purpose",
"is",
"to",
"take",
"a",
"string",
"split",
"it",
"into",
"separate",
"lines",
"and",
"count",
"the",
"leading",
"whitespace",
"of",
"each",
"line",
".",
"Once",
"finished",
"it",
"returns",
"an",
"array",
"of",
"two",
"items",
";",
"the",
"list",
"of",
"strings",
"and",
"the",
"matching",
"list",
"of",
"indents",
"which",
"are",
"related",
"to",
"each",
"other",
"via",
"index",
"."
] | f851cb7b72fbbfbfe4e38edeb91d90c04035ee74 | https://github.com/nyteshade/ne-tag-fns/blob/f851cb7b72fbbfbfe4e38edeb91d90c04035ee74/dist/functions.js#L223-L252 | train |
nyteshade/ne-tag-fns | dist/functions.js | stripEmptyFirstAndLast | function stripEmptyFirstAndLast(string) {
let strings = string.split(/\r?\n/);
// construct a small resuable function for trimming all initial whitespace
let trimL = s => s.replace(/^([ \t]*)/, '');
let trimR = s => s.replace(/([ \t]*)($)/, '$1');
// the first line is usually a misnomer, discount it if it is only
// whitespace
if (!trimL(strings[0]).length) {
strings.splice(0, 1);
}
// the same goes for the last line
if (
strings.length &&
strings[strings.length - 1] &&
!trimL(strings[strings.length - 1]).length)
{
strings.splice(strings.length - 1, 1);
}
return strings.join('\n');
} | javascript | function stripEmptyFirstAndLast(string) {
let strings = string.split(/\r?\n/);
// construct a small resuable function for trimming all initial whitespace
let trimL = s => s.replace(/^([ \t]*)/, '');
let trimR = s => s.replace(/([ \t]*)($)/, '$1');
// the first line is usually a misnomer, discount it if it is only
// whitespace
if (!trimL(strings[0]).length) {
strings.splice(0, 1);
}
// the same goes for the last line
if (
strings.length &&
strings[strings.length - 1] &&
!trimL(strings[strings.length - 1]).length)
{
strings.splice(strings.length - 1, 1);
}
return strings.join('\n');
} | [
"function",
"stripEmptyFirstAndLast",
"(",
"string",
")",
"{",
"let",
"strings",
"=",
"string",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
";",
"let",
"trimL",
"=",
"s",
"=>",
"s",
".",
"replace",
"(",
"/",
"^([ \\t]*)",
"/",
",",
"''",
")",
";",
"let",
"trimR",
"=",
"s",
"=>",
"s",
".",
"replace",
"(",
"/",
"([ \\t]*)($)",
"/",
",",
"'$1'",
")",
";",
"if",
"(",
"!",
"trimL",
"(",
"strings",
"[",
"0",
"]",
")",
".",
"length",
")",
"{",
"strings",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"}",
"if",
"(",
"strings",
".",
"length",
"&&",
"strings",
"[",
"strings",
".",
"length",
"-",
"1",
"]",
"&&",
"!",
"trimL",
"(",
"strings",
"[",
"strings",
".",
"length",
"-",
"1",
"]",
")",
".",
"length",
")",
"{",
"strings",
".",
"splice",
"(",
"strings",
".",
"length",
"-",
"1",
",",
"1",
")",
";",
"}",
"return",
"strings",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] | A `preWork` functor for use with `measureIndents` that strips the first and
last lines from a given string if that string has nothing but whitespace. A
commonly desired functionality when working with multiline template strings
@param {string} string the string to parse
@return {string} a modified string missing bits that make up the first and/
or last lines **if** either of these lines are comprised of only whitespace | [
"A",
"preWork",
"functor",
"for",
"use",
"with",
"measureIndents",
"that",
"strips",
"the",
"first",
"and",
"last",
"lines",
"from",
"a",
"given",
"string",
"if",
"that",
"string",
"has",
"nothing",
"but",
"whitespace",
".",
"A",
"commonly",
"desired",
"functionality",
"when",
"working",
"with",
"multiline",
"template",
"strings"
] | f851cb7b72fbbfbfe4e38edeb91d90c04035ee74 | https://github.com/nyteshade/ne-tag-fns/blob/f851cb7b72fbbfbfe4e38edeb91d90c04035ee74/dist/functions.js#L431-L453 | train |
nyteshade/ne-tag-fns | dist/functions.js | dropLowestIndents | function dropLowestIndents(
values)
{
let [strings, indents] = values;
let set = new Set(indents);
let lowest = Math.min(...indents);
set.delete(lowest);
return [strings, Array.from(set)];
} | javascript | function dropLowestIndents(
values)
{
let [strings, indents] = values;
let set = new Set(indents);
let lowest = Math.min(...indents);
set.delete(lowest);
return [strings, Array.from(set)];
} | [
"function",
"dropLowestIndents",
"(",
"values",
")",
"{",
"let",
"[",
"strings",
",",
"indents",
"]",
"=",
"values",
";",
"let",
"set",
"=",
"new",
"Set",
"(",
"indents",
")",
";",
"let",
"lowest",
"=",
"Math",
".",
"min",
"(",
"...",
"indents",
")",
";",
"set",
".",
"delete",
"(",
"lowest",
")",
";",
"return",
"[",
"strings",
",",
"Array",
".",
"from",
"(",
"set",
")",
"]",
";",
"}"
] | A `postWork` functor for use with `measureIndents` that will modify the
indents array to be an array missing its lowest number.
@param {[Array<string>, Array<number>]} values the tuple containing the
modified strings and indent values
@return {[Array<string>, Array<number>]} returns a tuple containing an
unmodified set of strings and a modified indents array missing the lowest
number in the list | [
"A",
"postWork",
"functor",
"for",
"use",
"with",
"measureIndents",
"that",
"will",
"modify",
"the",
"indents",
"array",
"to",
"be",
"an",
"array",
"missing",
"its",
"lowest",
"number",
"."
] | f851cb7b72fbbfbfe4e38edeb91d90c04035ee74 | https://github.com/nyteshade/ne-tag-fns/blob/f851cb7b72fbbfbfe4e38edeb91d90c04035ee74/dist/functions.js#L465-L475 | train |
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | GregorianCalendar | function GregorianCalendar(timezoneOffset, locale) {
var args = util.makeArray(arguments);
if (typeof timezoneOffset === 'object') {
locale = timezoneOffset;
timezoneOffset = locale.timezoneOffset;
} else if (args.length >= 3) {
timezoneOffset = locale = null;
}
locale = locale || defaultLocale;
this.locale = locale;
this.fields = []; /**
* The currently set time for this date.
* @protected
* @type Number|undefined
*/
/**
* The currently set time for this date.
* @protected
* @type Number|undefined
*/
this.time = undefined; /**
* The timezoneOffset in minutes used by this date.
* @type Number
* @protected
*/
/**
* The timezoneOffset in minutes used by this date.
* @type Number
* @protected
*/
this.timezoneOffset = timezoneOffset || locale.timezoneOffset; /**
* The first day of the week
* @type Number
* @protected
*/
/**
* The first day of the week
* @type Number
* @protected
*/
this.firstDayOfWeek = locale.firstDayOfWeek; /**
* The number of days required for the first week in a month or year,
* with possible values from 1 to 7.
* @@protected
* @type Number
*/
/**
* The number of days required for the first week in a month or year,
* with possible values from 1 to 7.
* @@protected
* @type Number
*/
this.minimalDaysInFirstWeek = locale.minimalDaysInFirstWeek;
this.fieldsComputed = false;
if (arguments.length >= 3) {
this.set.apply(this, args);
}
} | javascript | function GregorianCalendar(timezoneOffset, locale) {
var args = util.makeArray(arguments);
if (typeof timezoneOffset === 'object') {
locale = timezoneOffset;
timezoneOffset = locale.timezoneOffset;
} else if (args.length >= 3) {
timezoneOffset = locale = null;
}
locale = locale || defaultLocale;
this.locale = locale;
this.fields = []; /**
* The currently set time for this date.
* @protected
* @type Number|undefined
*/
/**
* The currently set time for this date.
* @protected
* @type Number|undefined
*/
this.time = undefined; /**
* The timezoneOffset in minutes used by this date.
* @type Number
* @protected
*/
/**
* The timezoneOffset in minutes used by this date.
* @type Number
* @protected
*/
this.timezoneOffset = timezoneOffset || locale.timezoneOffset; /**
* The first day of the week
* @type Number
* @protected
*/
/**
* The first day of the week
* @type Number
* @protected
*/
this.firstDayOfWeek = locale.firstDayOfWeek; /**
* The number of days required for the first week in a month or year,
* with possible values from 1 to 7.
* @@protected
* @type Number
*/
/**
* The number of days required for the first week in a month or year,
* with possible values from 1 to 7.
* @@protected
* @type Number
*/
this.minimalDaysInFirstWeek = locale.minimalDaysInFirstWeek;
this.fieldsComputed = false;
if (arguments.length >= 3) {
this.set.apply(this, args);
}
} | [
"function",
"GregorianCalendar",
"(",
"timezoneOffset",
",",
"locale",
")",
"{",
"var",
"args",
"=",
"util",
".",
"makeArray",
"(",
"arguments",
")",
";",
"if",
"(",
"typeof",
"timezoneOffset",
"===",
"'object'",
")",
"{",
"locale",
"=",
"timezoneOffset",
";",
"timezoneOffset",
"=",
"locale",
".",
"timezoneOffset",
";",
"}",
"else",
"if",
"(",
"args",
".",
"length",
">=",
"3",
")",
"{",
"timezoneOffset",
"=",
"locale",
"=",
"null",
";",
"}",
"locale",
"=",
"locale",
"||",
"defaultLocale",
";",
"this",
".",
"locale",
"=",
"locale",
";",
"this",
".",
"fields",
"=",
"[",
"]",
";",
"this",
".",
"time",
"=",
"undefined",
";",
"this",
".",
"timezoneOffset",
"=",
"timezoneOffset",
"||",
"locale",
".",
"timezoneOffset",
";",
"this",
".",
"firstDayOfWeek",
"=",
"locale",
".",
"firstDayOfWeek",
";",
"this",
".",
"minimalDaysInFirstWeek",
"=",
"locale",
".",
"minimalDaysInFirstWeek",
";",
"this",
".",
"fieldsComputed",
"=",
"false",
";",
"if",
"(",
"arguments",
".",
"length",
">=",
"3",
")",
"{",
"this",
".",
"set",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
"}"
] | GregorianCalendar class.
- no arguments:
Constructs a default GregorianCalendar using the current time
in the default time zone with the default locale.
- one argument timezoneOffset:
Constructs a GregorianCalendar based on the current time
in the given timezoneOffset with the default locale.
- one argument locale:
Constructs a GregorianCalendar
based on the current time in the default time zone with the given locale.
- two arguments
Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.
- zone - the given time zone.
- aLocale - the given locale.
- 3 to 6 arguments:
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
- year - the value used to set the YEAR calendar field in the calendar.
- month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g.,
0 for January.
- dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
- hourOfDay - the value used to set the HOUR_OF_DAY calendar field in the calendar.
- minute - the value used to set the MINUTE calendar field in the calendar.
- second - the value used to set the SECONDS calendar field in the calendar.
@class KISSY.Date.Gregorian
GregorianCalendar class.
- no arguments:
Constructs a default GregorianCalendar using the current time
in the default time zone with the default locale.
- one argument timezoneOffset:
Constructs a GregorianCalendar based on the current time
in the given timezoneOffset with the default locale.
- one argument locale:
Constructs a GregorianCalendar
based on the current time in the default time zone with the given locale.
- two arguments
Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.
- zone - the given time zone.
- aLocale - the given locale.
- 3 to 6 arguments:
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
- year - the value used to set the YEAR calendar field in the calendar.
- month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g.,
0 for January.
- dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
- hourOfDay - the value used to set the HOUR_OF_DAY calendar field in the calendar.
- minute - the value used to set the MINUTE calendar field in the calendar.
- second - the value used to set the SECONDS calendar field in the calendar.
@class KISSY.Date.Gregorian | [
"GregorianCalendar",
"class",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L87-L144 | train |
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function (field) {
if (MIN_VALUES[field] !== undefined) {
return MIN_VALUES[field];
}
var fields = this.fields;
if (field === WEEK_OF_MONTH) {
var cal = new GregorianCalendar(fields[YEAR], fields[MONTH], 1);
return cal.get(WEEK_OF_MONTH);
}
throw new Error('minimum value not defined!');
} | javascript | function (field) {
if (MIN_VALUES[field] !== undefined) {
return MIN_VALUES[field];
}
var fields = this.fields;
if (field === WEEK_OF_MONTH) {
var cal = new GregorianCalendar(fields[YEAR], fields[MONTH], 1);
return cal.get(WEEK_OF_MONTH);
}
throw new Error('minimum value not defined!');
} | [
"function",
"(",
"field",
")",
"{",
"if",
"(",
"MIN_VALUES",
"[",
"field",
"]",
"!==",
"undefined",
")",
"{",
"return",
"MIN_VALUES",
"[",
"field",
"]",
";",
"}",
"var",
"fields",
"=",
"this",
".",
"fields",
";",
"if",
"(",
"field",
"===",
"WEEK_OF_MONTH",
")",
"{",
"var",
"cal",
"=",
"new",
"GregorianCalendar",
"(",
"fields",
"[",
"YEAR",
"]",
",",
"fields",
"[",
"MONTH",
"]",
",",
"1",
")",
";",
"return",
"cal",
".",
"get",
"(",
"WEEK_OF_MONTH",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'minimum value not defined!'",
")",
";",
"}"
] | Returns the minimum value for
the given calendar field of this GregorianCalendar instance.
The minimum value is defined as the smallest value
returned by the get method for any possible time value,
taking into consideration the current values of the getFirstDayOfWeek,
getMinimalDaysInFirstWeek.
@param field the calendar field.
@returns {Number} the minimum value for the given calendar field. | [
"Returns",
"the",
"minimum",
"value",
"for",
"the",
"given",
"calendar",
"field",
"of",
"this",
"GregorianCalendar",
"instance",
".",
"The",
"minimum",
"value",
"is",
"defined",
"as",
"the",
"smallest",
"value",
"returned",
"by",
"the",
"get",
"method",
"for",
"any",
"possible",
"time",
"value",
"taking",
"into",
"consideration",
"the",
"current",
"values",
"of",
"the",
"getFirstDayOfWeek",
"getMinimalDaysInFirstWeek",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L378-L388 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function (field) {
if (MAX_VALUES[field] !== undefined) {
return MAX_VALUES[field];
}
var value, fields = this.fields;
switch (field) {
case DAY_OF_MONTH:
value = getMonthLength(fields[YEAR], fields[MONTH]);
break;
case WEEK_OF_YEAR:
var endOfYear = new GregorianCalendar(fields[YEAR], GregorianCalendar.DECEMBER, 31);
value = endOfYear.get(WEEK_OF_YEAR);
if (value === 1) {
value = 52;
}
break;
case WEEK_OF_MONTH:
var endOfMonth = new GregorianCalendar(fields[YEAR], fields[MONTH], getMonthLength(fields[YEAR], fields[MONTH]));
value = endOfMonth.get(WEEK_OF_MONTH);
break;
case DAY_OF_YEAR:
value = getYearLength(fields[YEAR]);
break;
case DAY_OF_WEEK_IN_MONTH:
value = toInt((getMonthLength(fields[YEAR], fields[MONTH]) - 1) / 7) + 1;
break;
}
if (value === undefined) {
throw new Error('maximum value not defined!');
}
return value;
} | javascript | function (field) {
if (MAX_VALUES[field] !== undefined) {
return MAX_VALUES[field];
}
var value, fields = this.fields;
switch (field) {
case DAY_OF_MONTH:
value = getMonthLength(fields[YEAR], fields[MONTH]);
break;
case WEEK_OF_YEAR:
var endOfYear = new GregorianCalendar(fields[YEAR], GregorianCalendar.DECEMBER, 31);
value = endOfYear.get(WEEK_OF_YEAR);
if (value === 1) {
value = 52;
}
break;
case WEEK_OF_MONTH:
var endOfMonth = new GregorianCalendar(fields[YEAR], fields[MONTH], getMonthLength(fields[YEAR], fields[MONTH]));
value = endOfMonth.get(WEEK_OF_MONTH);
break;
case DAY_OF_YEAR:
value = getYearLength(fields[YEAR]);
break;
case DAY_OF_WEEK_IN_MONTH:
value = toInt((getMonthLength(fields[YEAR], fields[MONTH]) - 1) / 7) + 1;
break;
}
if (value === undefined) {
throw new Error('maximum value not defined!');
}
return value;
} | [
"function",
"(",
"field",
")",
"{",
"if",
"(",
"MAX_VALUES",
"[",
"field",
"]",
"!==",
"undefined",
")",
"{",
"return",
"MAX_VALUES",
"[",
"field",
"]",
";",
"}",
"var",
"value",
",",
"fields",
"=",
"this",
".",
"fields",
";",
"switch",
"(",
"field",
")",
"{",
"case",
"DAY_OF_MONTH",
":",
"value",
"=",
"getMonthLength",
"(",
"fields",
"[",
"YEAR",
"]",
",",
"fields",
"[",
"MONTH",
"]",
")",
";",
"break",
";",
"case",
"WEEK_OF_YEAR",
":",
"var",
"endOfYear",
"=",
"new",
"GregorianCalendar",
"(",
"fields",
"[",
"YEAR",
"]",
",",
"GregorianCalendar",
".",
"DECEMBER",
",",
"31",
")",
";",
"value",
"=",
"endOfYear",
".",
"get",
"(",
"WEEK_OF_YEAR",
")",
";",
"if",
"(",
"value",
"===",
"1",
")",
"{",
"value",
"=",
"52",
";",
"}",
"break",
";",
"case",
"WEEK_OF_MONTH",
":",
"var",
"endOfMonth",
"=",
"new",
"GregorianCalendar",
"(",
"fields",
"[",
"YEAR",
"]",
",",
"fields",
"[",
"MONTH",
"]",
",",
"getMonthLength",
"(",
"fields",
"[",
"YEAR",
"]",
",",
"fields",
"[",
"MONTH",
"]",
")",
")",
";",
"value",
"=",
"endOfMonth",
".",
"get",
"(",
"WEEK_OF_MONTH",
")",
";",
"break",
";",
"case",
"DAY_OF_YEAR",
":",
"value",
"=",
"getYearLength",
"(",
"fields",
"[",
"YEAR",
"]",
")",
";",
"break",
";",
"case",
"DAY_OF_WEEK_IN_MONTH",
":",
"value",
"=",
"toInt",
"(",
"(",
"getMonthLength",
"(",
"fields",
"[",
"YEAR",
"]",
",",
"fields",
"[",
"MONTH",
"]",
")",
"-",
"1",
")",
"/",
"7",
")",
"+",
"1",
";",
"break",
";",
"}",
"if",
"(",
"value",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"'maximum value not defined!'",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Returns the maximum value for the given calendar field
of this GregorianCalendar instance.
The maximum value is defined as the largest value returned
by the get method for any possible time value, taking into consideration
the current values of the getFirstDayOfWeek, getMinimalDaysInFirstWeek methods.
@param field the calendar field.
@returns {Number} the maximum value for the given calendar field. | [
"Returns",
"the",
"maximum",
"value",
"for",
"the",
"given",
"calendar",
"field",
"of",
"this",
"GregorianCalendar",
"instance",
".",
"The",
"maximum",
"value",
"is",
"defined",
"as",
"the",
"largest",
"value",
"returned",
"by",
"the",
"get",
"method",
"for",
"any",
"possible",
"time",
"value",
"taking",
"into",
"consideration",
"the",
"current",
"values",
"of",
"the",
"getFirstDayOfWeek",
"getMinimalDaysInFirstWeek",
"methods",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L398-L429 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function (field, v) {
var len = arguments.length;
if (len === 2) {
this.fields[field] = v;
} else if (len < MILLISECONDS + 1) {
for (var i = 0; i < len; i++) {
this.fields[YEAR + i] = arguments[i];
}
} else {
throw new Error('illegal arguments for KISSY GregorianCalendar set');
}
this.time = undefined;
} | javascript | function (field, v) {
var len = arguments.length;
if (len === 2) {
this.fields[field] = v;
} else if (len < MILLISECONDS + 1) {
for (var i = 0; i < len; i++) {
this.fields[YEAR + i] = arguments[i];
}
} else {
throw new Error('illegal arguments for KISSY GregorianCalendar set');
}
this.time = undefined;
} | [
"function",
"(",
"field",
",",
"v",
")",
"{",
"var",
"len",
"=",
"arguments",
".",
"length",
";",
"if",
"(",
"len",
"===",
"2",
")",
"{",
"this",
".",
"fields",
"[",
"field",
"]",
"=",
"v",
";",
"}",
"else",
"if",
"(",
"len",
"<",
"MILLISECONDS",
"+",
"1",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"this",
".",
"fields",
"[",
"YEAR",
"+",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'illegal arguments for KISSY GregorianCalendar set'",
")",
";",
"}",
"this",
".",
"time",
"=",
"undefined",
";",
"}"
] | Returns the year of the given calendar field.
@method getYear
@returns {Number} the year for the given calendar field.
Returns the month of the given calendar field.
@method getMonth
@returns {Number} the month for the given calendar field.
Returns the day of month of the given calendar field.
@method getDayOfMonth
@returns {Number} the day of month for the given calendar field.
Returns the hour of day of the given calendar field.
@method getHourOfDay
@returns {Number} the hour of day for the given calendar field.
Returns the minute of the given calendar field.
@method getMinute
@returns {Number} the minute for the given calendar field.
Returns the second of the given calendar field.
@method getSecond
@returns {Number} the second for the given calendar field.
Returns the millisecond of the given calendar field.
@method getMilliSecond
@returns {Number} the millisecond for the given calendar field.
Returns the week of year of the given calendar field.
@method getWeekOfYear
@returns {Number} the week of year for the given calendar field.
Returns the week of month of the given calendar field.
@method getWeekOfMonth
@returns {Number} the week of month for the given calendar field.
Returns the day of year of the given calendar field.
@method getDayOfYear
@returns {Number} the day of year for the given calendar field.
Returns the day of week of the given calendar field.
@method getDayOfWeek
@returns {Number} the day of week for the given calendar field.
Returns the day of week in month of the given calendar field.
@method getDayOfWeekInMonth
@returns {Number} the day of week in month for the given calendar field.
Sets the given calendar field to the given value.
@param field the given calendar field.
@param v the value to be set for the given calendar field. | [
"Returns",
"the",
"year",
"of",
"the",
"given",
"calendar",
"field",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L722-L734 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function (value, amount, min, max) {
var diff = value - min;
var range = max - min + 1;
amount %= range;
return min + (diff + amount + range) % range;
} | javascript | function (value, amount, min, max) {
var diff = value - min;
var range = max - min + 1;
amount %= range;
return min + (diff + amount + range) % range;
} | [
"function",
"(",
"value",
",",
"amount",
",",
"min",
",",
"max",
")",
"{",
"var",
"diff",
"=",
"value",
"-",
"min",
";",
"var",
"range",
"=",
"max",
"-",
"min",
"+",
"1",
";",
"amount",
"%=",
"range",
";",
"return",
"min",
"+",
"(",
"diff",
"+",
"amount",
"+",
"range",
")",
"%",
"range",
";",
"}"
] | add the year of the given calendar field.
@method addYear
@param {Number} amount the signed amount to add to field.
add the month of the given calendar field.
@method addMonth
@param {Number} amount the signed amount to add to field.
add the day of month of the given calendar field.
@method addDayOfMonth
@param {Number} amount the signed amount to add to field.
add the hour of day of the given calendar field.
@method addHourOfDay
@param {Number} amount the signed amount to add to field.
add the minute of the given calendar field.
@method addMinute
@param {Number} amount the signed amount to add to field.
add the second of the given calendar field.
@method addSecond
@param {Number} amount the signed amount to add to field.
add the millisecond of the given calendar field.
@method addMilliSecond
@param {Number} amount the signed amount to add to field.
add the week of year of the given calendar field.
@method addWeekOfYear
@param {Number} amount the signed amount to add to field.
add the week of month of the given calendar field.
@method addWeekOfMonth
@param {Number} amount the signed amount to add to field.
add the day of year of the given calendar field.
@method addDayOfYear
@param {Number} amount the signed amount to add to field.
add the day of week of the given calendar field.
@method addDayOfWeek
@param {Number} amount the signed amount to add to field.
add the day of week in month of the given calendar field.
@method addDayOfWeekInMonth
@param {Number} amount the signed amount to add to field.
Get rolled value for the field
@protected | [
"add",
"the",
"year",
"of",
"the",
"given",
"calendar",
"field",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L932-L937 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function (field, amount) {
if (!amount) {
return;
}
var self = this; // computer and retrieve original value
// computer and retrieve original value
var value = self.get(field);
var min = self.getActualMinimum(field);
var max = self.getActualMaximum(field);
value = self.getRolledValue(value, amount, min, max);
self.set(field, value); // consider compute time priority
// consider compute time priority
switch (field) {
case MONTH:
adjustDayOfMonth(self);
break;
default:
// other fields are set already when get
self.updateFieldsBySet(field);
break;
}
} | javascript | function (field, amount) {
if (!amount) {
return;
}
var self = this; // computer and retrieve original value
// computer and retrieve original value
var value = self.get(field);
var min = self.getActualMinimum(field);
var max = self.getActualMaximum(field);
value = self.getRolledValue(value, amount, min, max);
self.set(field, value); // consider compute time priority
// consider compute time priority
switch (field) {
case MONTH:
adjustDayOfMonth(self);
break;
default:
// other fields are set already when get
self.updateFieldsBySet(field);
break;
}
} | [
"function",
"(",
"field",
",",
"amount",
")",
"{",
"if",
"(",
"!",
"amount",
")",
"{",
"return",
";",
"}",
"var",
"self",
"=",
"this",
";",
"var",
"value",
"=",
"self",
".",
"get",
"(",
"field",
")",
";",
"var",
"min",
"=",
"self",
".",
"getActualMinimum",
"(",
"field",
")",
";",
"var",
"max",
"=",
"self",
".",
"getActualMaximum",
"(",
"field",
")",
";",
"value",
"=",
"self",
".",
"getRolledValue",
"(",
"value",
",",
"amount",
",",
"min",
",",
"max",
")",
";",
"self",
".",
"set",
"(",
"field",
",",
"value",
")",
";",
"switch",
"(",
"field",
")",
"{",
"case",
"MONTH",
":",
"adjustDayOfMonth",
"(",
"self",
")",
";",
"break",
";",
"default",
":",
"self",
".",
"updateFieldsBySet",
"(",
"field",
")",
";",
"break",
";",
"}",
"}"
] | Adds a signed amount to the specified calendar field without changing larger fields.
A negative roll amount means to subtract from field without changing
larger fields. If the specified amount is 0, this method performs nothing.
@example
var d = new GregorianCalendar();
d.set(1999, GregorianCalendar.AUGUST, 31);
// 1999-4-30
// Tuesday June 1, 1999
d.set(1999, GregorianCalendar.JUNE, 1);
d.add(Gregorian.WEEK_OF_MONTH,-1); // === d.add(Gregorian.WEEK_OF_MONTH,
d.get(Gregorian.WEEK_OF_MONTH));
// 1999-06-29
@param field the calendar field.
@param {Number} amount the signed amount to add to field. | [
"Adds",
"a",
"signed",
"amount",
"to",
"the",
"specified",
"calendar",
"field",
"without",
"changing",
"larger",
"fields",
".",
"A",
"negative",
"roll",
"amount",
"means",
"to",
"subtract",
"from",
"field",
"without",
"changing",
"larger",
"fields",
".",
"If",
"the",
"specified",
"amount",
"is",
"0",
"this",
"method",
"performs",
"nothing",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L959-L980 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function (field) {
var fields = this.fields;
switch (field) {
case WEEK_OF_MONTH:
fields[DAY_OF_MONTH] = undefined;
break;
case DAY_OF_YEAR:
fields[MONTH] = undefined;
break;
case DAY_OF_WEEK:
fields[DAY_OF_MONTH] = undefined;
break;
case WEEK_OF_YEAR:
fields[DAY_OF_YEAR] = undefined;
fields[MONTH] = undefined;
break;
}
} | javascript | function (field) {
var fields = this.fields;
switch (field) {
case WEEK_OF_MONTH:
fields[DAY_OF_MONTH] = undefined;
break;
case DAY_OF_YEAR:
fields[MONTH] = undefined;
break;
case DAY_OF_WEEK:
fields[DAY_OF_MONTH] = undefined;
break;
case WEEK_OF_YEAR:
fields[DAY_OF_YEAR] = undefined;
fields[MONTH] = undefined;
break;
}
} | [
"function",
"(",
"field",
")",
"{",
"var",
"fields",
"=",
"this",
".",
"fields",
";",
"switch",
"(",
"field",
")",
"{",
"case",
"WEEK_OF_MONTH",
":",
"fields",
"[",
"DAY_OF_MONTH",
"]",
"=",
"undefined",
";",
"break",
";",
"case",
"DAY_OF_YEAR",
":",
"fields",
"[",
"MONTH",
"]",
"=",
"undefined",
";",
"break",
";",
"case",
"DAY_OF_WEEK",
":",
"fields",
"[",
"DAY_OF_MONTH",
"]",
"=",
"undefined",
";",
"break",
";",
"case",
"WEEK_OF_YEAR",
":",
"fields",
"[",
"DAY_OF_YEAR",
"]",
"=",
"undefined",
";",
"fields",
"[",
"MONTH",
"]",
"=",
"undefined",
";",
"break",
";",
"}",
"}"
] | roll the year of the given calendar field.
@method rollYear
@param {Number} amount the signed amount to add to field.
roll the month of the given calendar field.
@param {Number} amount the signed amount to add to field.
@method rollMonth
roll the day of month of the given calendar field.
@method rollDayOfMonth
@param {Number} amount the signed amount to add to field.
roll the hour of day of the given calendar field.
@method rollHourOfDay
@param {Number} amount the signed amount to add to field.
roll the minute of the given calendar field.
@method rollMinute
@param {Number} amount the signed amount to add to field.
roll the second of the given calendar field.
@method rollSecond
@param {Number} amount the signed amount to add to field.
roll the millisecond of the given calendar field.
@method rollMilliSecond
@param {Number} amount the signed amount to add to field.
roll the week of year of the given calendar field.
@method rollWeekOfYear
@param {Number} amount the signed amount to add to field.
roll the week of month of the given calendar field.
@method rollWeekOfMonth
@param {Number} amount the signed amount to add to field.
roll the day of year of the given calendar field.
@method rollDayOfYear
@param {Number} amount the signed amount to add to field.
roll the day of week of the given calendar field.
@method rollDayOfWeek
@param {Number} amount the signed amount to add to field.
remove other priority fields when call getFixedDate
precondition: other fields are all set or computed
@protected | [
"roll",
"the",
"year",
"of",
"the",
"given",
"calendar",
"field",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L1041-L1058 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function () {
var weekYear = this.getWeekYear();
if (weekYear === this.get(YEAR)) {
return this.getActualMaximum(WEEK_OF_YEAR);
} // Use the 2nd week for calculating the max of WEEK_OF_YEAR
// Use the 2nd week for calculating the max of WEEK_OF_YEAR
var gc = this.clone();
gc.setWeekDate(weekYear, 2, this.get(DAY_OF_WEEK));
return gc.getActualMaximum(WEEK_OF_YEAR);
} | javascript | function () {
var weekYear = this.getWeekYear();
if (weekYear === this.get(YEAR)) {
return this.getActualMaximum(WEEK_OF_YEAR);
} // Use the 2nd week for calculating the max of WEEK_OF_YEAR
// Use the 2nd week for calculating the max of WEEK_OF_YEAR
var gc = this.clone();
gc.setWeekDate(weekYear, 2, this.get(DAY_OF_WEEK));
return gc.getActualMaximum(WEEK_OF_YEAR);
} | [
"function",
"(",
")",
"{",
"var",
"weekYear",
"=",
"this",
".",
"getWeekYear",
"(",
")",
";",
"if",
"(",
"weekYear",
"===",
"this",
".",
"get",
"(",
"YEAR",
")",
")",
"{",
"return",
"this",
".",
"getActualMaximum",
"(",
"WEEK_OF_YEAR",
")",
";",
"}",
"var",
"gc",
"=",
"this",
".",
"clone",
"(",
")",
";",
"gc",
".",
"setWeekDate",
"(",
"weekYear",
",",
"2",
",",
"this",
".",
"get",
"(",
"DAY_OF_WEEK",
")",
")",
";",
"return",
"gc",
".",
"getActualMaximum",
"(",
"WEEK_OF_YEAR",
")",
";",
"}"
] | Returns the number of weeks in the week year
represented by this GregorianCalendar.
For example, if this GregorianCalendar's date is
December 31, 2008 with the ISO
8601 compatible setting, this method will return 53 for the
period: December 29, 2008 to January 3, 2010
while getActualMaximum(WEEK_OF_YEAR) will return
52 for the period: December 31, 2007 to December 28, 2008.
@return {Number} the number of weeks in the week year. | [
"Returns",
"the",
"number",
"of",
"weeks",
"in",
"the",
"week",
"year",
"represented",
"by",
"this",
"GregorianCalendar",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L1127-L1136 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function () {
var year = this.get(YEAR); // implicitly complete
// implicitly complete
var weekOfYear = this.get(WEEK_OF_YEAR);
var month = this.get(MONTH);
if (month === GregorianCalendar.JANUARY) {
if (weekOfYear >= 52) {
--year;
}
} else if (month === GregorianCalendar.DECEMBER) {
if (weekOfYear === 1) {
++year;
}
}
return year;
} | javascript | function () {
var year = this.get(YEAR); // implicitly complete
// implicitly complete
var weekOfYear = this.get(WEEK_OF_YEAR);
var month = this.get(MONTH);
if (month === GregorianCalendar.JANUARY) {
if (weekOfYear >= 52) {
--year;
}
} else if (month === GregorianCalendar.DECEMBER) {
if (weekOfYear === 1) {
++year;
}
}
return year;
} | [
"function",
"(",
")",
"{",
"var",
"year",
"=",
"this",
".",
"get",
"(",
"YEAR",
")",
";",
"var",
"weekOfYear",
"=",
"this",
".",
"get",
"(",
"WEEK_OF_YEAR",
")",
";",
"var",
"month",
"=",
"this",
".",
"get",
"(",
"MONTH",
")",
";",
"if",
"(",
"month",
"===",
"GregorianCalendar",
".",
"JANUARY",
")",
"{",
"if",
"(",
"weekOfYear",
">=",
"52",
")",
"{",
"--",
"year",
";",
"}",
"}",
"else",
"if",
"(",
"month",
"===",
"GregorianCalendar",
".",
"DECEMBER",
")",
"{",
"if",
"(",
"weekOfYear",
"===",
"1",
")",
"{",
"++",
"year",
";",
"}",
"}",
"return",
"year",
";",
"}"
] | Returns the week year represented by this GregorianCalendar.
The dates in the weeks between 1 and the
maximum week number of the week year have the same week year value
that may be one year before or after the calendar year value.
@return {Number} the week year represented by this GregorianCalendar. | [
"Returns",
"the",
"week",
"year",
"represented",
"by",
"this",
"GregorianCalendar",
".",
"The",
"dates",
"in",
"the",
"weeks",
"between",
"1",
"and",
"the",
"maximum",
"week",
"number",
"of",
"the",
"week",
"year",
"have",
"the",
"same",
"week",
"year",
"value",
"that",
"may",
"be",
"one",
"year",
"before",
"or",
"after",
"the",
"calendar",
"year",
"value",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L1145-L1160 | train |
|
kissyteam/kissy-xtemplate | lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js | function () {
if (this.time === undefined) {
this.computeTime();
}
var cal = new GregorianCalendar(this.timezoneOffset, this.locale);
cal.setTime(this.time);
return cal;
} | javascript | function () {
if (this.time === undefined) {
this.computeTime();
}
var cal = new GregorianCalendar(this.timezoneOffset, this.locale);
cal.setTime(this.time);
return cal;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"time",
"===",
"undefined",
")",
"{",
"this",
".",
"computeTime",
"(",
")",
";",
"}",
"var",
"cal",
"=",
"new",
"GregorianCalendar",
"(",
"this",
".",
"timezoneOffset",
",",
"this",
".",
"locale",
")",
";",
"cal",
".",
"setTime",
"(",
"this",
".",
"time",
")",
";",
"return",
"cal",
";",
"}"
] | Creates and returns a copy of this object.
@returns {KISSY.Date.Gregorian} | [
"Creates",
"and",
"returns",
"a",
"copy",
"of",
"this",
"object",
"."
] | 1d454ab624c867d6a862d63dba576f8d24c6dcfc | https://github.com/kissyteam/kissy-xtemplate/blob/1d454ab624c867d6a862d63dba576f8d24c6dcfc/lib/kissy/5.0.0-alpha.3/lib/build/date/gregorian.js#L1203-L1210 | train |
|
danmilon/passbookster | lib/Pass.js | Pass | function Pass(style, fields, opts, cb) {
Stream.call(this)
// Get our own shallow copy of the fields
this.fields = _.extend({}, fields)
this.style = style
this.opts = opts
if (!this.fields[style]) {
this.fields[style] = {}
}
// Copy structure fields to style
if (this.fields.structure) {
this.fields[style] = this.fields.structure
}
// Structure no longer needed
delete this.fields.structure
// setup images and certs
this._setupImages()
this._setupCerts(opts.certs)
// Transform relevantData to ISO Date if its a Date instance
if (fields.relevantDate instanceof Date) {
fields.relavantDate = fields.relavantDate.toISOString()
}
// Validate pass fields and generate
this.validate()
this.cb = cb
process.nextTick(this._generate.bind(this))
} | javascript | function Pass(style, fields, opts, cb) {
Stream.call(this)
// Get our own shallow copy of the fields
this.fields = _.extend({}, fields)
this.style = style
this.opts = opts
if (!this.fields[style]) {
this.fields[style] = {}
}
// Copy structure fields to style
if (this.fields.structure) {
this.fields[style] = this.fields.structure
}
// Structure no longer needed
delete this.fields.structure
// setup images and certs
this._setupImages()
this._setupCerts(opts.certs)
// Transform relevantData to ISO Date if its a Date instance
if (fields.relevantDate instanceof Date) {
fields.relavantDate = fields.relavantDate.toISOString()
}
// Validate pass fields and generate
this.validate()
this.cb = cb
process.nextTick(this._generate.bind(this))
} | [
"function",
"Pass",
"(",
"style",
",",
"fields",
",",
"opts",
",",
"cb",
")",
"{",
"Stream",
".",
"call",
"(",
"this",
")",
"this",
".",
"fields",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"fields",
")",
"this",
".",
"style",
"=",
"style",
"this",
".",
"opts",
"=",
"opts",
"if",
"(",
"!",
"this",
".",
"fields",
"[",
"style",
"]",
")",
"{",
"this",
".",
"fields",
"[",
"style",
"]",
"=",
"{",
"}",
"}",
"if",
"(",
"this",
".",
"fields",
".",
"structure",
")",
"{",
"this",
".",
"fields",
"[",
"style",
"]",
"=",
"this",
".",
"fields",
".",
"structure",
"}",
"delete",
"this",
".",
"fields",
".",
"structure",
"this",
".",
"_setupImages",
"(",
")",
"this",
".",
"_setupCerts",
"(",
"opts",
".",
"certs",
")",
"if",
"(",
"fields",
".",
"relevantDate",
"instanceof",
"Date",
")",
"{",
"fields",
".",
"relavantDate",
"=",
"fields",
".",
"relavantDate",
".",
"toISOString",
"(",
")",
"}",
"this",
".",
"validate",
"(",
")",
"this",
".",
"cb",
"=",
"cb",
"process",
".",
"nextTick",
"(",
"this",
".",
"_generate",
".",
"bind",
"(",
"this",
")",
")",
"}"
] | Generates a pass over a streaming interface or optionally a callback
@param {String} style Style of the pass
@param {Object} fields Pass fields
@param {Object} opts Extra options
@param {Function} cb Callback function | [
"Generates",
"a",
"pass",
"over",
"a",
"streaming",
"interface",
"or",
"optionally",
"a",
"callback"
] | 92d8140b5c9d3b6db31e32a8c2ae17a7b56c8490 | https://github.com/danmilon/passbookster/blob/92d8140b5c9d3b6db31e32a8c2ae17a7b56c8490/lib/Pass.js#L21-L54 | train |
enmasseio/hypertimer | lib/synchronization/slave.js | sync | function sync() {
// retrieve latency, then wait 1 sec
function getLatencyAndWait() {
var result = null;
if (isDestroyed) {
return Promise.resolve(result);
}
return getLatency(slave)
.then(function (latency) { result = latency }) // store the retrieved latency
.catch(function (err) { console.log(err) }) // just log failed requests
.then(function () { return util.wait(DELAY) }) // wait 1 sec
.then(function () { return result}); // return the retrieved latency
}
return util
.repeat(getLatencyAndWait, REPEAT)
.then(function (all) {
debug('latencies', all);
// filter away failed requests
var latencies = all.filter(function (latency) {
return latency !== null;
});
// calculate the limit for outliers
var limit = stat.median(latencies) + stat.std(latencies);
// filter away outliers: all latencies largereq than the mean+std
var filtered = latencies.filter(function (latency) {
return latency < limit;
});
// return the mean latency
return (filtered.length > 0) ? stat.mean(filtered) : null;
})
.then(function (latency) {
if (isDestroyed) {
return Promise.resolve(null);
}
else {
return slave.request('time').then(function (timestamp) {
var time = timestamp + latency;
slave.emit('change', time);
return time;
});
}
})
.catch(function (err) {
slave.emit('error', err)
});
} | javascript | function sync() {
// retrieve latency, then wait 1 sec
function getLatencyAndWait() {
var result = null;
if (isDestroyed) {
return Promise.resolve(result);
}
return getLatency(slave)
.then(function (latency) { result = latency }) // store the retrieved latency
.catch(function (err) { console.log(err) }) // just log failed requests
.then(function () { return util.wait(DELAY) }) // wait 1 sec
.then(function () { return result}); // return the retrieved latency
}
return util
.repeat(getLatencyAndWait, REPEAT)
.then(function (all) {
debug('latencies', all);
// filter away failed requests
var latencies = all.filter(function (latency) {
return latency !== null;
});
// calculate the limit for outliers
var limit = stat.median(latencies) + stat.std(latencies);
// filter away outliers: all latencies largereq than the mean+std
var filtered = latencies.filter(function (latency) {
return latency < limit;
});
// return the mean latency
return (filtered.length > 0) ? stat.mean(filtered) : null;
})
.then(function (latency) {
if (isDestroyed) {
return Promise.resolve(null);
}
else {
return slave.request('time').then(function (timestamp) {
var time = timestamp + latency;
slave.emit('change', time);
return time;
});
}
})
.catch(function (err) {
slave.emit('error', err)
});
} | [
"function",
"sync",
"(",
")",
"{",
"function",
"getLatencyAndWait",
"(",
")",
"{",
"var",
"result",
"=",
"null",
";",
"if",
"(",
"isDestroyed",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"return",
"getLatency",
"(",
"slave",
")",
".",
"then",
"(",
"function",
"(",
"latency",
")",
"{",
"result",
"=",
"latency",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"util",
".",
"wait",
"(",
"DELAY",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"result",
"}",
")",
";",
"}",
"return",
"util",
".",
"repeat",
"(",
"getLatencyAndWait",
",",
"REPEAT",
")",
".",
"then",
"(",
"function",
"(",
"all",
")",
"{",
"debug",
"(",
"'latencies'",
",",
"all",
")",
";",
"var",
"latencies",
"=",
"all",
".",
"filter",
"(",
"function",
"(",
"latency",
")",
"{",
"return",
"latency",
"!==",
"null",
";",
"}",
")",
";",
"var",
"limit",
"=",
"stat",
".",
"median",
"(",
"latencies",
")",
"+",
"stat",
".",
"std",
"(",
"latencies",
")",
";",
"var",
"filtered",
"=",
"latencies",
".",
"filter",
"(",
"function",
"(",
"latency",
")",
"{",
"return",
"latency",
"<",
"limit",
";",
"}",
")",
";",
"return",
"(",
"filtered",
".",
"length",
">",
"0",
")",
"?",
"stat",
".",
"mean",
"(",
"filtered",
")",
":",
"null",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"latency",
")",
"{",
"if",
"(",
"isDestroyed",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"null",
")",
";",
"}",
"else",
"{",
"return",
"slave",
".",
"request",
"(",
"'time'",
")",
".",
"then",
"(",
"function",
"(",
"timestamp",
")",
"{",
"var",
"time",
"=",
"timestamp",
"+",
"latency",
";",
"slave",
".",
"emit",
"(",
"'change'",
",",
"time",
")",
";",
"return",
"time",
";",
"}",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"slave",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
")",
";",
"}"
] | Sync with the time of the master. Emits a 'change' message
@private | [
"Sync",
"with",
"the",
"time",
"of",
"the",
"master",
".",
"Emits",
"a",
"change",
"message"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/synchronization/slave.js#L41-L93 | train |
enmasseio/hypertimer | lib/synchronization/slave.js | getLatencyAndWait | function getLatencyAndWait() {
var result = null;
if (isDestroyed) {
return Promise.resolve(result);
}
return getLatency(slave)
.then(function (latency) { result = latency }) // store the retrieved latency
.catch(function (err) { console.log(err) }) // just log failed requests
.then(function () { return util.wait(DELAY) }) // wait 1 sec
.then(function () { return result}); // return the retrieved latency
} | javascript | function getLatencyAndWait() {
var result = null;
if (isDestroyed) {
return Promise.resolve(result);
}
return getLatency(slave)
.then(function (latency) { result = latency }) // store the retrieved latency
.catch(function (err) { console.log(err) }) // just log failed requests
.then(function () { return util.wait(DELAY) }) // wait 1 sec
.then(function () { return result}); // return the retrieved latency
} | [
"function",
"getLatencyAndWait",
"(",
")",
"{",
"var",
"result",
"=",
"null",
";",
"if",
"(",
"isDestroyed",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
";",
"}",
"return",
"getLatency",
"(",
"slave",
")",
".",
"then",
"(",
"function",
"(",
"latency",
")",
"{",
"result",
"=",
"latency",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"util",
".",
"wait",
"(",
"DELAY",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"result",
"}",
")",
";",
"}"
] | retrieve latency, then wait 1 sec | [
"retrieve",
"latency",
"then",
"wait",
"1",
"sec"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/synchronization/slave.js#L43-L55 | train |
enmasseio/hypertimer | lib/synchronization/slave.js | getLatency | function getLatency(emitter) {
var start = Date.now();
return emitter.request('time')
.then(function (timestamp) {
var end = Date.now();
var latency = (end - start) / 2;
var time = timestamp + latency;
// apply the first ever retrieved offset immediately.
if (isFirst) {
isFirst = false;
emitter.emit('change', time);
}
return latency;
})
} | javascript | function getLatency(emitter) {
var start = Date.now();
return emitter.request('time')
.then(function (timestamp) {
var end = Date.now();
var latency = (end - start) / 2;
var time = timestamp + latency;
// apply the first ever retrieved offset immediately.
if (isFirst) {
isFirst = false;
emitter.emit('change', time);
}
return latency;
})
} | [
"function",
"getLatency",
"(",
"emitter",
")",
"{",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"return",
"emitter",
".",
"request",
"(",
"'time'",
")",
".",
"then",
"(",
"function",
"(",
"timestamp",
")",
"{",
"var",
"end",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"latency",
"=",
"(",
"end",
"-",
"start",
")",
"/",
"2",
";",
"var",
"time",
"=",
"timestamp",
"+",
"latency",
";",
"if",
"(",
"isFirst",
")",
"{",
"isFirst",
"=",
"false",
";",
"emitter",
".",
"emit",
"(",
"'change'",
",",
"time",
")",
";",
"}",
"return",
"latency",
";",
"}",
")",
"}"
] | Request the time of the master and calculate the latency from the
roundtrip time
@param {{request: function}} emitter
@returns {Promise.<number | null>} returns the latency
@private | [
"Request",
"the",
"time",
"of",
"the",
"master",
"and",
"calculate",
"the",
"latency",
"from",
"the",
"roundtrip",
"time"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/synchronization/slave.js#L102-L119 | train |
rymizuki/node-hariko | lib/hariko-parser/structure/index.js | build | function build(data) {
const resources = resources_1.ResourcesStructure.create();
const annotations = annotations_1.AnnotationsStructure.create();
data.content[0].content.forEach((content) => {
if (content.element === 'annotation') {
annotations.add(content.content);
return;
}
const resource = resources.createResource(content.attributes.href.content);
content.content.forEach((transition_data) => {
const transition = resource.createTransition(transition_data);
transition_data.content.forEach((http_transaction_data) => {
const http_transaction = transition.createHttpTransaction();
http_transaction.setHttpRequest(http_transaction.createHttpRequest(http_transaction_data.content[0]));
http_transaction.setHttpResponse(http_transaction.createHttpResponse(http_transaction_data.content[1]));
transition.addHttpTransaction(http_transaction);
});
resource.addTransition(transition);
});
resources.add(resource);
});
return resources;
} | javascript | function build(data) {
const resources = resources_1.ResourcesStructure.create();
const annotations = annotations_1.AnnotationsStructure.create();
data.content[0].content.forEach((content) => {
if (content.element === 'annotation') {
annotations.add(content.content);
return;
}
const resource = resources.createResource(content.attributes.href.content);
content.content.forEach((transition_data) => {
const transition = resource.createTransition(transition_data);
transition_data.content.forEach((http_transaction_data) => {
const http_transaction = transition.createHttpTransaction();
http_transaction.setHttpRequest(http_transaction.createHttpRequest(http_transaction_data.content[0]));
http_transaction.setHttpResponse(http_transaction.createHttpResponse(http_transaction_data.content[1]));
transition.addHttpTransaction(http_transaction);
});
resource.addTransition(transition);
});
resources.add(resource);
});
return resources;
} | [
"function",
"build",
"(",
"data",
")",
"{",
"const",
"resources",
"=",
"resources_1",
".",
"ResourcesStructure",
".",
"create",
"(",
")",
";",
"const",
"annotations",
"=",
"annotations_1",
".",
"AnnotationsStructure",
".",
"create",
"(",
")",
";",
"data",
".",
"content",
"[",
"0",
"]",
".",
"content",
".",
"forEach",
"(",
"(",
"content",
")",
"=>",
"{",
"if",
"(",
"content",
".",
"element",
"===",
"'annotation'",
")",
"{",
"annotations",
".",
"add",
"(",
"content",
".",
"content",
")",
";",
"return",
";",
"}",
"const",
"resource",
"=",
"resources",
".",
"createResource",
"(",
"content",
".",
"attributes",
".",
"href",
".",
"content",
")",
";",
"content",
".",
"content",
".",
"forEach",
"(",
"(",
"transition_data",
")",
"=>",
"{",
"const",
"transition",
"=",
"resource",
".",
"createTransition",
"(",
"transition_data",
")",
";",
"transition_data",
".",
"content",
".",
"forEach",
"(",
"(",
"http_transaction_data",
")",
"=>",
"{",
"const",
"http_transaction",
"=",
"transition",
".",
"createHttpTransaction",
"(",
")",
";",
"http_transaction",
".",
"setHttpRequest",
"(",
"http_transaction",
".",
"createHttpRequest",
"(",
"http_transaction_data",
".",
"content",
"[",
"0",
"]",
")",
")",
";",
"http_transaction",
".",
"setHttpResponse",
"(",
"http_transaction",
".",
"createHttpResponse",
"(",
"http_transaction_data",
".",
"content",
"[",
"1",
"]",
")",
")",
";",
"transition",
".",
"addHttpTransaction",
"(",
"http_transaction",
")",
";",
"}",
")",
";",
"resource",
".",
"addTransition",
"(",
"transition",
")",
";",
"}",
")",
";",
"resources",
".",
"add",
"(",
"resource",
")",
";",
"}",
")",
";",
"return",
"resources",
";",
"}"
] | Convert protagonist's parsing result to hariko's structure
@param data ProtagonistParseResult | [
"Convert",
"protagonist",
"s",
"parsing",
"result",
"to",
"hariko",
"s",
"structure"
] | 5668f832fb80ed1e20898f1b98d74672e46e1a1f | https://github.com/rymizuki/node-hariko/blob/5668f832fb80ed1e20898f1b98d74672e46e1a1f/lib/hariko-parser/structure/index.js#L9-L31 | train |
keymetrics/trassingue | src/logger.js | Logger | function Logger (level, name) {
if (name) {
debug = require('debug')(typeof name === 'string' ? name : 'vxx');
}
this.level = level;
this.debug('Logger started');
} | javascript | function Logger (level, name) {
if (name) {
debug = require('debug')(typeof name === 'string' ? name : 'vxx');
}
this.level = level;
this.debug('Logger started');
} | [
"function",
"Logger",
"(",
"level",
",",
"name",
")",
"{",
"if",
"(",
"name",
")",
"{",
"debug",
"=",
"require",
"(",
"'debug'",
")",
"(",
"typeof",
"name",
"===",
"'string'",
"?",
"name",
":",
"'vxx'",
")",
";",
"}",
"this",
".",
"level",
"=",
"level",
";",
"this",
".",
"debug",
"(",
"'Logger started'",
")",
";",
"}"
] | Creates a logger object.
@constructor | [
"Creates",
"a",
"logger",
"object",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/logger.js#L26-L32 | train |
jldec/pub-server | server/handle-errors.js | error | function error(status, req, res, msg) {
debug('%s %s', status, req.originalUrl);
msg = msg || '';
var page = generator.page$['/' + status];
// 404 with no matching status page => redirect to home
if (!page && status === 404) {
if (generator.home) return res.redirect(302, '/');
if (server.statics.defaultFile) return res.redirect(302, server.statics.defaultFile);
}
// avoid exposing error pages unless authorized
if (page) {
if (!server.isPageAuthorized || !server.isPageAuthorized(req, page)) {
if (server.login) return server.login(req, res);
else page = null;
}
}
if (!page) return res.status(status).send(u.escape(msg));
res.status(status).send(
generator.renderDoc(page)
.replace(/%s/g, u.escape(msg)) // TODO - replace with humane.js or proper template
.replace('<body', '<body data-err-status="' + status + '"' + (msg ? ' data-err-msg="' + u.escape(msg) + '"' : ''))
);
} | javascript | function error(status, req, res, msg) {
debug('%s %s', status, req.originalUrl);
msg = msg || '';
var page = generator.page$['/' + status];
// 404 with no matching status page => redirect to home
if (!page && status === 404) {
if (generator.home) return res.redirect(302, '/');
if (server.statics.defaultFile) return res.redirect(302, server.statics.defaultFile);
}
// avoid exposing error pages unless authorized
if (page) {
if (!server.isPageAuthorized || !server.isPageAuthorized(req, page)) {
if (server.login) return server.login(req, res);
else page = null;
}
}
if (!page) return res.status(status).send(u.escape(msg));
res.status(status).send(
generator.renderDoc(page)
.replace(/%s/g, u.escape(msg)) // TODO - replace with humane.js or proper template
.replace('<body', '<body data-err-status="' + status + '"' + (msg ? ' data-err-msg="' + u.escape(msg) + '"' : ''))
);
} | [
"function",
"error",
"(",
"status",
",",
"req",
",",
"res",
",",
"msg",
")",
"{",
"debug",
"(",
"'%s %s'",
",",
"status",
",",
"req",
".",
"originalUrl",
")",
";",
"msg",
"=",
"msg",
"||",
"''",
";",
"var",
"page",
"=",
"generator",
".",
"page$",
"[",
"'/'",
"+",
"status",
"]",
";",
"if",
"(",
"!",
"page",
"&&",
"status",
"===",
"404",
")",
"{",
"if",
"(",
"generator",
".",
"home",
")",
"return",
"res",
".",
"redirect",
"(",
"302",
",",
"'/'",
")",
";",
"if",
"(",
"server",
".",
"statics",
".",
"defaultFile",
")",
"return",
"res",
".",
"redirect",
"(",
"302",
",",
"server",
".",
"statics",
".",
"defaultFile",
")",
";",
"}",
"if",
"(",
"page",
")",
"{",
"if",
"(",
"!",
"server",
".",
"isPageAuthorized",
"||",
"!",
"server",
".",
"isPageAuthorized",
"(",
"req",
",",
"page",
")",
")",
"{",
"if",
"(",
"server",
".",
"login",
")",
"return",
"server",
".",
"login",
"(",
"req",
",",
"res",
")",
";",
"else",
"page",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"!",
"page",
")",
"return",
"res",
".",
"status",
"(",
"status",
")",
".",
"send",
"(",
"u",
".",
"escape",
"(",
"msg",
")",
")",
";",
"res",
".",
"status",
"(",
"status",
")",
".",
"send",
"(",
"generator",
".",
"renderDoc",
"(",
"page",
")",
".",
"replace",
"(",
"/",
"%s",
"/",
"g",
",",
"u",
".",
"escape",
"(",
"msg",
")",
")",
".",
"replace",
"(",
"'<body'",
",",
"'<body data-err-status=\"'",
"+",
"status",
"+",
"'\"'",
"+",
"(",
"msg",
"?",
"' data-err-msg=\"'",
"+",
"u",
".",
"escape",
"(",
"msg",
")",
"+",
"'\"'",
":",
"''",
")",
")",
")",
";",
"}"
] | general purpose error response | [
"general",
"purpose",
"error",
"response"
] | 2e11d2377cf5a0b31ca7fdcef78a433d0c4885df | https://github.com/jldec/pub-server/blob/2e11d2377cf5a0b31ca7fdcef78a433d0c4885df/server/handle-errors.js#L60-L87 | train |
realtime-framework/RealtimeMessaging-Javascript | ortc.js | function(frame) {
if (script2) {
script2.parentNode.removeChild(script2);
script2 = null;
}
if (script) {
clearTimeout(tref);
script.parentNode.removeChild(script);
script.onreadystatechange = script.onerror =
script.onload = script.onclick = null;
script = null;
callback(frame);
callback = null;
}
} | javascript | function(frame) {
if (script2) {
script2.parentNode.removeChild(script2);
script2 = null;
}
if (script) {
clearTimeout(tref);
script.parentNode.removeChild(script);
script.onreadystatechange = script.onerror =
script.onload = script.onclick = null;
script = null;
callback(frame);
callback = null;
}
} | [
"function",
"(",
"frame",
")",
"{",
"if",
"(",
"script2",
")",
"{",
"script2",
".",
"parentNode",
".",
"removeChild",
"(",
"script2",
")",
";",
"script2",
"=",
"null",
";",
"}",
"if",
"(",
"script",
")",
"{",
"clearTimeout",
"(",
"tref",
")",
";",
"script",
".",
"parentNode",
".",
"removeChild",
"(",
"script",
")",
";",
"script",
".",
"onreadystatechange",
"=",
"script",
".",
"onerror",
"=",
"script",
".",
"onload",
"=",
"script",
".",
"onclick",
"=",
"null",
";",
"script",
"=",
"null",
";",
"callback",
"(",
"frame",
")",
";",
"callback",
"=",
"null",
";",
"}",
"}"
] | Opera synchronous load trick. | [
"Opera",
"synchronous",
"load",
"trick",
"."
] | 0a13dbd1457e77783aa043a3ff411408bbd097ed | https://github.com/realtime-framework/RealtimeMessaging-Javascript/blob/0a13dbd1457e77783aa043a3ff411408bbd097ed/ortc.js#L1527-L1541 | train |
|
realtime-framework/RealtimeMessaging-Javascript | ortc.js | function(url, constructReceiver, user_callback) {
var id = 'a' + utils.random_string(6);
var url_id = url + '?c=' + escape(WPrefix + '.' + id);
// Callback will be called exactly once.
var callback = function(frame) {
delete _window[WPrefix][id];
user_callback(frame);
};
var close_script = constructReceiver(url_id, callback);
_window[WPrefix][id] = close_script;
var stop = function() {
if (_window[WPrefix][id]) {
_window[WPrefix][id](utils.closeFrame(1000, "JSONP user aborted read"));
}
};
return stop;
} | javascript | function(url, constructReceiver, user_callback) {
var id = 'a' + utils.random_string(6);
var url_id = url + '?c=' + escape(WPrefix + '.' + id);
// Callback will be called exactly once.
var callback = function(frame) {
delete _window[WPrefix][id];
user_callback(frame);
};
var close_script = constructReceiver(url_id, callback);
_window[WPrefix][id] = close_script;
var stop = function() {
if (_window[WPrefix][id]) {
_window[WPrefix][id](utils.closeFrame(1000, "JSONP user aborted read"));
}
};
return stop;
} | [
"function",
"(",
"url",
",",
"constructReceiver",
",",
"user_callback",
")",
"{",
"var",
"id",
"=",
"'a'",
"+",
"utils",
".",
"random_string",
"(",
"6",
")",
";",
"var",
"url_id",
"=",
"url",
"+",
"'?c='",
"+",
"escape",
"(",
"WPrefix",
"+",
"'.'",
"+",
"id",
")",
";",
"var",
"callback",
"=",
"function",
"(",
"frame",
")",
"{",
"delete",
"_window",
"[",
"WPrefix",
"]",
"[",
"id",
"]",
";",
"user_callback",
"(",
"frame",
")",
";",
"}",
";",
"var",
"close_script",
"=",
"constructReceiver",
"(",
"url_id",
",",
"callback",
")",
";",
"_window",
"[",
"WPrefix",
"]",
"[",
"id",
"]",
"=",
"close_script",
";",
"var",
"stop",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"_window",
"[",
"WPrefix",
"]",
"[",
"id",
"]",
")",
"{",
"_window",
"[",
"WPrefix",
"]",
"[",
"id",
"]",
"(",
"utils",
".",
"closeFrame",
"(",
"1000",
",",
"\"JSONP user aborted read\"",
")",
")",
";",
"}",
"}",
";",
"return",
"stop",
";",
"}"
] | Abstract away code that handles global namespace pollution. | [
"Abstract",
"away",
"code",
"that",
"handles",
"global",
"namespace",
"pollution",
"."
] | 0a13dbd1457e77783aa043a3ff411408bbd097ed | https://github.com/realtime-framework/RealtimeMessaging-Javascript/blob/0a13dbd1457e77783aa043a3ff411408bbd097ed/ortc.js#L1696-L1713 | train |
|
racker/node-zookeeper-client | lib/client.js | wrapWorkAndCallback | function wrapWorkAndCallback(work, callback) {
return function(err) {
work.stop(err);
callback.apply(this, arguments);
};
} | javascript | function wrapWorkAndCallback(work, callback) {
return function(err) {
work.stop(err);
callback.apply(this, arguments);
};
} | [
"function",
"wrapWorkAndCallback",
"(",
"work",
",",
"callback",
")",
"{",
"return",
"function",
"(",
"err",
")",
"{",
"work",
".",
"stop",
"(",
"err",
")",
";",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] | Returns back a function that wraps the original callback.
@param {Work} work object that needs to be stopped.
@param {Function} callback invoked in lock acquistion.
@return {Function} wrapper function that encompasses original callback. | [
"Returns",
"back",
"a",
"function",
"that",
"wraps",
"the",
"original",
"callback",
"."
] | 658fd4900c4d1f410cd8522487a6a75e7dd25f9c | https://github.com/racker/node-zookeeper-client/blob/658fd4900c4d1f410cd8522487a6a75e7dd25f9c/lib/client.js#L474-L479 | train |
racker/node-zookeeper-client | lib/client.js | function(reaped) {
childCount += 1;
if (reaped) {
self.options.log.trace1('Incrementing reapCount', {current: reapCount});
reapCount += 1;
}
if (childCount >= children.length) {
cbWrapper(function() {
callback(null, reapCount);
});
}
} | javascript | function(reaped) {
childCount += 1;
if (reaped) {
self.options.log.trace1('Incrementing reapCount', {current: reapCount});
reapCount += 1;
}
if (childCount >= children.length) {
cbWrapper(function() {
callback(null, reapCount);
});
}
} | [
"function",
"(",
"reaped",
")",
"{",
"childCount",
"+=",
"1",
";",
"if",
"(",
"reaped",
")",
"{",
"self",
".",
"options",
".",
"log",
".",
"trace1",
"(",
"'Incrementing reapCount'",
",",
"{",
"current",
":",
"reapCount",
"}",
")",
";",
"reapCount",
"+=",
"1",
";",
"}",
"if",
"(",
"childCount",
">=",
"children",
".",
"length",
")",
"{",
"cbWrapper",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"null",
",",
"reapCount",
")",
";",
"}",
")",
";",
"}",
"}"
] | for each child, do a get. | [
"for",
"each",
"child",
"do",
"a",
"get",
"."
] | 658fd4900c4d1f410cd8522487a6a75e7dd25f9c | https://github.com/racker/node-zookeeper-client/blob/658fd4900c4d1f410cd8522487a6a75e7dd25f9c/lib/client.js#L601-L612 | train |
|
andjosh/mongo-throttle | lib/throttler.js | throttleMiddleware | function throttleMiddleware (request, response, next) {
var ip = null
if (config.useCustomHeader && request.headers[config.useCustomHeader]) {
ip = request.headers[config.useCustomHeader]
} else {
ip = request.headers['x-forwarded-for'] ||
request.connection.remoteAddress ||
request.socket.remoteAddress ||
request.connection.socket.remoteAddress || ''
ip = ip.split(',')[0]
if (!ipRegex().test(ip) || ip.substr(0, 7) === '::ffff:' || ip === '::1') {
ip = '127.0.0.1'
} else {
ip = ip.match(ipRegex())[0]
}
}
Throttle
.findOneAndUpdate({ip: ip}, { $inc: { hits: 1 } }, { upsert: false })
.exec(function (error, throttle) {
if (errHandler(response, next, error)) { return }
if (!throttle) {
throttle = new Throttle({
createdAt: new Date(),
ip: ip
})
throttle.save(function (error, throttle) {
// THERE'S NO ERROR, BUT THROTTLE WAS NOT SAVE
if (!throttle && !error) {
error = new Error('Error checking rate limit.')
}
if (errHandler(response, next, error)) { return }
respondWithThrottle(request, response, next, throttle)
})
} else {
respondWithThrottle(request, response, next, throttle)
}
})
} | javascript | function throttleMiddleware (request, response, next) {
var ip = null
if (config.useCustomHeader && request.headers[config.useCustomHeader]) {
ip = request.headers[config.useCustomHeader]
} else {
ip = request.headers['x-forwarded-for'] ||
request.connection.remoteAddress ||
request.socket.remoteAddress ||
request.connection.socket.remoteAddress || ''
ip = ip.split(',')[0]
if (!ipRegex().test(ip) || ip.substr(0, 7) === '::ffff:' || ip === '::1') {
ip = '127.0.0.1'
} else {
ip = ip.match(ipRegex())[0]
}
}
Throttle
.findOneAndUpdate({ip: ip}, { $inc: { hits: 1 } }, { upsert: false })
.exec(function (error, throttle) {
if (errHandler(response, next, error)) { return }
if (!throttle) {
throttle = new Throttle({
createdAt: new Date(),
ip: ip
})
throttle.save(function (error, throttle) {
// THERE'S NO ERROR, BUT THROTTLE WAS NOT SAVE
if (!throttle && !error) {
error = new Error('Error checking rate limit.')
}
if (errHandler(response, next, error)) { return }
respondWithThrottle(request, response, next, throttle)
})
} else {
respondWithThrottle(request, response, next, throttle)
}
})
} | [
"function",
"throttleMiddleware",
"(",
"request",
",",
"response",
",",
"next",
")",
"{",
"var",
"ip",
"=",
"null",
"if",
"(",
"config",
".",
"useCustomHeader",
"&&",
"request",
".",
"headers",
"[",
"config",
".",
"useCustomHeader",
"]",
")",
"{",
"ip",
"=",
"request",
".",
"headers",
"[",
"config",
".",
"useCustomHeader",
"]",
"}",
"else",
"{",
"ip",
"=",
"request",
".",
"headers",
"[",
"'x-forwarded-for'",
"]",
"||",
"request",
".",
"connection",
".",
"remoteAddress",
"||",
"request",
".",
"socket",
".",
"remoteAddress",
"||",
"request",
".",
"connection",
".",
"socket",
".",
"remoteAddress",
"||",
"''",
"ip",
"=",
"ip",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
"if",
"(",
"!",
"ipRegex",
"(",
")",
".",
"test",
"(",
"ip",
")",
"||",
"ip",
".",
"substr",
"(",
"0",
",",
"7",
")",
"===",
"'::ffff:'",
"||",
"ip",
"===",
"'::1'",
")",
"{",
"ip",
"=",
"'127.0.0.1'",
"}",
"else",
"{",
"ip",
"=",
"ip",
".",
"match",
"(",
"ipRegex",
"(",
")",
")",
"[",
"0",
"]",
"}",
"}",
"Throttle",
".",
"findOneAndUpdate",
"(",
"{",
"ip",
":",
"ip",
"}",
",",
"{",
"$inc",
":",
"{",
"hits",
":",
"1",
"}",
"}",
",",
"{",
"upsert",
":",
"false",
"}",
")",
".",
"exec",
"(",
"function",
"(",
"error",
",",
"throttle",
")",
"{",
"if",
"(",
"errHandler",
"(",
"response",
",",
"next",
",",
"error",
")",
")",
"{",
"return",
"}",
"if",
"(",
"!",
"throttle",
")",
"{",
"throttle",
"=",
"new",
"Throttle",
"(",
"{",
"createdAt",
":",
"new",
"Date",
"(",
")",
",",
"ip",
":",
"ip",
"}",
")",
"throttle",
".",
"save",
"(",
"function",
"(",
"error",
",",
"throttle",
")",
"{",
"if",
"(",
"!",
"throttle",
"&&",
"!",
"error",
")",
"{",
"error",
"=",
"new",
"Error",
"(",
"'Error checking rate limit.'",
")",
"}",
"if",
"(",
"errHandler",
"(",
"response",
",",
"next",
",",
"error",
")",
")",
"{",
"return",
"}",
"respondWithThrottle",
"(",
"request",
",",
"response",
",",
"next",
",",
"throttle",
")",
"}",
")",
"}",
"else",
"{",
"respondWithThrottle",
"(",
"request",
",",
"response",
",",
"next",
",",
"throttle",
")",
"}",
"}",
")",
"}"
] | Check for request limit on the requesting IP
@access public
@param {object} request Express-style request
@param {object} response Express-style response
@param {function} next Express-style next callback | [
"Check",
"for",
"request",
"limit",
"on",
"the",
"requesting",
"IP"
] | 8bb6a488b3a246379b5a4a77b330b68e0ed5375a | https://github.com/andjosh/mongo-throttle/blob/8bb6a488b3a246379b5a4a77b330b68e0ed5375a/lib/throttler.js#L75-L117 | train |
enmasseio/hypertimer | lib/synchronization/socket-emitter.js | send | function send (event, data) {
var envelope = {
event: event,
data: data
};
debug('send', envelope);
socket.send(JSON.stringify(envelope));
} | javascript | function send (event, data) {
var envelope = {
event: event,
data: data
};
debug('send', envelope);
socket.send(JSON.stringify(envelope));
} | [
"function",
"send",
"(",
"event",
",",
"data",
")",
"{",
"var",
"envelope",
"=",
"{",
"event",
":",
"event",
",",
"data",
":",
"data",
"}",
";",
"debug",
"(",
"'send'",
",",
"envelope",
")",
";",
"socket",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"envelope",
")",
")",
";",
"}"
] | Send an event
@param {string} event
@param {*} data | [
"Send",
"an",
"event"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/synchronization/socket-emitter.js#L21-L28 | train |
enmasseio/hypertimer | lib/synchronization/socket-emitter.js | request | function request (event, data) {
return new Promise(function (resolve, reject) {
// put the data in an envelope with id
var id = getId();
var envelope = {
event: event,
id: id,
data: data
};
// add the request to the list with requests in progress
queue[id] = {
resolve: resolve,
reject: reject,
timeout: setTimeout(function () {
delete queue[id];
reject(new Error('Timeout'));
}, TIMEOUT)
};
debug('request', envelope);
socket.send(JSON.stringify(envelope));
}).catch(function (err) {console.log('ERROR', err)});
} | javascript | function request (event, data) {
return new Promise(function (resolve, reject) {
// put the data in an envelope with id
var id = getId();
var envelope = {
event: event,
id: id,
data: data
};
// add the request to the list with requests in progress
queue[id] = {
resolve: resolve,
reject: reject,
timeout: setTimeout(function () {
delete queue[id];
reject(new Error('Timeout'));
}, TIMEOUT)
};
debug('request', envelope);
socket.send(JSON.stringify(envelope));
}).catch(function (err) {console.log('ERROR', err)});
} | [
"function",
"request",
"(",
"event",
",",
"data",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"id",
"=",
"getId",
"(",
")",
";",
"var",
"envelope",
"=",
"{",
"event",
":",
"event",
",",
"id",
":",
"id",
",",
"data",
":",
"data",
"}",
";",
"queue",
"[",
"id",
"]",
"=",
"{",
"resolve",
":",
"resolve",
",",
"reject",
":",
"reject",
",",
"timeout",
":",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"delete",
"queue",
"[",
"id",
"]",
";",
"reject",
"(",
"new",
"Error",
"(",
"'Timeout'",
")",
")",
";",
"}",
",",
"TIMEOUT",
")",
"}",
";",
"debug",
"(",
"'request'",
",",
"envelope",
")",
";",
"socket",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"envelope",
")",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'ERROR'",
",",
"err",
")",
"}",
")",
";",
"}"
] | Request an event, await a response
@param {string} event
@param {*} data
@return {Promise} Returns a promise which resolves with the reply | [
"Request",
"an",
"event",
"await",
"a",
"response"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/synchronization/socket-emitter.js#L36-L59 | train |
pnevyk/tipograph | scripts/readme.js | dummyMarkdown | function dummyMarkdown() {
var codeBlock = /^```/;
var quoteBlock = /^>/;
var listBlock = /^\* /;
var commentInline = '<!--.*-->';
var codeInline = '`.+`';
function split(content) {
var pattern = new RegExp([commentInline, codeInline].join('|'), 'g');
var result = null;
var last = 0;
var output = [];
while ((result = pattern.exec(content)) !== null) {
output.push({ transform: true, content: content.slice(last, result.index)});
output.push({ transform: false, content: result[0]});
last = pattern.lastIndex;
}
output.push({ transform: true, content: content.slice(last)});
return output;
}
return function (input) {
var output = [];
var lines = input.split('\n');
for (var l = 0; l < lines.length; l++) {
var line = lines[l];
var e;
var content;
if (codeBlock.test(line)) {
e = l + 1;
while (!codeBlock.test(lines[e])) {
e++;
}
output.push({ transform: false, content: lines.slice(l, e + 1).join('\n') + '\n\n' });
l = e;
} else if (quoteBlock.test(line)) {
e = l + 1;
while (quoteBlock.test(lines[e])) {
e++;
}
content = [line].concat(lines.slice(l + 1, e).map(function (nextLine) {
return nextLine.slice(2);
})).join(' ') + '\n\n';
output = output.concat(split(content));
l = e - 1;
} else if (listBlock.test(line)) {
e = l + 1;
while (lines[e] !== '') {
if (!listBlock.test(lines[e])) {
lines[e - 1] += ' ' + lines[e];
lines[e] = '';
}
e++;
}
content = lines.slice(l, e).filter(function (line) {
return line !== '';
}).join('\n') + '\n';
output = output.concat(split(content));
l = e - 1;
} else if (line !== '') {
e = l + 1;
while (lines[e] !== '') {
e++;
}
content = lines.slice(l, e).join(' ') + '\n\n';
output = output.concat(split(content));
l = e - 1;
}
}
return output;
};
} | javascript | function dummyMarkdown() {
var codeBlock = /^```/;
var quoteBlock = /^>/;
var listBlock = /^\* /;
var commentInline = '<!--.*-->';
var codeInline = '`.+`';
function split(content) {
var pattern = new RegExp([commentInline, codeInline].join('|'), 'g');
var result = null;
var last = 0;
var output = [];
while ((result = pattern.exec(content)) !== null) {
output.push({ transform: true, content: content.slice(last, result.index)});
output.push({ transform: false, content: result[0]});
last = pattern.lastIndex;
}
output.push({ transform: true, content: content.slice(last)});
return output;
}
return function (input) {
var output = [];
var lines = input.split('\n');
for (var l = 0; l < lines.length; l++) {
var line = lines[l];
var e;
var content;
if (codeBlock.test(line)) {
e = l + 1;
while (!codeBlock.test(lines[e])) {
e++;
}
output.push({ transform: false, content: lines.slice(l, e + 1).join('\n') + '\n\n' });
l = e;
} else if (quoteBlock.test(line)) {
e = l + 1;
while (quoteBlock.test(lines[e])) {
e++;
}
content = [line].concat(lines.slice(l + 1, e).map(function (nextLine) {
return nextLine.slice(2);
})).join(' ') + '\n\n';
output = output.concat(split(content));
l = e - 1;
} else if (listBlock.test(line)) {
e = l + 1;
while (lines[e] !== '') {
if (!listBlock.test(lines[e])) {
lines[e - 1] += ' ' + lines[e];
lines[e] = '';
}
e++;
}
content = lines.slice(l, e).filter(function (line) {
return line !== '';
}).join('\n') + '\n';
output = output.concat(split(content));
l = e - 1;
} else if (line !== '') {
e = l + 1;
while (lines[e] !== '') {
e++;
}
content = lines.slice(l, e).join(' ') + '\n\n';
output = output.concat(split(content));
l = e - 1;
}
}
return output;
};
} | [
"function",
"dummyMarkdown",
"(",
")",
"{",
"var",
"codeBlock",
"=",
"/",
"^```",
"/",
";",
"var",
"quoteBlock",
"=",
"/",
"^>",
"/",
";",
"var",
"listBlock",
"=",
"/",
"^\\* ",
"/",
";",
"var",
"commentInline",
"=",
"'<!--.*",
";",
"var",
"codeInline",
"=",
"'`.+`'",
";",
"function",
"split",
"(",
"content",
")",
"{",
"var",
"pattern",
"=",
"new",
"RegExp",
"(",
"[",
"commentInline",
",",
"codeInline",
"]",
".",
"join",
"(",
"'|'",
")",
",",
"'g'",
")",
";",
"var",
"result",
"=",
"null",
";",
"var",
"last",
"=",
"0",
";",
"var",
"output",
"=",
"[",
"]",
";",
"while",
"(",
"(",
"result",
"=",
"pattern",
".",
"exec",
"(",
"content",
")",
")",
"!==",
"null",
")",
"{",
"output",
".",
"push",
"(",
"{",
"transform",
":",
"true",
",",
"content",
":",
"content",
".",
"slice",
"(",
"last",
",",
"result",
".",
"index",
")",
"}",
")",
";",
"output",
".",
"push",
"(",
"{",
"transform",
":",
"false",
",",
"content",
":",
"result",
"[",
"0",
"]",
"}",
")",
";",
"last",
"=",
"pattern",
".",
"lastIndex",
";",
"}",
"output",
".",
"push",
"(",
"{",
"transform",
":",
"true",
",",
"content",
":",
"content",
".",
"slice",
"(",
"last",
")",
"}",
")",
";",
"return",
"output",
";",
"}",
"return",
"function",
"(",
"input",
")",
"{",
"var",
"output",
"=",
"[",
"]",
";",
"var",
"lines",
"=",
"input",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"for",
"(",
"var",
"l",
"=",
"0",
";",
"l",
"<",
"lines",
".",
"length",
";",
"l",
"++",
")",
"{",
"var",
"line",
"=",
"lines",
"[",
"l",
"]",
";",
"var",
"e",
";",
"var",
"content",
";",
"if",
"(",
"codeBlock",
".",
"test",
"(",
"line",
")",
")",
"{",
"e",
"=",
"l",
"+",
"1",
";",
"while",
"(",
"!",
"codeBlock",
".",
"test",
"(",
"lines",
"[",
"e",
"]",
")",
")",
"{",
"e",
"++",
";",
"}",
"output",
".",
"push",
"(",
"{",
"transform",
":",
"false",
",",
"content",
":",
"lines",
".",
"slice",
"(",
"l",
",",
"e",
"+",
"1",
")",
".",
"join",
"(",
"'\\n'",
")",
"+",
"\\n",
"}",
")",
";",
"'\\n\\n'",
"}",
"else",
"\\n",
"}",
"}",
";",
"}"
] | this format preprocessor is far from being full markdown, it is built to be usable for tipograph readme in the future, this may grow into full markdown support | [
"this",
"format",
"preprocessor",
"is",
"far",
"from",
"being",
"full",
"markdown",
"it",
"is",
"built",
"to",
"be",
"usable",
"for",
"tipograph",
"readme",
"in",
"the",
"future",
"this",
"may",
"grow",
"into",
"full",
"markdown",
"support"
] | c7b0683e9449dbe1646ecc0f6201b7df925dbdf5 | https://github.com/pnevyk/tipograph/blob/c7b0683e9449dbe1646ecc0f6201b7df925dbdf5/scripts/readme.js#L74-L159 | train |
cb1kenobi/cli-kit | site/semantic/tasks/docs/metadata.js | parser | function parser(file, callback) {
// file exit conditions
if(file.isNull()) {
return callback(null, file); // pass along
}
if(file.isStream()) {
return callback(new Error('Streaming not supported'));
}
try {
var
/** @type {string} */
text = String(file.contents.toString('utf8')),
lines = text.split('\n'),
filename = file.path.substring(0, file.path.length - 4),
key = 'server/documents',
position = filename.indexOf(key)
;
// exit conditions
if(!lines) {
return;
}
if(position < 0) {
return callback(null, file);
}
filename = filename.substring(position + key.length + 1, filename.length);
var
lineCount = lines.length,
active = false,
yaml = [],
categories = [
'UI Element',
'UI Global',
'UI Collection',
'UI View',
'UI Module',
'UI Behavior'
],
index,
meta,
line
;
for(index = 0; index < lineCount; index++) {
line = lines[index];
// Wait for metadata block to begin
if(!active) {
if(startsWith(line, '---')) {
active = true;
}
continue;
}
// End of metadata block, stop parsing.
if(startsWith(line, '---')) {
break;
}
yaml.push(line);
}
// Parse yaml.
meta = YAML.parse(yaml.join('\n'));
if(meta && meta.type && meta.title && inArray(meta.type, categories) ) {
meta.category = meta.type;
meta.filename = filename;
meta.url = '/' + filename;
meta.title = meta.title;
// Primary key will by filepath
data[meta.element] = meta;
}
else {
// skip
// console.log(meta);
}
}
catch(error) {
console.log(error, filename);
}
callback(null, file);
} | javascript | function parser(file, callback) {
// file exit conditions
if(file.isNull()) {
return callback(null, file); // pass along
}
if(file.isStream()) {
return callback(new Error('Streaming not supported'));
}
try {
var
/** @type {string} */
text = String(file.contents.toString('utf8')),
lines = text.split('\n'),
filename = file.path.substring(0, file.path.length - 4),
key = 'server/documents',
position = filename.indexOf(key)
;
// exit conditions
if(!lines) {
return;
}
if(position < 0) {
return callback(null, file);
}
filename = filename.substring(position + key.length + 1, filename.length);
var
lineCount = lines.length,
active = false,
yaml = [],
categories = [
'UI Element',
'UI Global',
'UI Collection',
'UI View',
'UI Module',
'UI Behavior'
],
index,
meta,
line
;
for(index = 0; index < lineCount; index++) {
line = lines[index];
// Wait for metadata block to begin
if(!active) {
if(startsWith(line, '---')) {
active = true;
}
continue;
}
// End of metadata block, stop parsing.
if(startsWith(line, '---')) {
break;
}
yaml.push(line);
}
// Parse yaml.
meta = YAML.parse(yaml.join('\n'));
if(meta && meta.type && meta.title && inArray(meta.type, categories) ) {
meta.category = meta.type;
meta.filename = filename;
meta.url = '/' + filename;
meta.title = meta.title;
// Primary key will by filepath
data[meta.element] = meta;
}
else {
// skip
// console.log(meta);
}
}
catch(error) {
console.log(error, filename);
}
callback(null, file);
} | [
"function",
"parser",
"(",
"file",
",",
"callback",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"file",
")",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Streaming not supported'",
")",
")",
";",
"}",
"try",
"{",
"var",
"text",
"=",
"String",
"(",
"file",
".",
"contents",
".",
"toString",
"(",
"'utf8'",
")",
")",
",",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
",",
"\\n",
",",
"filename",
"=",
"file",
".",
"path",
".",
"substring",
"(",
"0",
",",
"file",
".",
"path",
".",
"length",
"-",
"4",
")",
",",
"key",
"=",
"'server/documents'",
";",
"position",
"=",
"filename",
".",
"indexOf",
"(",
"key",
")",
"if",
"(",
"!",
"lines",
")",
"{",
"return",
";",
"}",
"if",
"(",
"position",
"<",
"0",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"file",
")",
";",
"}",
"filename",
"=",
"filename",
".",
"substring",
"(",
"position",
"+",
"key",
".",
"length",
"+",
"1",
",",
"filename",
".",
"length",
")",
";",
"var",
"lineCount",
"=",
"lines",
".",
"length",
",",
"active",
"=",
"false",
",",
"yaml",
"=",
"[",
"]",
",",
"categories",
"=",
"[",
"'UI Element'",
",",
"'UI Global'",
",",
"'UI Collection'",
",",
"'UI View'",
",",
"'UI Module'",
",",
"'UI Behavior'",
"]",
",",
"index",
",",
"meta",
",",
"line",
";",
"for",
"(",
"index",
"=",
"0",
";",
"index",
"<",
"lineCount",
";",
"index",
"++",
")",
"{",
"line",
"=",
"lines",
"[",
"index",
"]",
";",
"if",
"(",
"!",
"active",
")",
"{",
"if",
"(",
"startsWith",
"(",
"line",
",",
"'---'",
")",
")",
"{",
"active",
"=",
"true",
";",
"}",
"continue",
";",
"}",
"if",
"(",
"startsWith",
"(",
"line",
",",
"'---'",
")",
")",
"{",
"break",
";",
"}",
"yaml",
".",
"push",
"(",
"line",
")",
";",
"}",
"meta",
"=",
"YAML",
".",
"parse",
"(",
"yaml",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"}",
"\\n",
"if",
"(",
"meta",
"&&",
"meta",
".",
"type",
"&&",
"meta",
".",
"title",
"&&",
"inArray",
"(",
"meta",
".",
"type",
",",
"categories",
")",
")",
"{",
"meta",
".",
"category",
"=",
"meta",
".",
"type",
";",
"meta",
".",
"filename",
"=",
"filename",
";",
"meta",
".",
"url",
"=",
"'/'",
"+",
"filename",
";",
"meta",
".",
"title",
"=",
"meta",
".",
"title",
";",
"data",
"[",
"meta",
".",
"element",
"]",
"=",
"meta",
";",
"}",
"else",
"{",
"}",
"}"
] | Parses a file for metadata and stores result in data object.
@param {File} file - object provided by map-stream.
@param {function(?,File)} - callback provided by map-stream to
reply when done. | [
"Parses",
"a",
"file",
"for",
"metadata",
"and",
"stores",
"result",
"in",
"data",
"object",
"."
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/site/semantic/tasks/docs/metadata.js#L39-L130 | train |
silkimen/browser-polyfill | polyfills/Element/polyfill.js | function (element, deep) {
var
childNodes = element.childNodes || [],
index = -1,
key, value, childNode;
if (element.nodeType === 1 && element.constructor !== Element) {
element.constructor = Element;
for (key in cache) {
value = cache[key];
element[key] = value;
}
}
while (childNode = deep && childNodes[++index]) {
shiv(childNode, deep);
}
return element;
} | javascript | function (element, deep) {
var
childNodes = element.childNodes || [],
index = -1,
key, value, childNode;
if (element.nodeType === 1 && element.constructor !== Element) {
element.constructor = Element;
for (key in cache) {
value = cache[key];
element[key] = value;
}
}
while (childNode = deep && childNodes[++index]) {
shiv(childNode, deep);
}
return element;
} | [
"function",
"(",
"element",
",",
"deep",
")",
"{",
"var",
"childNodes",
"=",
"element",
".",
"childNodes",
"||",
"[",
"]",
",",
"index",
"=",
"-",
"1",
",",
"key",
",",
"value",
",",
"childNode",
";",
"if",
"(",
"element",
".",
"nodeType",
"===",
"1",
"&&",
"element",
".",
"constructor",
"!==",
"Element",
")",
"{",
"element",
".",
"constructor",
"=",
"Element",
";",
"for",
"(",
"key",
"in",
"cache",
")",
"{",
"value",
"=",
"cache",
"[",
"key",
"]",
";",
"element",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
"while",
"(",
"childNode",
"=",
"deep",
"&&",
"childNodes",
"[",
"++",
"index",
"]",
")",
"{",
"shiv",
"(",
"childNode",
",",
"deep",
")",
";",
"}",
"return",
"element",
";",
"}"
] | polyfill Element.prototype on an element | [
"polyfill",
"Element",
".",
"prototype",
"on",
"an",
"element"
] | f4baaf975c93e8b8fdcea11417f2287dcbd6d208 | https://github.com/silkimen/browser-polyfill/blob/f4baaf975c93e8b8fdcea11417f2287dcbd6d208/polyfills/Element/polyfill.js#L22-L42 | train |
|
silkimen/browser-polyfill | polyfills/Element/polyfill.js | bodyCheck | function bodyCheck() {
if (!(loopLimit--)) clearTimeout(interval);
if (document.body && !document.body.prototype && /(complete|interactive)/.test(document.readyState)) {
shiv(document, true);
if (interval && document.body.prototype) clearTimeout(interval);
return (!!document.body.prototype);
}
return false;
} | javascript | function bodyCheck() {
if (!(loopLimit--)) clearTimeout(interval);
if (document.body && !document.body.prototype && /(complete|interactive)/.test(document.readyState)) {
shiv(document, true);
if (interval && document.body.prototype) clearTimeout(interval);
return (!!document.body.prototype);
}
return false;
} | [
"function",
"bodyCheck",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"loopLimit",
"--",
")",
")",
"clearTimeout",
"(",
"interval",
")",
";",
"if",
"(",
"document",
".",
"body",
"&&",
"!",
"document",
".",
"body",
".",
"prototype",
"&&",
"/",
"(complete|interactive)",
"/",
".",
"test",
"(",
"document",
".",
"readyState",
")",
")",
"{",
"shiv",
"(",
"document",
",",
"true",
")",
";",
"if",
"(",
"interval",
"&&",
"document",
".",
"body",
".",
"prototype",
")",
"clearTimeout",
"(",
"interval",
")",
";",
"return",
"(",
"!",
"!",
"document",
".",
"body",
".",
"prototype",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Apply Element prototype to the pre-existing DOM as soon as the body element appears. | [
"Apply",
"Element",
"prototype",
"to",
"the",
"pre",
"-",
"existing",
"DOM",
"as",
"soon",
"as",
"the",
"body",
"element",
"appears",
"."
] | f4baaf975c93e8b8fdcea11417f2287dcbd6d208 | https://github.com/silkimen/browser-polyfill/blob/f4baaf975c93e8b8fdcea11417f2287dcbd6d208/polyfills/Element/polyfill.js#L79-L87 | train |
enmasseio/hypertimer | lib/hypertimer.js | _getConfig | function _getConfig () {
return {
paced: paced,
rate: rate,
deterministic: deterministic,
time: configuredTime,
master: master,
port: port
}
} | javascript | function _getConfig () {
return {
paced: paced,
rate: rate,
deterministic: deterministic,
time: configuredTime,
master: master,
port: port
}
} | [
"function",
"_getConfig",
"(",
")",
"{",
"return",
"{",
"paced",
":",
"paced",
",",
"rate",
":",
"rate",
",",
"deterministic",
":",
"deterministic",
",",
"time",
":",
"configuredTime",
",",
"master",
":",
"master",
",",
"port",
":",
"port",
"}",
"}"
] | Get the current configuration
@returns {{paced: boolean, rate: number, deterministic: boolean, time: *, master: *}}
Returns a copy of the current configuration
@private | [
"Get",
"the",
"current",
"configuration"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L358-L367 | train |
enmasseio/hypertimer | lib/hypertimer.js | _rescheduleIntervals | function _rescheduleIntervals(now) {
for (var i = 0; i < timeouts.length; i++) {
var timeout = timeouts[i];
if (timeout.type === TYPE.INTERVAL) {
_rescheduleInterval(timeout, now);
}
}
} | javascript | function _rescheduleIntervals(now) {
for (var i = 0; i < timeouts.length; i++) {
var timeout = timeouts[i];
if (timeout.type === TYPE.INTERVAL) {
_rescheduleInterval(timeout, now);
}
}
} | [
"function",
"_rescheduleIntervals",
"(",
"now",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"timeouts",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"timeout",
"=",
"timeouts",
"[",
"i",
"]",
";",
"if",
"(",
"timeout",
".",
"type",
"===",
"TYPE",
".",
"INTERVAL",
")",
"{",
"_rescheduleInterval",
"(",
"timeout",
",",
"now",
")",
";",
"}",
"}",
"}"
] | Reschedule all intervals after a new time has been set.
@param {number} now
@private | [
"Reschedule",
"all",
"intervals",
"after",
"a",
"new",
"time",
"has",
"been",
"set",
"."
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L476-L483 | train |
enmasseio/hypertimer | lib/hypertimer.js | _rescheduleInterval | function _rescheduleInterval(timeout, now) {
timeout.occurrence = Math.round((now - timeout.firstTime) / timeout.interval);
timeout.time = timeout.firstTime + timeout.occurrence * timeout.interval;
} | javascript | function _rescheduleInterval(timeout, now) {
timeout.occurrence = Math.round((now - timeout.firstTime) / timeout.interval);
timeout.time = timeout.firstTime + timeout.occurrence * timeout.interval;
} | [
"function",
"_rescheduleInterval",
"(",
"timeout",
",",
"now",
")",
"{",
"timeout",
".",
"occurrence",
"=",
"Math",
".",
"round",
"(",
"(",
"now",
"-",
"timeout",
".",
"firstTime",
")",
"/",
"timeout",
".",
"interval",
")",
";",
"timeout",
".",
"time",
"=",
"timeout",
".",
"firstTime",
"+",
"timeout",
".",
"occurrence",
"*",
"timeout",
".",
"interval",
";",
"}"
] | Reschedule the intervals after a new time has been set.
@param {Object} timeout
@param {number} now
@private | [
"Reschedule",
"the",
"intervals",
"after",
"a",
"new",
"time",
"has",
"been",
"set",
"."
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L491-L494 | train |
enmasseio/hypertimer | lib/hypertimer.js | _execTimeout | function _execTimeout(timeout, callback) {
// store the timeout in the queue with timeouts in progress
// it can be cleared when a clearTimeout is executed inside the callback
current[timeout.id] = timeout;
function finish() {
// in case of an interval we have to reschedule on next cycle
// interval must not be cleared while executing the callback
if (timeout.type === TYPE.INTERVAL && current[timeout.id]) {
timeout.occurrence++;
timeout.time = timeout.firstTime + timeout.occurrence * timeout.interval;
_queueTimeout(timeout);
//console.log('queue timeout', timer.getTime().toISOString(), new Date(timeout.time).toISOString(), timeout.occurrence) // TODO: cleanup
}
// remove the timeout from the queue with timeouts in progress
delete current[timeout.id];
callback && callback();
}
// execute the callback
try {
if (timeout.callback.length == 0) {
// synchronous timeout, like `timer.setTimeout(function () {...}, delay)`
timeout.callback();
finish();
} else {
// asynchronous timeout, like `timer.setTimeout(function (done) {...; done(); }, delay)`
timeout.callback(finish);
}
} catch (err) {
// emit or log the error
if (hasListeners(timer, 'error')) {
timer.emit('error', err);
}
else {
console.log('Error', err);
}
finish();
}
} | javascript | function _execTimeout(timeout, callback) {
// store the timeout in the queue with timeouts in progress
// it can be cleared when a clearTimeout is executed inside the callback
current[timeout.id] = timeout;
function finish() {
// in case of an interval we have to reschedule on next cycle
// interval must not be cleared while executing the callback
if (timeout.type === TYPE.INTERVAL && current[timeout.id]) {
timeout.occurrence++;
timeout.time = timeout.firstTime + timeout.occurrence * timeout.interval;
_queueTimeout(timeout);
//console.log('queue timeout', timer.getTime().toISOString(), new Date(timeout.time).toISOString(), timeout.occurrence) // TODO: cleanup
}
// remove the timeout from the queue with timeouts in progress
delete current[timeout.id];
callback && callback();
}
// execute the callback
try {
if (timeout.callback.length == 0) {
// synchronous timeout, like `timer.setTimeout(function () {...}, delay)`
timeout.callback();
finish();
} else {
// asynchronous timeout, like `timer.setTimeout(function (done) {...; done(); }, delay)`
timeout.callback(finish);
}
} catch (err) {
// emit or log the error
if (hasListeners(timer, 'error')) {
timer.emit('error', err);
}
else {
console.log('Error', err);
}
finish();
}
} | [
"function",
"_execTimeout",
"(",
"timeout",
",",
"callback",
")",
"{",
"current",
"[",
"timeout",
".",
"id",
"]",
"=",
"timeout",
";",
"function",
"finish",
"(",
")",
"{",
"if",
"(",
"timeout",
".",
"type",
"===",
"TYPE",
".",
"INTERVAL",
"&&",
"current",
"[",
"timeout",
".",
"id",
"]",
")",
"{",
"timeout",
".",
"occurrence",
"++",
";",
"timeout",
".",
"time",
"=",
"timeout",
".",
"firstTime",
"+",
"timeout",
".",
"occurrence",
"*",
"timeout",
".",
"interval",
";",
"_queueTimeout",
"(",
"timeout",
")",
";",
"}",
"delete",
"current",
"[",
"timeout",
".",
"id",
"]",
";",
"callback",
"&&",
"callback",
"(",
")",
";",
"}",
"try",
"{",
"if",
"(",
"timeout",
".",
"callback",
".",
"length",
"==",
"0",
")",
"{",
"timeout",
".",
"callback",
"(",
")",
";",
"finish",
"(",
")",
";",
"}",
"else",
"{",
"timeout",
".",
"callback",
"(",
"finish",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"hasListeners",
"(",
"timer",
",",
"'error'",
")",
")",
"{",
"timer",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Error'",
",",
"err",
")",
";",
"}",
"finish",
"(",
")",
";",
"}",
"}"
] | Execute a timeout
@param {{id: number, type: number, time: number, callback: function}} timeout
@param {function} [callback]
The callback is executed when the timeout's callback is
finished. Called without parameters
@private | [
"Execute",
"a",
"timeout"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L529-L571 | train |
enmasseio/hypertimer | lib/hypertimer.js | _getExpiredTimeouts | function _getExpiredTimeouts(time) {
var i = 0;
while (i < timeouts.length && ((timeouts[i].time <= time) || !isFinite(timeouts[i].time))) {
i++;
}
var expired = timeouts.splice(0, i);
if (deterministic == false) {
// the array with expired timeouts is in deterministic order
// shuffle them
util.shuffle(expired);
}
return expired;
} | javascript | function _getExpiredTimeouts(time) {
var i = 0;
while (i < timeouts.length && ((timeouts[i].time <= time) || !isFinite(timeouts[i].time))) {
i++;
}
var expired = timeouts.splice(0, i);
if (deterministic == false) {
// the array with expired timeouts is in deterministic order
// shuffle them
util.shuffle(expired);
}
return expired;
} | [
"function",
"_getExpiredTimeouts",
"(",
"time",
")",
"{",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"timeouts",
".",
"length",
"&&",
"(",
"(",
"timeouts",
"[",
"i",
"]",
".",
"time",
"<=",
"time",
")",
"||",
"!",
"isFinite",
"(",
"timeouts",
"[",
"i",
"]",
".",
"time",
")",
")",
")",
"{",
"i",
"++",
";",
"}",
"var",
"expired",
"=",
"timeouts",
".",
"splice",
"(",
"0",
",",
"i",
")",
";",
"if",
"(",
"deterministic",
"==",
"false",
")",
"{",
"util",
".",
"shuffle",
"(",
"expired",
")",
";",
"}",
"return",
"expired",
";",
"}"
] | Remove all timeouts occurring before or on the provided time from the
queue and return them.
@param {number} time A timestamp
@returns {Array} returns an array containing all expired timeouts
@private | [
"Remove",
"all",
"timeouts",
"occurring",
"before",
"or",
"on",
"the",
"provided",
"time",
"from",
"the",
"queue",
"and",
"return",
"them",
"."
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L580-L594 | train |
enmasseio/hypertimer | lib/hypertimer.js | _schedule | function _schedule() {
// do not _schedule when there are timeouts in progress
// this can be the case with async timeouts in non-paced mode.
// _schedule will be executed again when all async timeouts are finished.
if (!paced && Object.keys(current).length > 0) {
return;
}
var next = timeouts[0];
// cancel timer when running
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (running && next) {
// schedule next timeout
var time = next.time;
var delay = time - timer.now();
var realDelay = paced ? delay / rate : 0;
function onTimeout() {
// when running in non-paced mode, update the hyperTime to
// adjust the time of the current event
if (!paced) {
hyperTime = (time > hyperTime && isFinite(time)) ? time : hyperTime;
}
// grab all expired timeouts from the queue
var expired = _getExpiredTimeouts(time);
// note: expired.length can never be zero (on every change of the queue, we reschedule)
// execute all expired timeouts
if (paced) {
// in paced mode, we fire all timeouts in parallel,
// and don't await their completion (they can do async operations)
expired.forEach(function (timeout) {
_execTimeout(timeout);
});
// schedule the next round
_schedule();
}
else {
// in non-paced mode, we execute all expired timeouts serially,
// and wait for their completion in order to guarantee deterministic
// order of execution
function next() {
var timeout = expired.shift();
if (timeout) {
_execTimeout(timeout, next);
}
else {
// schedule the next round
_schedule();
}
}
next();
}
}
timeoutId = setTimeout(onTimeout, Math.round(realDelay));
// Note: Math.round(realDelay) is to defeat a bug in node.js v0.10.30,
// see https://github.com/joyent/node/issues/8065
}
} | javascript | function _schedule() {
// do not _schedule when there are timeouts in progress
// this can be the case with async timeouts in non-paced mode.
// _schedule will be executed again when all async timeouts are finished.
if (!paced && Object.keys(current).length > 0) {
return;
}
var next = timeouts[0];
// cancel timer when running
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (running && next) {
// schedule next timeout
var time = next.time;
var delay = time - timer.now();
var realDelay = paced ? delay / rate : 0;
function onTimeout() {
// when running in non-paced mode, update the hyperTime to
// adjust the time of the current event
if (!paced) {
hyperTime = (time > hyperTime && isFinite(time)) ? time : hyperTime;
}
// grab all expired timeouts from the queue
var expired = _getExpiredTimeouts(time);
// note: expired.length can never be zero (on every change of the queue, we reschedule)
// execute all expired timeouts
if (paced) {
// in paced mode, we fire all timeouts in parallel,
// and don't await their completion (they can do async operations)
expired.forEach(function (timeout) {
_execTimeout(timeout);
});
// schedule the next round
_schedule();
}
else {
// in non-paced mode, we execute all expired timeouts serially,
// and wait for their completion in order to guarantee deterministic
// order of execution
function next() {
var timeout = expired.shift();
if (timeout) {
_execTimeout(timeout, next);
}
else {
// schedule the next round
_schedule();
}
}
next();
}
}
timeoutId = setTimeout(onTimeout, Math.round(realDelay));
// Note: Math.round(realDelay) is to defeat a bug in node.js v0.10.30,
// see https://github.com/joyent/node/issues/8065
}
} | [
"function",
"_schedule",
"(",
")",
"{",
"if",
"(",
"!",
"paced",
"&&",
"Object",
".",
"keys",
"(",
"current",
")",
".",
"length",
">",
"0",
")",
"{",
"return",
";",
"}",
"var",
"next",
"=",
"timeouts",
"[",
"0",
"]",
";",
"if",
"(",
"timeoutId",
")",
"{",
"clearTimeout",
"(",
"timeoutId",
")",
";",
"timeoutId",
"=",
"null",
";",
"}",
"if",
"(",
"running",
"&&",
"next",
")",
"{",
"var",
"time",
"=",
"next",
".",
"time",
";",
"var",
"delay",
"=",
"time",
"-",
"timer",
".",
"now",
"(",
")",
";",
"var",
"realDelay",
"=",
"paced",
"?",
"delay",
"/",
"rate",
":",
"0",
";",
"function",
"onTimeout",
"(",
")",
"{",
"if",
"(",
"!",
"paced",
")",
"{",
"hyperTime",
"=",
"(",
"time",
">",
"hyperTime",
"&&",
"isFinite",
"(",
"time",
")",
")",
"?",
"time",
":",
"hyperTime",
";",
"}",
"var",
"expired",
"=",
"_getExpiredTimeouts",
"(",
"time",
")",
";",
"if",
"(",
"paced",
")",
"{",
"expired",
".",
"forEach",
"(",
"function",
"(",
"timeout",
")",
"{",
"_execTimeout",
"(",
"timeout",
")",
";",
"}",
")",
";",
"_schedule",
"(",
")",
";",
"}",
"else",
"{",
"function",
"next",
"(",
")",
"{",
"var",
"timeout",
"=",
"expired",
".",
"shift",
"(",
")",
";",
"if",
"(",
"timeout",
")",
"{",
"_execTimeout",
"(",
"timeout",
",",
"next",
")",
";",
"}",
"else",
"{",
"_schedule",
"(",
")",
";",
"}",
"}",
"next",
"(",
")",
";",
"}",
"}",
"timeoutId",
"=",
"setTimeout",
"(",
"onTimeout",
",",
"Math",
".",
"round",
"(",
"realDelay",
")",
")",
";",
"}",
"}"
] | Reschedule all queued timeouts
@private | [
"Reschedule",
"all",
"queued",
"timeouts"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L600-L666 | train |
enmasseio/hypertimer | lib/hypertimer.js | toTimestamp | function toTimestamp(date) {
var value =
(typeof date === 'number') ? date : // number
(date instanceof Date) ? date.valueOf() : // Date
new Date(date).valueOf(); // ISOString, momentjs, ...
if (isNaN(value)) {
throw new TypeError('Invalid date ' + JSON.stringify(date) + '. ' +
'Date, number, or ISOString expected');
}
return value;
} | javascript | function toTimestamp(date) {
var value =
(typeof date === 'number') ? date : // number
(date instanceof Date) ? date.valueOf() : // Date
new Date(date).valueOf(); // ISOString, momentjs, ...
if (isNaN(value)) {
throw new TypeError('Invalid date ' + JSON.stringify(date) + '. ' +
'Date, number, or ISOString expected');
}
return value;
} | [
"function",
"toTimestamp",
"(",
"date",
")",
"{",
"var",
"value",
"=",
"(",
"typeof",
"date",
"===",
"'number'",
")",
"?",
"date",
":",
"(",
"date",
"instanceof",
"Date",
")",
"?",
"date",
".",
"valueOf",
"(",
")",
":",
"new",
"Date",
"(",
"date",
")",
".",
"valueOf",
"(",
")",
";",
"if",
"(",
"isNaN",
"(",
"value",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Invalid date '",
"+",
"JSON",
".",
"stringify",
"(",
"date",
")",
"+",
"'. '",
"+",
"'Date, number, or ISOString expected'",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Convert a Date, number, or ISOString to a number timestamp,
and validate whether it's a valid Date. The number Infinity is also
accepted as a valid timestamp
@param {Date | number | string} date
@return {number} Returns a unix timestamp, a number | [
"Convert",
"a",
"Date",
"number",
"or",
"ISOString",
"to",
"a",
"number",
"timestamp",
"and",
"validate",
"whether",
"it",
"s",
"a",
"valid",
"Date",
".",
"The",
"number",
"Infinity",
"is",
"also",
"accepted",
"as",
"a",
"valid",
"timestamp"
] | 856ff0a8b7ac2f327a0c755b96b339c63eaf7c89 | https://github.com/enmasseio/hypertimer/blob/856ff0a8b7ac2f327a0c755b96b339c63eaf7c89/lib/hypertimer.js#L675-L687 | train |
pdubroy/tree-walk | index.js | pick | function pick(obj, keys) {
var result = {};
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
if (key in obj) result[key] = obj[key];
}
return result;
} | javascript | function pick(obj, keys) {
var result = {};
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
if (key in obj) result[key] = obj[key];
}
return result;
} | [
"function",
"pick",
"(",
"obj",
",",
"keys",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"length",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"key",
"in",
"obj",
")",
"result",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"return",
"result",
";",
"}"
] | Returns a copy of `obj` containing only the properties given by `keys`. | [
"Returns",
"a",
"copy",
"of",
"obj",
"containing",
"only",
"the",
"properties",
"given",
"by",
"keys",
"."
] | 3a8aa0a5eb3bac6714e9830267a3456b2653d641 | https://github.com/pdubroy/tree-walk/blob/3a8aa0a5eb3bac6714e9830267a3456b2653d641/index.js#L46-L53 | train |
pdubroy/tree-walk | index.js | copyAndPush | function copyAndPush(arr, obj) {
var result = arr.slice();
result.push(obj);
return result;
} | javascript | function copyAndPush(arr, obj) {
var result = arr.slice();
result.push(obj);
return result;
} | [
"function",
"copyAndPush",
"(",
"arr",
",",
"obj",
")",
"{",
"var",
"result",
"=",
"arr",
".",
"slice",
"(",
")",
";",
"result",
".",
"push",
"(",
"obj",
")",
";",
"return",
"result",
";",
"}"
] | Makes a shallow copy of `arr`, and adds `obj` to the end of the copy. | [
"Makes",
"a",
"shallow",
"copy",
"of",
"arr",
"and",
"adds",
"obj",
"to",
"the",
"end",
"of",
"the",
"copy",
"."
] | 3a8aa0a5eb3bac6714e9830267a3456b2653d641 | https://github.com/pdubroy/tree-walk/blob/3a8aa0a5eb3bac6714e9830267a3456b2653d641/index.js#L56-L60 | train |
pdubroy/tree-walk | index.js | Walker | function Walker(traversalStrategy) {
if (!(this instanceof Walker))
return new Walker(traversalStrategy);
// There are two different strategy shorthands: if a single string is
// specified, treat the value of that property as the traversal target.
// If an array is specified, the traversal target is the node itself, but
// only the properties contained in the array will be traversed.
if (isString(traversalStrategy)) {
var prop = traversalStrategy;
traversalStrategy = function(node) {
if (isObject(node) && prop in node) return node[prop];
};
} else if (Array.isArray(traversalStrategy)) {
var props = traversalStrategy;
traversalStrategy = function(node) {
if (isObject(node)) return pick(node, props);
};
}
this._traversalStrategy = traversalStrategy || defaultTraversal;
} | javascript | function Walker(traversalStrategy) {
if (!(this instanceof Walker))
return new Walker(traversalStrategy);
// There are two different strategy shorthands: if a single string is
// specified, treat the value of that property as the traversal target.
// If an array is specified, the traversal target is the node itself, but
// only the properties contained in the array will be traversed.
if (isString(traversalStrategy)) {
var prop = traversalStrategy;
traversalStrategy = function(node) {
if (isObject(node) && prop in node) return node[prop];
};
} else if (Array.isArray(traversalStrategy)) {
var props = traversalStrategy;
traversalStrategy = function(node) {
if (isObject(node)) return pick(node, props);
};
}
this._traversalStrategy = traversalStrategy || defaultTraversal;
} | [
"function",
"Walker",
"(",
"traversalStrategy",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Walker",
")",
")",
"return",
"new",
"Walker",
"(",
"traversalStrategy",
")",
";",
"if",
"(",
"isString",
"(",
"traversalStrategy",
")",
")",
"{",
"var",
"prop",
"=",
"traversalStrategy",
";",
"traversalStrategy",
"=",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"isObject",
"(",
"node",
")",
"&&",
"prop",
"in",
"node",
")",
"return",
"node",
"[",
"prop",
"]",
";",
"}",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"traversalStrategy",
")",
")",
"{",
"var",
"props",
"=",
"traversalStrategy",
";",
"traversalStrategy",
"=",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"isObject",
"(",
"node",
")",
")",
"return",
"pick",
"(",
"node",
",",
"props",
")",
";",
"}",
";",
"}",
"this",
".",
"_traversalStrategy",
"=",
"traversalStrategy",
"||",
"defaultTraversal",
";",
"}"
] | Returns an object containing the walk functions. If `traversalStrategy` is specified, it is a function determining how objects should be traversed. Given an object, it returns the object to be recursively walked. The default strategy is equivalent to `_.identity` for regular objects, and for DOM nodes it returns the node's DOM children. | [
"Returns",
"an",
"object",
"containing",
"the",
"walk",
"functions",
".",
"If",
"traversalStrategy",
"is",
"specified",
"it",
"is",
"a",
"function",
"determining",
"how",
"objects",
"should",
"be",
"traversed",
".",
"Given",
"an",
"object",
"it",
"returns",
"the",
"object",
"to",
"be",
"recursively",
"walked",
".",
"The",
"default",
"strategy",
"is",
"equivalent",
"to",
"_",
".",
"identity",
"for",
"regular",
"objects",
"and",
"for",
"DOM",
"nodes",
"it",
"returns",
"the",
"node",
"s",
"DOM",
"children",
"."
] | 3a8aa0a5eb3bac6714e9830267a3456b2653d641 | https://github.com/pdubroy/tree-walk/blob/3a8aa0a5eb3bac6714e9830267a3456b2653d641/index.js#L125-L145 | train |
rricard/koa-swagger | lib/index.js | createMiddleware | function createMiddleware(router, validator) {
/**
* Checks request and response against a swagger spec
* Uses the usual koa context attributes
* Uses the koa-bodyparser context attribute
* Sets a new context attribute: {object} parameter
*/
return function* middleware(next) {
// Routing matches
try {
var routeMatch = match.path(router, this.path);
} catch(e) {
// TODO: let an option before doing that, strict mode throws the error
yield next;
return false;
}
this.pathParam = routeMatch.param; // Add the path's params to the context
var methodDef = match.method(routeMatch.def, this.method);
// Parameters check & assign
this.parameter = check.parameters(validator,
methodDef.parameters || [], this);
// Let the implementation happen
yield next;
// Response check
var statusDef = match.status(methodDef.responses || {}, this.status);
check.sentHeaders(validator, statusDef.headers || {}, this.sentHeaders);
if(statusDef.schema) {
check.body(validator, statusDef.schema, yield this.body);
}
};
} | javascript | function createMiddleware(router, validator) {
/**
* Checks request and response against a swagger spec
* Uses the usual koa context attributes
* Uses the koa-bodyparser context attribute
* Sets a new context attribute: {object} parameter
*/
return function* middleware(next) {
// Routing matches
try {
var routeMatch = match.path(router, this.path);
} catch(e) {
// TODO: let an option before doing that, strict mode throws the error
yield next;
return false;
}
this.pathParam = routeMatch.param; // Add the path's params to the context
var methodDef = match.method(routeMatch.def, this.method);
// Parameters check & assign
this.parameter = check.parameters(validator,
methodDef.parameters || [], this);
// Let the implementation happen
yield next;
// Response check
var statusDef = match.status(methodDef.responses || {}, this.status);
check.sentHeaders(validator, statusDef.headers || {}, this.sentHeaders);
if(statusDef.schema) {
check.body(validator, statusDef.schema, yield this.body);
}
};
} | [
"function",
"createMiddleware",
"(",
"router",
",",
"validator",
")",
"{",
"return",
"function",
"*",
"middleware",
"(",
"next",
")",
"{",
"try",
"{",
"var",
"routeMatch",
"=",
"match",
".",
"path",
"(",
"router",
",",
"this",
".",
"path",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"yield",
"next",
";",
"return",
"false",
";",
"}",
"this",
".",
"pathParam",
"=",
"routeMatch",
".",
"param",
";",
"var",
"methodDef",
"=",
"match",
".",
"method",
"(",
"routeMatch",
".",
"def",
",",
"this",
".",
"method",
")",
";",
"this",
".",
"parameter",
"=",
"check",
".",
"parameters",
"(",
"validator",
",",
"methodDef",
".",
"parameters",
"||",
"[",
"]",
",",
"this",
")",
";",
"yield",
"next",
";",
"var",
"statusDef",
"=",
"match",
".",
"status",
"(",
"methodDef",
".",
"responses",
"||",
"{",
"}",
",",
"this",
".",
"status",
")",
";",
"check",
".",
"sentHeaders",
"(",
"validator",
",",
"statusDef",
".",
"headers",
"||",
"{",
"}",
",",
"this",
".",
"sentHeaders",
")",
";",
"if",
"(",
"statusDef",
".",
"schema",
")",
"{",
"check",
".",
"body",
"(",
"validator",
",",
"statusDef",
".",
"schema",
",",
"yield",
"this",
".",
"body",
")",
";",
"}",
"}",
";",
"}"
] | Creates the generator from the swagger router & validator
@param router {routington} A swagger definition
@param validator {function(object, Schema)} JSON-Schema validator function
@returns {function*} The created middleware | [
"Creates",
"the",
"generator",
"from",
"the",
"swagger",
"router",
"&",
"validator"
] | 1c2d6cef6fa594a4b5a7697192b28df512c0ed73 | https://github.com/rricard/koa-swagger/blob/1c2d6cef6fa594a4b5a7697192b28df512c0ed73/lib/index.js#L16-L50 | train |
keymetrics/trassingue | index.js | start | function start(projectConfig) {
var config = initConfig(projectConfig);
if (traceApi.isActive() && !config.forceNewAgent_) { // already started.
throw new Error('Cannot call start on an already started agent.');
}
if (!config.enabled) {
return traceApi;
}
if (config.logLevel < 0) {
config.logLevel = 0;
} else if (config.logLevel >= Logger.LEVELS.length) {
config.logLevel = Logger.LEVELS.length - 1;
}
var logger = new Logger(config.logLevel, config.logger === 'debug' ? 'vxx' : undefined);
if (onUncaughtExceptionValues.indexOf(config.onUncaughtException) === -1) {
logger.error('The value of onUncaughtException should be one of ',
onUncaughtExceptionValues);
throw new Error('Invalid value for onUncaughtException configuration.');
}
var headers = {};
headers[constants.TRACE_AGENT_REQUEST_HEADER] = 1;
if (modulesLoadedBeforeTrace.length > 0) {
logger.error('Tracing might not work as the following modules ' +
'were loaded before the trace agent was initialized: ' +
JSON.stringify(modulesLoadedBeforeTrace));
}
agent = require('./src/trace-agent.js').get(config, logger);
traceApi.enable_(agent);
pluginLoader.activate(agent);
traceApi.getCls = function() {
return agent.getCls();
};
traceApi.getBus = function() {
return agent.traceWriter;
};
return traceApi;
} | javascript | function start(projectConfig) {
var config = initConfig(projectConfig);
if (traceApi.isActive() && !config.forceNewAgent_) { // already started.
throw new Error('Cannot call start on an already started agent.');
}
if (!config.enabled) {
return traceApi;
}
if (config.logLevel < 0) {
config.logLevel = 0;
} else if (config.logLevel >= Logger.LEVELS.length) {
config.logLevel = Logger.LEVELS.length - 1;
}
var logger = new Logger(config.logLevel, config.logger === 'debug' ? 'vxx' : undefined);
if (onUncaughtExceptionValues.indexOf(config.onUncaughtException) === -1) {
logger.error('The value of onUncaughtException should be one of ',
onUncaughtExceptionValues);
throw new Error('Invalid value for onUncaughtException configuration.');
}
var headers = {};
headers[constants.TRACE_AGENT_REQUEST_HEADER] = 1;
if (modulesLoadedBeforeTrace.length > 0) {
logger.error('Tracing might not work as the following modules ' +
'were loaded before the trace agent was initialized: ' +
JSON.stringify(modulesLoadedBeforeTrace));
}
agent = require('./src/trace-agent.js').get(config, logger);
traceApi.enable_(agent);
pluginLoader.activate(agent);
traceApi.getCls = function() {
return agent.getCls();
};
traceApi.getBus = function() {
return agent.traceWriter;
};
return traceApi;
} | [
"function",
"start",
"(",
"projectConfig",
")",
"{",
"var",
"config",
"=",
"initConfig",
"(",
"projectConfig",
")",
";",
"if",
"(",
"traceApi",
".",
"isActive",
"(",
")",
"&&",
"!",
"config",
".",
"forceNewAgent_",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot call start on an already started agent.'",
")",
";",
"}",
"if",
"(",
"!",
"config",
".",
"enabled",
")",
"{",
"return",
"traceApi",
";",
"}",
"if",
"(",
"config",
".",
"logLevel",
"<",
"0",
")",
"{",
"config",
".",
"logLevel",
"=",
"0",
";",
"}",
"else",
"if",
"(",
"config",
".",
"logLevel",
">=",
"Logger",
".",
"LEVELS",
".",
"length",
")",
"{",
"config",
".",
"logLevel",
"=",
"Logger",
".",
"LEVELS",
".",
"length",
"-",
"1",
";",
"}",
"var",
"logger",
"=",
"new",
"Logger",
"(",
"config",
".",
"logLevel",
",",
"config",
".",
"logger",
"===",
"'debug'",
"?",
"'vxx'",
":",
"undefined",
")",
";",
"if",
"(",
"onUncaughtExceptionValues",
".",
"indexOf",
"(",
"config",
".",
"onUncaughtException",
")",
"===",
"-",
"1",
")",
"{",
"logger",
".",
"error",
"(",
"'The value of onUncaughtException should be one of '",
",",
"onUncaughtExceptionValues",
")",
";",
"throw",
"new",
"Error",
"(",
"'Invalid value for onUncaughtException configuration.'",
")",
";",
"}",
"var",
"headers",
"=",
"{",
"}",
";",
"headers",
"[",
"constants",
".",
"TRACE_AGENT_REQUEST_HEADER",
"]",
"=",
"1",
";",
"if",
"(",
"modulesLoadedBeforeTrace",
".",
"length",
">",
"0",
")",
"{",
"logger",
".",
"error",
"(",
"'Tracing might not work as the following modules '",
"+",
"'were loaded before the trace agent was initialized: '",
"+",
"JSON",
".",
"stringify",
"(",
"modulesLoadedBeforeTrace",
")",
")",
";",
"}",
"agent",
"=",
"require",
"(",
"'./src/trace-agent.js'",
")",
".",
"get",
"(",
"config",
",",
"logger",
")",
";",
"traceApi",
".",
"enable_",
"(",
"agent",
")",
";",
"pluginLoader",
".",
"activate",
"(",
"agent",
")",
";",
"traceApi",
".",
"getCls",
"=",
"function",
"(",
")",
"{",
"return",
"agent",
".",
"getCls",
"(",
")",
";",
"}",
";",
"traceApi",
".",
"getBus",
"=",
"function",
"(",
")",
"{",
"return",
"agent",
".",
"traceWriter",
";",
"}",
";",
"return",
"traceApi",
";",
"}"
] | Start the Trace agent that will make your application available for
tracing with Stackdriver Trace.
@param {object=} config - Trace configuration
@resource [Introductory video]{@link
https://www.youtube.com/watch?v=NCFDqeo7AeY}
@example
trace.start(); | [
"Start",
"the",
"Trace",
"agent",
"that",
"will",
"make",
"your",
"application",
"available",
"for",
"tracing",
"with",
"Stackdriver",
"Trace",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/index.js#L71-L117 | train |
takuyaa/doublearray | doublearray.js | function (signed, bytes, size) {
if (signed) {
switch(bytes) {
case 1:
return new Int8Array(size);
case 2:
return new Int16Array(size);
case 4:
return new Int32Array(size);
default:
throw new RangeError("Invalid newArray parameter element_bytes:" + bytes);
}
} else {
switch(bytes) {
case 1:
return new Uint8Array(size);
case 2:
return new Uint16Array(size);
case 4:
return new Uint32Array(size);
default:
throw new RangeError("Invalid newArray parameter element_bytes:" + bytes);
}
}
} | javascript | function (signed, bytes, size) {
if (signed) {
switch(bytes) {
case 1:
return new Int8Array(size);
case 2:
return new Int16Array(size);
case 4:
return new Int32Array(size);
default:
throw new RangeError("Invalid newArray parameter element_bytes:" + bytes);
}
} else {
switch(bytes) {
case 1:
return new Uint8Array(size);
case 2:
return new Uint16Array(size);
case 4:
return new Uint32Array(size);
default:
throw new RangeError("Invalid newArray parameter element_bytes:" + bytes);
}
}
} | [
"function",
"(",
"signed",
",",
"bytes",
",",
"size",
")",
"{",
"if",
"(",
"signed",
")",
"{",
"switch",
"(",
"bytes",
")",
"{",
"case",
"1",
":",
"return",
"new",
"Int8Array",
"(",
"size",
")",
";",
"case",
"2",
":",
"return",
"new",
"Int16Array",
"(",
"size",
")",
";",
"case",
"4",
":",
"return",
"new",
"Int32Array",
"(",
"size",
")",
";",
"default",
":",
"throw",
"new",
"RangeError",
"(",
"\"Invalid newArray parameter element_bytes:\"",
"+",
"bytes",
")",
";",
"}",
"}",
"else",
"{",
"switch",
"(",
"bytes",
")",
"{",
"case",
"1",
":",
"return",
"new",
"Uint8Array",
"(",
"size",
")",
";",
"case",
"2",
":",
"return",
"new",
"Uint16Array",
"(",
"size",
")",
";",
"case",
"4",
":",
"return",
"new",
"Uint32Array",
"(",
"size",
")",
";",
"default",
":",
"throw",
"new",
"RangeError",
"(",
"\"Invalid newArray parameter element_bytes:\"",
"+",
"bytes",
")",
";",
"}",
"}",
"}"
] | Array utility functions | [
"Array",
"utility",
"functions"
] | d026d9dce65c7c414e643b55d0774f080e606a09 | https://github.com/takuyaa/doublearray/blob/d026d9dce65c7c414e643b55d0774f080e606a09/doublearray.js#L618-L642 | train |
|
jldec/pub-server | server/serve-statics.js | scan | function scan(sp, cb) {
cb = u.onceMaybe(cb);
var timer = u.timer();
sp.route = sp.route || '/';
var src = sp.src;
// only construct src, defaults, sendOpts etc. once
if (!src) {
sp.name = sp.name || 'staticPath:' + sp.path;
sp.depth = sp.depth || opts.staticDepth || 5;
sp.maxAge = 'maxAge' in sp ? sp.maxAge : '10m';
sp.includeBinaries = true;
src = sp.src = fsbase(sp);
if (src.isfile()) { sp.depth = 1; }
sp.sendOpts = u.assign(
u.pick(sp, 'maxAge', 'lastModified', 'etag'),
{ dotfiles:'ignore',
index:false, // handled at this level
extensions:false, // ditto
root:src.path } );
}
src.listfiles(function(err, files) {
if (err) return cb(log(err));
sp.files = files;
self.scanCnt++;
mapAllFiles();
debug('static scan %s-deep %sms %s', sp.depth, timer(), sp.path.replace(/.*\/node_modules\//g, ''));
debug(files.length > 10 ? '[' + files.length + ' files]' : u.pluck(files, 'filepath'));
cb();
});
} | javascript | function scan(sp, cb) {
cb = u.onceMaybe(cb);
var timer = u.timer();
sp.route = sp.route || '/';
var src = sp.src;
// only construct src, defaults, sendOpts etc. once
if (!src) {
sp.name = sp.name || 'staticPath:' + sp.path;
sp.depth = sp.depth || opts.staticDepth || 5;
sp.maxAge = 'maxAge' in sp ? sp.maxAge : '10m';
sp.includeBinaries = true;
src = sp.src = fsbase(sp);
if (src.isfile()) { sp.depth = 1; }
sp.sendOpts = u.assign(
u.pick(sp, 'maxAge', 'lastModified', 'etag'),
{ dotfiles:'ignore',
index:false, // handled at this level
extensions:false, // ditto
root:src.path } );
}
src.listfiles(function(err, files) {
if (err) return cb(log(err));
sp.files = files;
self.scanCnt++;
mapAllFiles();
debug('static scan %s-deep %sms %s', sp.depth, timer(), sp.path.replace(/.*\/node_modules\//g, ''));
debug(files.length > 10 ? '[' + files.length + ' files]' : u.pluck(files, 'filepath'));
cb();
});
} | [
"function",
"scan",
"(",
"sp",
",",
"cb",
")",
"{",
"cb",
"=",
"u",
".",
"onceMaybe",
"(",
"cb",
")",
";",
"var",
"timer",
"=",
"u",
".",
"timer",
"(",
")",
";",
"sp",
".",
"route",
"=",
"sp",
".",
"route",
"||",
"'/'",
";",
"var",
"src",
"=",
"sp",
".",
"src",
";",
"if",
"(",
"!",
"src",
")",
"{",
"sp",
".",
"name",
"=",
"sp",
".",
"name",
"||",
"'staticPath:'",
"+",
"sp",
".",
"path",
";",
"sp",
".",
"depth",
"=",
"sp",
".",
"depth",
"||",
"opts",
".",
"staticDepth",
"||",
"5",
";",
"sp",
".",
"maxAge",
"=",
"'maxAge'",
"in",
"sp",
"?",
"sp",
".",
"maxAge",
":",
"'10m'",
";",
"sp",
".",
"includeBinaries",
"=",
"true",
";",
"src",
"=",
"sp",
".",
"src",
"=",
"fsbase",
"(",
"sp",
")",
";",
"if",
"(",
"src",
".",
"isfile",
"(",
")",
")",
"{",
"sp",
".",
"depth",
"=",
"1",
";",
"}",
"sp",
".",
"sendOpts",
"=",
"u",
".",
"assign",
"(",
"u",
".",
"pick",
"(",
"sp",
",",
"'maxAge'",
",",
"'lastModified'",
",",
"'etag'",
")",
",",
"{",
"dotfiles",
":",
"'ignore'",
",",
"index",
":",
"false",
",",
"extensions",
":",
"false",
",",
"root",
":",
"src",
".",
"path",
"}",
")",
";",
"}",
"src",
".",
"listfiles",
"(",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"log",
"(",
"err",
")",
")",
";",
"sp",
".",
"files",
"=",
"files",
";",
"self",
".",
"scanCnt",
"++",
";",
"mapAllFiles",
"(",
")",
";",
"debug",
"(",
"'static scan %s-deep %sms %s'",
",",
"sp",
".",
"depth",
",",
"timer",
"(",
")",
",",
"sp",
".",
"path",
".",
"replace",
"(",
"/",
".*\\/node_modules\\/",
"/",
"g",
",",
"''",
")",
")",
";",
"debug",
"(",
"files",
".",
"length",
">",
"10",
"?",
"'['",
"+",
"files",
".",
"length",
"+",
"' files]'",
":",
"u",
".",
"pluck",
"(",
"files",
",",
"'filepath'",
")",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] | repeatable scan for single staticPath | [
"repeatable",
"scan",
"for",
"single",
"staticPath"
] | 2e11d2377cf5a0b31ca7fdcef78a433d0c4885df | https://github.com/jldec/pub-server/blob/2e11d2377cf5a0b31ca7fdcef78a433d0c4885df/server/serve-statics.js#L128-L160 | train |
MozillaReality/gamepad-plus | standard-mapper/gamepad.js | function () {
var gamepadSupportAvailable = navigator.getGamepads ||
!!navigator.webkitGetGamepads ||
!!navigator.webkitGamepads;
if (!gamepadSupportAvailable) {
// It doesn't seem Gamepad API is available, show a message telling
// the visitor about it.
window.tester.showNotSupported();
} else {
// Check and see if gamepadconnected/gamepaddisconnected is supported.
// If so, listen for those events and don't start polling until a
// gamepad has been connected.
if (gamepadSupport.hasEvents) {
// If connection events are not supported, just start polling.
gamepadSupport.startPolling();
} else {
window.addEventListener('gamepadconnected',
gamepadSupport.onGamepadConnect);
window.addEventListener('gamepaddisconnected',
gamepadSupport.onGamepadDisconnect);
}
}
} | javascript | function () {
var gamepadSupportAvailable = navigator.getGamepads ||
!!navigator.webkitGetGamepads ||
!!navigator.webkitGamepads;
if (!gamepadSupportAvailable) {
// It doesn't seem Gamepad API is available, show a message telling
// the visitor about it.
window.tester.showNotSupported();
} else {
// Check and see if gamepadconnected/gamepaddisconnected is supported.
// If so, listen for those events and don't start polling until a
// gamepad has been connected.
if (gamepadSupport.hasEvents) {
// If connection events are not supported, just start polling.
gamepadSupport.startPolling();
} else {
window.addEventListener('gamepadconnected',
gamepadSupport.onGamepadConnect);
window.addEventListener('gamepaddisconnected',
gamepadSupport.onGamepadDisconnect);
}
}
} | [
"function",
"(",
")",
"{",
"var",
"gamepadSupportAvailable",
"=",
"navigator",
".",
"getGamepads",
"||",
"!",
"!",
"navigator",
".",
"webkitGetGamepads",
"||",
"!",
"!",
"navigator",
".",
"webkitGamepads",
";",
"if",
"(",
"!",
"gamepadSupportAvailable",
")",
"{",
"window",
".",
"tester",
".",
"showNotSupported",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"gamepadSupport",
".",
"hasEvents",
")",
"{",
"gamepadSupport",
".",
"startPolling",
"(",
")",
";",
"}",
"else",
"{",
"window",
".",
"addEventListener",
"(",
"'gamepadconnected'",
",",
"gamepadSupport",
".",
"onGamepadConnect",
")",
";",
"window",
".",
"addEventListener",
"(",
"'gamepaddisconnected'",
",",
"gamepadSupport",
".",
"onGamepadDisconnect",
")",
";",
"}",
"}",
"}"
] | Initialize support for Gamepad API. | [
"Initialize",
"support",
"for",
"Gamepad",
"API",
"."
] | b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb | https://github.com/MozillaReality/gamepad-plus/blob/b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb/standard-mapper/gamepad.js#L36-L59 | train |
|
MozillaReality/gamepad-plus | standard-mapper/gamepad.js | function (event) {
// Add the new gamepad on the list of gamepads to look after.
gamepadSupport.gamepads.push(event.gamepad);
// Ask the tester to update the screen to show more gamepads.
window.tester.updateGamepads(gamepadSupport.gamepads);
// Start the polling loop to monitor button changes.
gamepadSupport.startPolling();
} | javascript | function (event) {
// Add the new gamepad on the list of gamepads to look after.
gamepadSupport.gamepads.push(event.gamepad);
// Ask the tester to update the screen to show more gamepads.
window.tester.updateGamepads(gamepadSupport.gamepads);
// Start the polling loop to monitor button changes.
gamepadSupport.startPolling();
} | [
"function",
"(",
"event",
")",
"{",
"gamepadSupport",
".",
"gamepads",
".",
"push",
"(",
"event",
".",
"gamepad",
")",
";",
"window",
".",
"tester",
".",
"updateGamepads",
"(",
"gamepadSupport",
".",
"gamepads",
")",
";",
"gamepadSupport",
".",
"startPolling",
"(",
")",
";",
"}"
] | React to the gamepad being connected. | [
"React",
"to",
"the",
"gamepad",
"being",
"connected",
"."
] | b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb | https://github.com/MozillaReality/gamepad-plus/blob/b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb/standard-mapper/gamepad.js#L64-L73 | train |
|
MozillaReality/gamepad-plus | standard-mapper/gamepad.js | function (event) {
// Remove the gamepad from the list of gamepads to monitor.
for (var i in gamepadSupport.gamepads) {
if (gamepadSupport.gamepads[i].index === event.gamepad.index) {
gamepadSupport.gamepads.splice(i, 1);
break;
}
}
// If no gamepads are left, stop the polling loop (but only if
// `gamepadconnected` will get fired when a gamepad is reconnected).
if (!gamepadSupport.gamepads.length && gamepadSupport.hasEvents) {
gamepadSupport.stopPolling();
}
// Ask the tester to update the screen to remove the gamepad.
window.tester.updateGamepads(gamepadSupport.gamepads);
} | javascript | function (event) {
// Remove the gamepad from the list of gamepads to monitor.
for (var i in gamepadSupport.gamepads) {
if (gamepadSupport.gamepads[i].index === event.gamepad.index) {
gamepadSupport.gamepads.splice(i, 1);
break;
}
}
// If no gamepads are left, stop the polling loop (but only if
// `gamepadconnected` will get fired when a gamepad is reconnected).
if (!gamepadSupport.gamepads.length && gamepadSupport.hasEvents) {
gamepadSupport.stopPolling();
}
// Ask the tester to update the screen to remove the gamepad.
window.tester.updateGamepads(gamepadSupport.gamepads);
} | [
"function",
"(",
"event",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"gamepadSupport",
".",
"gamepads",
")",
"{",
"if",
"(",
"gamepadSupport",
".",
"gamepads",
"[",
"i",
"]",
".",
"index",
"===",
"event",
".",
"gamepad",
".",
"index",
")",
"{",
"gamepadSupport",
".",
"gamepads",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"gamepadSupport",
".",
"gamepads",
".",
"length",
"&&",
"gamepadSupport",
".",
"hasEvents",
")",
"{",
"gamepadSupport",
".",
"stopPolling",
"(",
")",
";",
"}",
"window",
".",
"tester",
".",
"updateGamepads",
"(",
"gamepadSupport",
".",
"gamepads",
")",
";",
"}"
] | React to the gamepad being disconnected. | [
"React",
"to",
"the",
"gamepad",
"being",
"disconnected",
"."
] | b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb | https://github.com/MozillaReality/gamepad-plus/blob/b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb/standard-mapper/gamepad.js#L78-L95 | train |
|
MozillaReality/gamepad-plus | standard-mapper/gamepad.js | function (gamepadId) {
var gamepad = gamepadSupport.gamepads[gamepadId];
// Update all the buttons (and their corresponding labels) on screen.
window.tester.updateButton(gamepad.buttons[0], gamepadId, 'button-1');
window.tester.updateButton(gamepad.buttons[1], gamepadId, 'button-2');
window.tester.updateButton(gamepad.buttons[2], gamepadId, 'button-3');
window.tester.updateButton(gamepad.buttons[3], gamepadId, 'button-4');
window.tester.updateButton(gamepad.buttons[4], gamepadId,
'button-left-shoulder-top');
window.tester.updateButton(gamepad.buttons[6], gamepadId,
'button-left-shoulder-bottom');
window.tester.updateButton(gamepad.buttons[5], gamepadId,
'button-right-shoulder-top');
window.tester.updateButton(gamepad.buttons[7], gamepadId,
'button-right-shoulder-bottom');
window.tester.updateButton(gamepad.buttons[8], gamepadId, 'button-select');
window.tester.updateButton(gamepad.buttons[9], gamepadId, 'button-start');
window.tester.updateButton(gamepad.buttons[10], gamepadId, 'stick-1');
window.tester.updateButton(gamepad.buttons[11], gamepadId, 'stick-2');
window.tester.updateButton(gamepad.buttons[12], gamepadId, 'button-dpad-top');
window.tester.updateButton(gamepad.buttons[13], gamepadId, 'button-dpad-bottom');
window.tester.updateButton(gamepad.buttons[14], gamepadId, 'button-dpad-left');
window.tester.updateButton(gamepad.buttons[15], gamepadId, 'button-dpad-right');
// Update all the analogue sticks.
window.tester.updateAxis(gamepad.axes[0], gamepadId,
'stick-1-axis-x', 'stick-1', true);
window.tester.updateAxis(gamepad.axes[1], gamepadId,
'stick-1-axis-y', 'stick-1', false);
window.tester.updateAxis(gamepad.axes[2], gamepadId,
'stick-2-axis-x', 'stick-2', true);
window.tester.updateAxis(gamepad.axes[3], gamepadId,
'stick-2-axis-y', 'stick-2', false);
// Update extraneous buttons.
var extraButtonId = gamepadSupport.TYPICAL_BUTTON_COUNT;
while (typeof gamepad.buttons[extraButtonId] !== 'undefined') {
window.tester.updateButton(gamepad.buttons[extraButtonId], gamepadId,
'extra-button-' + extraButtonId);
extraButtonId++;
}
// Update extraneous axes.
var extraAxisId = gamepadSupport.TYPICAL_AXIS_COUNT;
while (typeof gamepad.axes[extraAxisId] !== 'undefined') {
window.tester.updateAxis(gamepad.axes[extraAxisId], gamepadId,
'extra-axis-' + extraAxisId);
extraAxisId++;
}
} | javascript | function (gamepadId) {
var gamepad = gamepadSupport.gamepads[gamepadId];
// Update all the buttons (and their corresponding labels) on screen.
window.tester.updateButton(gamepad.buttons[0], gamepadId, 'button-1');
window.tester.updateButton(gamepad.buttons[1], gamepadId, 'button-2');
window.tester.updateButton(gamepad.buttons[2], gamepadId, 'button-3');
window.tester.updateButton(gamepad.buttons[3], gamepadId, 'button-4');
window.tester.updateButton(gamepad.buttons[4], gamepadId,
'button-left-shoulder-top');
window.tester.updateButton(gamepad.buttons[6], gamepadId,
'button-left-shoulder-bottom');
window.tester.updateButton(gamepad.buttons[5], gamepadId,
'button-right-shoulder-top');
window.tester.updateButton(gamepad.buttons[7], gamepadId,
'button-right-shoulder-bottom');
window.tester.updateButton(gamepad.buttons[8], gamepadId, 'button-select');
window.tester.updateButton(gamepad.buttons[9], gamepadId, 'button-start');
window.tester.updateButton(gamepad.buttons[10], gamepadId, 'stick-1');
window.tester.updateButton(gamepad.buttons[11], gamepadId, 'stick-2');
window.tester.updateButton(gamepad.buttons[12], gamepadId, 'button-dpad-top');
window.tester.updateButton(gamepad.buttons[13], gamepadId, 'button-dpad-bottom');
window.tester.updateButton(gamepad.buttons[14], gamepadId, 'button-dpad-left');
window.tester.updateButton(gamepad.buttons[15], gamepadId, 'button-dpad-right');
// Update all the analogue sticks.
window.tester.updateAxis(gamepad.axes[0], gamepadId,
'stick-1-axis-x', 'stick-1', true);
window.tester.updateAxis(gamepad.axes[1], gamepadId,
'stick-1-axis-y', 'stick-1', false);
window.tester.updateAxis(gamepad.axes[2], gamepadId,
'stick-2-axis-x', 'stick-2', true);
window.tester.updateAxis(gamepad.axes[3], gamepadId,
'stick-2-axis-y', 'stick-2', false);
// Update extraneous buttons.
var extraButtonId = gamepadSupport.TYPICAL_BUTTON_COUNT;
while (typeof gamepad.buttons[extraButtonId] !== 'undefined') {
window.tester.updateButton(gamepad.buttons[extraButtonId], gamepadId,
'extra-button-' + extraButtonId);
extraButtonId++;
}
// Update extraneous axes.
var extraAxisId = gamepadSupport.TYPICAL_AXIS_COUNT;
while (typeof gamepad.axes[extraAxisId] !== 'undefined') {
window.tester.updateAxis(gamepad.axes[extraAxisId], gamepadId,
'extra-axis-' + extraAxisId);
extraAxisId++;
}
} | [
"function",
"(",
"gamepadId",
")",
"{",
"var",
"gamepad",
"=",
"gamepadSupport",
".",
"gamepads",
"[",
"gamepadId",
"]",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"0",
"]",
",",
"gamepadId",
",",
"'button-1'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"1",
"]",
",",
"gamepadId",
",",
"'button-2'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"2",
"]",
",",
"gamepadId",
",",
"'button-3'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"3",
"]",
",",
"gamepadId",
",",
"'button-4'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"4",
"]",
",",
"gamepadId",
",",
"'button-left-shoulder-top'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"6",
"]",
",",
"gamepadId",
",",
"'button-left-shoulder-bottom'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"5",
"]",
",",
"gamepadId",
",",
"'button-right-shoulder-top'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"7",
"]",
",",
"gamepadId",
",",
"'button-right-shoulder-bottom'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"8",
"]",
",",
"gamepadId",
",",
"'button-select'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"9",
"]",
",",
"gamepadId",
",",
"'button-start'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"10",
"]",
",",
"gamepadId",
",",
"'stick-1'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"11",
"]",
",",
"gamepadId",
",",
"'stick-2'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"12",
"]",
",",
"gamepadId",
",",
"'button-dpad-top'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"13",
"]",
",",
"gamepadId",
",",
"'button-dpad-bottom'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"14",
"]",
",",
"gamepadId",
",",
"'button-dpad-left'",
")",
";",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"15",
"]",
",",
"gamepadId",
",",
"'button-dpad-right'",
")",
";",
"window",
".",
"tester",
".",
"updateAxis",
"(",
"gamepad",
".",
"axes",
"[",
"0",
"]",
",",
"gamepadId",
",",
"'stick-1-axis-x'",
",",
"'stick-1'",
",",
"true",
")",
";",
"window",
".",
"tester",
".",
"updateAxis",
"(",
"gamepad",
".",
"axes",
"[",
"1",
"]",
",",
"gamepadId",
",",
"'stick-1-axis-y'",
",",
"'stick-1'",
",",
"false",
")",
";",
"window",
".",
"tester",
".",
"updateAxis",
"(",
"gamepad",
".",
"axes",
"[",
"2",
"]",
",",
"gamepadId",
",",
"'stick-2-axis-x'",
",",
"'stick-2'",
",",
"true",
")",
";",
"window",
".",
"tester",
".",
"updateAxis",
"(",
"gamepad",
".",
"axes",
"[",
"3",
"]",
",",
"gamepadId",
",",
"'stick-2-axis-y'",
",",
"'stick-2'",
",",
"false",
")",
";",
"var",
"extraButtonId",
"=",
"gamepadSupport",
".",
"TYPICAL_BUTTON_COUNT",
";",
"while",
"(",
"typeof",
"gamepad",
".",
"buttons",
"[",
"extraButtonId",
"]",
"!==",
"'undefined'",
")",
"{",
"window",
".",
"tester",
".",
"updateButton",
"(",
"gamepad",
".",
"buttons",
"[",
"extraButtonId",
"]",
",",
"gamepadId",
",",
"'extra-button-'",
"+",
"extraButtonId",
")",
";",
"extraButtonId",
"++",
";",
"}",
"var",
"extraAxisId",
"=",
"gamepadSupport",
".",
"TYPICAL_AXIS_COUNT",
";",
"while",
"(",
"typeof",
"gamepad",
".",
"axes",
"[",
"extraAxisId",
"]",
"!==",
"'undefined'",
")",
"{",
"window",
".",
"tester",
".",
"updateAxis",
"(",
"gamepad",
".",
"axes",
"[",
"extraAxisId",
"]",
",",
"gamepadId",
",",
"'extra-axis-'",
"+",
"extraAxisId",
")",
";",
"extraAxisId",
"++",
";",
"}",
"}"
] | Call the tester with new state and ask it to update the visual representation of a given gamepad. | [
"Call",
"the",
"tester",
"with",
"new",
"state",
"and",
"ask",
"it",
"to",
"update",
"the",
"visual",
"representation",
"of",
"a",
"given",
"gamepad",
"."
] | b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb | https://github.com/MozillaReality/gamepad-plus/blob/b3cc035c524f3fde7c46ad2e2fb94ab61d1bc6cb/standard-mapper/gamepad.js#L214-L271 | train |
|
cb1kenobi/cli-kit | site/semantic/tasks/admin/components/update.js | pushFiles | function pushFiles() {
console.info('Pushing files for ' + component);
git.push('origin', 'master', { args: '', cwd: outputDirectory }, function(error) {
console.info('Push completed successfully');
getSHA();
});
} | javascript | function pushFiles() {
console.info('Pushing files for ' + component);
git.push('origin', 'master', { args: '', cwd: outputDirectory }, function(error) {
console.info('Push completed successfully');
getSHA();
});
} | [
"function",
"pushFiles",
"(",
")",
"{",
"console",
".",
"info",
"(",
"'Pushing files for '",
"+",
"component",
")",
";",
"git",
".",
"push",
"(",
"'origin'",
",",
"'master'",
",",
"{",
"args",
":",
"''",
",",
"cwd",
":",
"outputDirectory",
"}",
",",
"function",
"(",
"error",
")",
"{",
"console",
".",
"info",
"(",
"'Push completed successfully'",
")",
";",
"getSHA",
"(",
")",
";",
"}",
")",
";",
"}"
] | push changes to remote | [
"push",
"changes",
"to",
"remote"
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/site/semantic/tasks/admin/components/update.js#L138-L144 | train |
cb1kenobi/cli-kit | site/semantic/tasks/admin/components/update.js | getSHA | function getSHA() {
git.exec(versionOptions, function(error, version) {
version = version.trim();
createRelease(version);
});
} | javascript | function getSHA() {
git.exec(versionOptions, function(error, version) {
version = version.trim();
createRelease(version);
});
} | [
"function",
"getSHA",
"(",
")",
"{",
"git",
".",
"exec",
"(",
"versionOptions",
",",
"function",
"(",
"error",
",",
"version",
")",
"{",
"version",
"=",
"version",
".",
"trim",
"(",
")",
";",
"createRelease",
"(",
"version",
")",
";",
"}",
")",
";",
"}"
] | gets SHA of last commit | [
"gets",
"SHA",
"of",
"last",
"commit"
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/site/semantic/tasks/admin/components/update.js#L147-L152 | train |
cb1kenobi/cli-kit | site/semantic/tasks/admin/components/update.js | nextRepo | function nextRepo() {
console.log('Sleeping for 1 second...');
// avoid rate throttling
global.clearTimeout(timer);
timer = global.setTimeout(stepRepo, 100);
} | javascript | function nextRepo() {
console.log('Sleeping for 1 second...');
// avoid rate throttling
global.clearTimeout(timer);
timer = global.setTimeout(stepRepo, 100);
} | [
"function",
"nextRepo",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'Sleeping for 1 second...'",
")",
";",
"global",
".",
"clearTimeout",
"(",
"timer",
")",
";",
"timer",
"=",
"global",
".",
"setTimeout",
"(",
"stepRepo",
",",
"100",
")",
";",
"}"
] | Steps to next repository | [
"Steps",
"to",
"next",
"repository"
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/site/semantic/tasks/admin/components/update.js#L165-L170 | train |
danmilon/passbookster | lib/Template.js | Template | function Template(style, fields, opts) {
// throw early if style is incorrect
if (passFields.STYLES.indexOf(style) === -1) {
throw new Error('Incorrect passbook style ' + style)
}
this.style = style
this.opts = opts || {}
this.fields = fields || {}
// Set formatVersion by default
this.fields.formatVersion = 1
} | javascript | function Template(style, fields, opts) {
// throw early if style is incorrect
if (passFields.STYLES.indexOf(style) === -1) {
throw new Error('Incorrect passbook style ' + style)
}
this.style = style
this.opts = opts || {}
this.fields = fields || {}
// Set formatVersion by default
this.fields.formatVersion = 1
} | [
"function",
"Template",
"(",
"style",
",",
"fields",
",",
"opts",
")",
"{",
"if",
"(",
"passFields",
".",
"STYLES",
".",
"indexOf",
"(",
"style",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Incorrect passbook style '",
"+",
"style",
")",
"}",
"this",
".",
"style",
"=",
"style",
"this",
".",
"opts",
"=",
"opts",
"||",
"{",
"}",
"this",
".",
"fields",
"=",
"fields",
"||",
"{",
"}",
"this",
".",
"fields",
".",
"formatVersion",
"=",
"1",
"}"
] | Create a passbook template.
A Template acts as a pass without having all its fields set.
Internally, on createPass it merely passes its fields and the extra ones
provided as an argument to a new Pass object
@param {String} style Pass style of the pass
@param {Object} fields Fields of the pass
@param {Object} opts Extra options | [
"Create",
"a",
"passbook",
"template",
".",
"A",
"Template",
"acts",
"as",
"a",
"pass",
"without",
"having",
"all",
"its",
"fields",
"set",
"."
] | 92d8140b5c9d3b6db31e32a8c2ae17a7b56c8490 | https://github.com/danmilon/passbookster/blob/92d8140b5c9d3b6db31e32a8c2ae17a7b56c8490/lib/Template.js#L15-L27 | train |
syntax-tree/mdast-util-heading-range | index.js | headingRange | function headingRange(node, options, callback) {
var test = options
var ignoreFinalDefinitions = false
// Object, not regex.
if (test && typeof test === 'object' && !('exec' in test)) {
ignoreFinalDefinitions = test.ignoreFinalDefinitions === true
test = test.test
}
if (typeof test === 'string') {
test = toExpression(test)
}
// Regex
if (test && 'exec' in test) {
test = wrapExpression(test)
}
if (typeof test !== 'function') {
throw new Error(
'Expected `string`, `regexp`, or `function` for `test`, not `' +
test +
'`'
)
}
search(node, test, ignoreFinalDefinitions, callback)
} | javascript | function headingRange(node, options, callback) {
var test = options
var ignoreFinalDefinitions = false
// Object, not regex.
if (test && typeof test === 'object' && !('exec' in test)) {
ignoreFinalDefinitions = test.ignoreFinalDefinitions === true
test = test.test
}
if (typeof test === 'string') {
test = toExpression(test)
}
// Regex
if (test && 'exec' in test) {
test = wrapExpression(test)
}
if (typeof test !== 'function') {
throw new Error(
'Expected `string`, `regexp`, or `function` for `test`, not `' +
test +
'`'
)
}
search(node, test, ignoreFinalDefinitions, callback)
} | [
"function",
"headingRange",
"(",
"node",
",",
"options",
",",
"callback",
")",
"{",
"var",
"test",
"=",
"options",
"var",
"ignoreFinalDefinitions",
"=",
"false",
"if",
"(",
"test",
"&&",
"typeof",
"test",
"===",
"'object'",
"&&",
"!",
"(",
"'exec'",
"in",
"test",
")",
")",
"{",
"ignoreFinalDefinitions",
"=",
"test",
".",
"ignoreFinalDefinitions",
"===",
"true",
"test",
"=",
"test",
".",
"test",
"}",
"if",
"(",
"typeof",
"test",
"===",
"'string'",
")",
"{",
"test",
"=",
"toExpression",
"(",
"test",
")",
"}",
"if",
"(",
"test",
"&&",
"'exec'",
"in",
"test",
")",
"{",
"test",
"=",
"wrapExpression",
"(",
"test",
")",
"}",
"if",
"(",
"typeof",
"test",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected `string`, `regexp`, or `function` for `test`, not `'",
"+",
"test",
"+",
"'`'",
")",
"}",
"search",
"(",
"node",
",",
"test",
",",
"ignoreFinalDefinitions",
",",
"callback",
")",
"}"
] | Search `node` with `options` and invoke `callback`. | [
"Search",
"node",
"with",
"options",
"and",
"invoke",
"callback",
"."
] | 279fcee135713b25223dc615cfd8b4a87d5006ce | https://github.com/syntax-tree/mdast-util-heading-range/blob/279fcee135713b25223dc615cfd8b4a87d5006ce/index.js#L10-L38 | train |
syntax-tree/mdast-util-heading-range | index.js | search | function search(root, test, skip, callback) {
var index = -1
var children = root.children
var length = children.length
var depth = null
var start = null
var end = null
var nodes
var clean
var child
while (++index < length) {
child = children[index]
if (closing(child, depth)) {
end = index
break
}
if (opening(child, depth, test)) {
start = index
depth = child.depth
}
}
if (start !== null) {
if (end === null) {
end = length
}
if (skip) {
while (end > start) {
child = children[end - 1]
if (!definition(child)) {
break
}
end--
}
}
nodes = callback(
children[start],
children.slice(start + 1, end),
children[end],
{
parent: root,
start: start,
end: children[end] ? end : null
}
)
clean = []
index = -1
length = nodes && nodes.length
// Ensure no empty nodes are inserted. This could be the case if `end` is
// in `nodes` but no `end` node exists.
while (++index < length) {
if (nodes[index]) {
clean.push(nodes[index])
}
}
if (nodes) {
splice.apply(children, [start, end - start + 1].concat(clean))
}
}
} | javascript | function search(root, test, skip, callback) {
var index = -1
var children = root.children
var length = children.length
var depth = null
var start = null
var end = null
var nodes
var clean
var child
while (++index < length) {
child = children[index]
if (closing(child, depth)) {
end = index
break
}
if (opening(child, depth, test)) {
start = index
depth = child.depth
}
}
if (start !== null) {
if (end === null) {
end = length
}
if (skip) {
while (end > start) {
child = children[end - 1]
if (!definition(child)) {
break
}
end--
}
}
nodes = callback(
children[start],
children.slice(start + 1, end),
children[end],
{
parent: root,
start: start,
end: children[end] ? end : null
}
)
clean = []
index = -1
length = nodes && nodes.length
// Ensure no empty nodes are inserted. This could be the case if `end` is
// in `nodes` but no `end` node exists.
while (++index < length) {
if (nodes[index]) {
clean.push(nodes[index])
}
}
if (nodes) {
splice.apply(children, [start, end - start + 1].concat(clean))
}
}
} | [
"function",
"search",
"(",
"root",
",",
"test",
",",
"skip",
",",
"callback",
")",
"{",
"var",
"index",
"=",
"-",
"1",
"var",
"children",
"=",
"root",
".",
"children",
"var",
"length",
"=",
"children",
".",
"length",
"var",
"depth",
"=",
"null",
"var",
"start",
"=",
"null",
"var",
"end",
"=",
"null",
"var",
"nodes",
"var",
"clean",
"var",
"child",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"child",
"=",
"children",
"[",
"index",
"]",
"if",
"(",
"closing",
"(",
"child",
",",
"depth",
")",
")",
"{",
"end",
"=",
"index",
"break",
"}",
"if",
"(",
"opening",
"(",
"child",
",",
"depth",
",",
"test",
")",
")",
"{",
"start",
"=",
"index",
"depth",
"=",
"child",
".",
"depth",
"}",
"}",
"if",
"(",
"start",
"!==",
"null",
")",
"{",
"if",
"(",
"end",
"===",
"null",
")",
"{",
"end",
"=",
"length",
"}",
"if",
"(",
"skip",
")",
"{",
"while",
"(",
"end",
">",
"start",
")",
"{",
"child",
"=",
"children",
"[",
"end",
"-",
"1",
"]",
"if",
"(",
"!",
"definition",
"(",
"child",
")",
")",
"{",
"break",
"}",
"end",
"--",
"}",
"}",
"nodes",
"=",
"callback",
"(",
"children",
"[",
"start",
"]",
",",
"children",
".",
"slice",
"(",
"start",
"+",
"1",
",",
"end",
")",
",",
"children",
"[",
"end",
"]",
",",
"{",
"parent",
":",
"root",
",",
"start",
":",
"start",
",",
"end",
":",
"children",
"[",
"end",
"]",
"?",
"end",
":",
"null",
"}",
")",
"clean",
"=",
"[",
"]",
"index",
"=",
"-",
"1",
"length",
"=",
"nodes",
"&&",
"nodes",
".",
"length",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"if",
"(",
"nodes",
"[",
"index",
"]",
")",
"{",
"clean",
".",
"push",
"(",
"nodes",
"[",
"index",
"]",
")",
"}",
"}",
"if",
"(",
"nodes",
")",
"{",
"splice",
".",
"apply",
"(",
"children",
",",
"[",
"start",
",",
"end",
"-",
"start",
"+",
"1",
"]",
".",
"concat",
"(",
"clean",
")",
")",
"}",
"}",
"}"
] | Search a node for heading range. | [
"Search",
"a",
"node",
"for",
"heading",
"range",
"."
] | 279fcee135713b25223dc615cfd8b4a87d5006ce | https://github.com/syntax-tree/mdast-util-heading-range/blob/279fcee135713b25223dc615cfd8b4a87d5006ce/index.js#L41-L110 | train |
dmitrisweb/raml-mocker-server | index.js | init | function init (prefs, callback) {
options = _.extend(defaults, prefs);
app = options.app || express();
app.use(cors());
ramlMocker.generate(options, process(function(requestsToMock){
requestsToMock.forEach(function(reqToMock){
addRoute(reqToMock);
});
log(new Array(30).join('='));
log('%s[%s]%s API routes generated', colors.qyan, requestsToMock.length, colors.default);
if(typeof callback === 'function'){
callback(app);
}
}));
var watcher = watch();
var server = launchServer(app);
function close () {
if (watcher) { watcher.close(); }
if (server) { server.close(); }
}
return {
close: close,
server: server,
watcher: watcher
};
} | javascript | function init (prefs, callback) {
options = _.extend(defaults, prefs);
app = options.app || express();
app.use(cors());
ramlMocker.generate(options, process(function(requestsToMock){
requestsToMock.forEach(function(reqToMock){
addRoute(reqToMock);
});
log(new Array(30).join('='));
log('%s[%s]%s API routes generated', colors.qyan, requestsToMock.length, colors.default);
if(typeof callback === 'function'){
callback(app);
}
}));
var watcher = watch();
var server = launchServer(app);
function close () {
if (watcher) { watcher.close(); }
if (server) { server.close(); }
}
return {
close: close,
server: server,
watcher: watcher
};
} | [
"function",
"init",
"(",
"prefs",
",",
"callback",
")",
"{",
"options",
"=",
"_",
".",
"extend",
"(",
"defaults",
",",
"prefs",
")",
";",
"app",
"=",
"options",
".",
"app",
"||",
"express",
"(",
")",
";",
"app",
".",
"use",
"(",
"cors",
"(",
")",
")",
";",
"ramlMocker",
".",
"generate",
"(",
"options",
",",
"process",
"(",
"function",
"(",
"requestsToMock",
")",
"{",
"requestsToMock",
".",
"forEach",
"(",
"function",
"(",
"reqToMock",
")",
"{",
"addRoute",
"(",
"reqToMock",
")",
";",
"}",
")",
";",
"log",
"(",
"new",
"Array",
"(",
"30",
")",
".",
"join",
"(",
"'='",
")",
")",
";",
"log",
"(",
"'%s[%s]%s API routes generated'",
",",
"colors",
".",
"qyan",
",",
"requestsToMock",
".",
"length",
",",
"colors",
".",
"default",
")",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"app",
")",
";",
"}",
"}",
")",
")",
";",
"var",
"watcher",
"=",
"watch",
"(",
")",
";",
"var",
"server",
"=",
"launchServer",
"(",
"app",
")",
";",
"function",
"close",
"(",
")",
"{",
"if",
"(",
"watcher",
")",
"{",
"watcher",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"server",
")",
"{",
"server",
".",
"close",
"(",
")",
";",
"}",
"}",
"return",
"{",
"close",
":",
"close",
",",
"server",
":",
"server",
",",
"watcher",
":",
"watcher",
"}",
";",
"}"
] | Initializing RAML mocker server
@param {Function} cb callback executed af
@param {Object} prefs configuration object
@return {[type]} [description] | [
"Initializing",
"RAML",
"mocker",
"server"
] | baaa9313449ebafb5c9fa9e3d3dc4682cf9494b9 | https://github.com/dmitrisweb/raml-mocker-server/blob/baaa9313449ebafb5c9fa9e3d3dc4682cf9494b9/index.js#L31-L61 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | logout | function logout(_ref3) {
var state = _ref3.state,
commit = _ref3.commit;
commit('c3s/user/SET_CURRENT_USER', null, {
root: true
});
commit('SET_ANON', false);
} | javascript | function logout(_ref3) {
var state = _ref3.state,
commit = _ref3.commit;
commit('c3s/user/SET_CURRENT_USER', null, {
root: true
});
commit('SET_ANON', false);
} | [
"function",
"logout",
"(",
"_ref3",
")",
"{",
"var",
"state",
"=",
"_ref3",
".",
"state",
",",
"commit",
"=",
"_ref3",
".",
"commit",
";",
"commit",
"(",
"'c3s/user/SET_CURRENT_USER'",
",",
"null",
",",
"{",
"root",
":",
"true",
"}",
")",
";",
"commit",
"(",
"'SET_ANON'",
",",
"false",
")",
";",
"}"
] | Logout user and remove from local store
@param state
@param commit | [
"Logout",
"user",
"and",
"remove",
"from",
"local",
"store"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L201-L208 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | getActivities | function getActivities(_ref, _ref2) {
var state = _ref.state,
commit = _ref.commit,
dispatch = _ref.dispatch,
rootState = _ref.rootState;
var _ref3 = _slicedToArray(_ref2, 2),
search = _ref3[0],
limit = _ref3[1];
search = rison.encode(search);
return makeRequest(commit, rootState.c3s.client.apis.Activities.get_activities, {
search_term: search || undefined,
limit: limit || 100
}, 'c3s/activity/SET_ACTIVITIES');
} | javascript | function getActivities(_ref, _ref2) {
var state = _ref.state,
commit = _ref.commit,
dispatch = _ref.dispatch,
rootState = _ref.rootState;
var _ref3 = _slicedToArray(_ref2, 2),
search = _ref3[0],
limit = _ref3[1];
search = rison.encode(search);
return makeRequest(commit, rootState.c3s.client.apis.Activities.get_activities, {
search_term: search || undefined,
limit: limit || 100
}, 'c3s/activity/SET_ACTIVITIES');
} | [
"function",
"getActivities",
"(",
"_ref",
",",
"_ref2",
")",
"{",
"var",
"state",
"=",
"_ref",
".",
"state",
",",
"commit",
"=",
"_ref",
".",
"commit",
",",
"dispatch",
"=",
"_ref",
".",
"dispatch",
",",
"rootState",
"=",
"_ref",
".",
"rootState",
";",
"var",
"_ref3",
"=",
"_slicedToArray",
"(",
"_ref2",
",",
"2",
")",
",",
"search",
"=",
"_ref3",
"[",
"0",
"]",
",",
"limit",
"=",
"_ref3",
"[",
"1",
"]",
";",
"search",
"=",
"rison",
".",
"encode",
"(",
"search",
")",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Activities",
".",
"get_activities",
",",
"{",
"search_term",
":",
"search",
"||",
"undefined",
",",
"limit",
":",
"limit",
"||",
"100",
"}",
",",
"'c3s/activity/SET_ACTIVITIES'",
")",
";",
"}"
] | Retrieve an array of activities based on a provided query object
@param state
@param commit
@param dispatch
@param rootState
@param search
@returns {Promise<*|boolean|void>} | [
"Retrieve",
"an",
"array",
"of",
"activities",
"based",
"on",
"a",
"provided",
"query",
"object"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L476-L491 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | createActivity | function createActivity(_ref9, activity) {
var state = _ref9.state,
commit = _ref9.commit,
rootState = _ref9.rootState;
return makeRequest(commit, rootState.c3s.client.apis.Activities.create_activity, {
activity: activity
}, 'c3s/activity/SET_ACTIVITY');
} | javascript | function createActivity(_ref9, activity) {
var state = _ref9.state,
commit = _ref9.commit,
rootState = _ref9.rootState;
return makeRequest(commit, rootState.c3s.client.apis.Activities.create_activity, {
activity: activity
}, 'c3s/activity/SET_ACTIVITY');
} | [
"function",
"createActivity",
"(",
"_ref9",
",",
"activity",
")",
"{",
"var",
"state",
"=",
"_ref9",
".",
"state",
",",
"commit",
"=",
"_ref9",
".",
"commit",
",",
"rootState",
"=",
"_ref9",
".",
"rootState",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Activities",
".",
"create_activity",
",",
"{",
"activity",
":",
"activity",
"}",
",",
"'c3s/activity/SET_ACTIVITY'",
")",
";",
"}"
] | Create an activity
@param state
@param commit
@param rootState
@param activity
@returns {Promise<*|boolean|void>} | [
"Create",
"an",
"activity"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L576-L583 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | deleteActivity | function deleteActivity(_ref10, _ref11) {
var state = _ref10.state,
commit = _ref10.commit,
rootState = _ref10.rootState;
var _ref12 = _slicedToArray(_ref11, 2),
pid = _ref12[0],
localRemove = _ref12[1];
if (localRemove) commit('c3s/activity/SET_ACTIVITY', null);
return makeRequest(commit, rootState.c3s.client.apis.Activities.delete_activity, {
id: pid
}, undefined);
} | javascript | function deleteActivity(_ref10, _ref11) {
var state = _ref10.state,
commit = _ref10.commit,
rootState = _ref10.rootState;
var _ref12 = _slicedToArray(_ref11, 2),
pid = _ref12[0],
localRemove = _ref12[1];
if (localRemove) commit('c3s/activity/SET_ACTIVITY', null);
return makeRequest(commit, rootState.c3s.client.apis.Activities.delete_activity, {
id: pid
}, undefined);
} | [
"function",
"deleteActivity",
"(",
"_ref10",
",",
"_ref11",
")",
"{",
"var",
"state",
"=",
"_ref10",
".",
"state",
",",
"commit",
"=",
"_ref10",
".",
"commit",
",",
"rootState",
"=",
"_ref10",
".",
"rootState",
";",
"var",
"_ref12",
"=",
"_slicedToArray",
"(",
"_ref11",
",",
"2",
")",
",",
"pid",
"=",
"_ref12",
"[",
"0",
"]",
",",
"localRemove",
"=",
"_ref12",
"[",
"1",
"]",
";",
"if",
"(",
"localRemove",
")",
"commit",
"(",
"'c3s/activity/SET_ACTIVITY'",
",",
"null",
")",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Activities",
".",
"delete_activity",
",",
"{",
"id",
":",
"pid",
"}",
",",
"undefined",
")",
";",
"}"
] | Delete an activity matching the supplied ID
@param state
@param commit
@param rootState
@param pid
@param localRemove
@returns {Promise<*|boolean|void>} | [
"Delete",
"an",
"activity",
"matching",
"the",
"supplied",
"ID"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L594-L607 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | deleteTasks | function deleteTasks(_ref12, tasks) {
var state = _ref12.state,
commit = _ref12.commit,
dispatch = _ref12.dispatch,
rootState = _ref12.rootState;
dispatch('SET_TASKS', null);
return makeRequest(commit, rootState.c3s.client.apis.Tasks.delete_tasks, {
tasks: tasks
}, 'c3s/task/SET_TASKS');
} | javascript | function deleteTasks(_ref12, tasks) {
var state = _ref12.state,
commit = _ref12.commit,
dispatch = _ref12.dispatch,
rootState = _ref12.rootState;
dispatch('SET_TASKS', null);
return makeRequest(commit, rootState.c3s.client.apis.Tasks.delete_tasks, {
tasks: tasks
}, 'c3s/task/SET_TASKS');
} | [
"function",
"deleteTasks",
"(",
"_ref12",
",",
"tasks",
")",
"{",
"var",
"state",
"=",
"_ref12",
".",
"state",
",",
"commit",
"=",
"_ref12",
".",
"commit",
",",
"dispatch",
"=",
"_ref12",
".",
"dispatch",
",",
"rootState",
"=",
"_ref12",
".",
"rootState",
";",
"dispatch",
"(",
"'SET_TASKS'",
",",
"null",
")",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Tasks",
".",
"delete_tasks",
",",
"{",
"tasks",
":",
"tasks",
"}",
",",
"'c3s/task/SET_TASKS'",
")",
";",
"}"
] | Delete an array of tasks
@param state
@param commit
@param dispatch
@param rootState
@param tasks
@returns {Promise<*|boolean|void>} | [
"Delete",
"an",
"array",
"of",
"tasks"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L877-L886 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | getProjects | function getProjects(_ref, _ref2) {
var state = _ref.state,
commit = _ref.commit,
dispatch = _ref.dispatch,
rootState = _ref.rootState;
var _ref3 = _slicedToArray(_ref2, 2),
search = _ref3[0],
limit = _ref3[1];
search = rison.encode(search);
return makeRequest(commit, rootState.c3s.client.apis.Projects.get_projects, {
search_term: search || undefined,
limit: limit || 100
}, 'c3s/project/SET_PROJECTS');
} | javascript | function getProjects(_ref, _ref2) {
var state = _ref.state,
commit = _ref.commit,
dispatch = _ref.dispatch,
rootState = _ref.rootState;
var _ref3 = _slicedToArray(_ref2, 2),
search = _ref3[0],
limit = _ref3[1];
search = rison.encode(search);
return makeRequest(commit, rootState.c3s.client.apis.Projects.get_projects, {
search_term: search || undefined,
limit: limit || 100
}, 'c3s/project/SET_PROJECTS');
} | [
"function",
"getProjects",
"(",
"_ref",
",",
"_ref2",
")",
"{",
"var",
"state",
"=",
"_ref",
".",
"state",
",",
"commit",
"=",
"_ref",
".",
"commit",
",",
"dispatch",
"=",
"_ref",
".",
"dispatch",
",",
"rootState",
"=",
"_ref",
".",
"rootState",
";",
"var",
"_ref3",
"=",
"_slicedToArray",
"(",
"_ref2",
",",
"2",
")",
",",
"search",
"=",
"_ref3",
"[",
"0",
"]",
",",
"limit",
"=",
"_ref3",
"[",
"1",
"]",
";",
"search",
"=",
"rison",
".",
"encode",
"(",
"search",
")",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Projects",
".",
"get_projects",
",",
"{",
"search_term",
":",
"search",
"||",
"undefined",
",",
"limit",
":",
"limit",
"||",
"100",
"}",
",",
"'c3s/project/SET_PROJECTS'",
")",
";",
"}"
] | Retrieve an array of projects based on a provided query object
@param state
@param commit
@param dispatch
@param rootState
@param search
@returns {Promise<*|boolean|void>} | [
"Retrieve",
"an",
"array",
"of",
"projects",
"based",
"on",
"a",
"provided",
"query",
"object"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L1239-L1254 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | createProject | function createProject(_ref8, project) {
var state = _ref8.state,
commit = _ref8.commit,
rootState = _ref8.rootState;
return makeRequest(commit, rootState.c3s.client.apis.Projects.create_project, {
project: project
}, 'c3s/project/SET_PROJECT');
} | javascript | function createProject(_ref8, project) {
var state = _ref8.state,
commit = _ref8.commit,
rootState = _ref8.rootState;
return makeRequest(commit, rootState.c3s.client.apis.Projects.create_project, {
project: project
}, 'c3s/project/SET_PROJECT');
} | [
"function",
"createProject",
"(",
"_ref8",
",",
"project",
")",
"{",
"var",
"state",
"=",
"_ref8",
".",
"state",
",",
"commit",
"=",
"_ref8",
".",
"commit",
",",
"rootState",
"=",
"_ref8",
".",
"rootState",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Projects",
".",
"create_project",
",",
"{",
"project",
":",
"project",
"}",
",",
"'c3s/project/SET_PROJECT'",
")",
";",
"}"
] | Create a project
@param state
@param commit
@param rootState
@param activity
@returns {Promise<*|boolean|void>} | [
"Create",
"a",
"project"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L1341-L1348 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | deleteProject | function deleteProject(_ref9, _ref10) {
var state = _ref9.state,
commit = _ref9.commit,
rootState = _ref9.rootState;
var _ref11 = _slicedToArray(_ref10, 2),
pid = _ref11[0],
localRemove = _ref11[1];
if (localRemove) commit('c3s/project/SET_PROJECT', null);
return makeRequest(commit, rootState.c3s.client.apis.Projects.delete_project, {
id: pid
}, undefined);
} | javascript | function deleteProject(_ref9, _ref10) {
var state = _ref9.state,
commit = _ref9.commit,
rootState = _ref9.rootState;
var _ref11 = _slicedToArray(_ref10, 2),
pid = _ref11[0],
localRemove = _ref11[1];
if (localRemove) commit('c3s/project/SET_PROJECT', null);
return makeRequest(commit, rootState.c3s.client.apis.Projects.delete_project, {
id: pid
}, undefined);
} | [
"function",
"deleteProject",
"(",
"_ref9",
",",
"_ref10",
")",
"{",
"var",
"state",
"=",
"_ref9",
".",
"state",
",",
"commit",
"=",
"_ref9",
".",
"commit",
",",
"rootState",
"=",
"_ref9",
".",
"rootState",
";",
"var",
"_ref11",
"=",
"_slicedToArray",
"(",
"_ref10",
",",
"2",
")",
",",
"pid",
"=",
"_ref11",
"[",
"0",
"]",
",",
"localRemove",
"=",
"_ref11",
"[",
"1",
"]",
";",
"if",
"(",
"localRemove",
")",
"commit",
"(",
"'c3s/project/SET_PROJECT'",
",",
"null",
")",
";",
"return",
"makeRequest",
"(",
"commit",
",",
"rootState",
".",
"c3s",
".",
"client",
".",
"apis",
".",
"Projects",
".",
"delete_project",
",",
"{",
"id",
":",
"pid",
"}",
",",
"undefined",
")",
";",
"}"
] | Delete a project matching the supplied ID
@param state
@param commit
@param rootState
@param pid
@param localRemove
@returns {Promise<*|boolean|void>} | [
"Delete",
"a",
"project",
"matching",
"the",
"supplied",
"ID"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L1359-L1372 | train |
CitizenScienceCenter/vuex-c3s | dist/vuex-c3s.es.js | install | function install(Vue) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Swagger({
url: options.swaggerURL,
requestInterceptor: function requestInterceptor(req) {
// req.headers['content-type'] = 'application/json'
if (options.store.state.c3s && options.store.state.c3s.user) {
var u = options.store.state.c3s.user.currentUser;
if (u) {
req.headers['X-API-KEY'] = u.api_key;
}
} else {
console.log('c3s: state not loaded or not found');
}
return req;
}
}).then(function (client) {
var store = options.store;
var swaggerURL = options.swaggerURL;
if (!store || !swaggerURL) {
console.error('C3S: Missing store and/or Swagger URL params.');
return;
}
console.log('Loaded from ' + options.swaggerURL);
for (var i in modules) {
var m = modules[i];
var name = m['name'];
var preserve = true;
if (Array.isArray(name)) {
if (store.state.c3s && store.state.c3s[name[1]] === undefined) {
preserve = false;
}
} else {
if (store.state[name] === undefined) {
preserve = false;
}
}
store.registerModule(name, m['module'], {
preserveState: preserve
}); // if (store.state.hasOwnProperty(m['name']) === false) {
// console.error('C3S: C3S vuex module is not correctly initialized. Please check the module name:', m['name']);
// return;
// }
// TODO check why store reports this as false when it is created
}
store.commit('c3s/SET_API', client);
var isLoaded = function isLoaded() {
if (store.c3s !== undefined && store.c3s.client !== null) {
return true;
} else {
return false;
}
};
Vue.prototype.$c3s = {
store: C3SStore,
loaded: isLoaded
};
Vue.c3s = {
store: C3SStore,
loaded: isLoaded
};
}).catch(function (err) {
console.error('C3S: URL was not found or an initialisation error occurred');
console.error(err);
});
} | javascript | function install(Vue) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Swagger({
url: options.swaggerURL,
requestInterceptor: function requestInterceptor(req) {
// req.headers['content-type'] = 'application/json'
if (options.store.state.c3s && options.store.state.c3s.user) {
var u = options.store.state.c3s.user.currentUser;
if (u) {
req.headers['X-API-KEY'] = u.api_key;
}
} else {
console.log('c3s: state not loaded or not found');
}
return req;
}
}).then(function (client) {
var store = options.store;
var swaggerURL = options.swaggerURL;
if (!store || !swaggerURL) {
console.error('C3S: Missing store and/or Swagger URL params.');
return;
}
console.log('Loaded from ' + options.swaggerURL);
for (var i in modules) {
var m = modules[i];
var name = m['name'];
var preserve = true;
if (Array.isArray(name)) {
if (store.state.c3s && store.state.c3s[name[1]] === undefined) {
preserve = false;
}
} else {
if (store.state[name] === undefined) {
preserve = false;
}
}
store.registerModule(name, m['module'], {
preserveState: preserve
}); // if (store.state.hasOwnProperty(m['name']) === false) {
// console.error('C3S: C3S vuex module is not correctly initialized. Please check the module name:', m['name']);
// return;
// }
// TODO check why store reports this as false when it is created
}
store.commit('c3s/SET_API', client);
var isLoaded = function isLoaded() {
if (store.c3s !== undefined && store.c3s.client !== null) {
return true;
} else {
return false;
}
};
Vue.prototype.$c3s = {
store: C3SStore,
loaded: isLoaded
};
Vue.c3s = {
store: C3SStore,
loaded: isLoaded
};
}).catch(function (err) {
console.error('C3S: URL was not found or an initialisation error occurred');
console.error(err);
});
} | [
"function",
"install",
"(",
"Vue",
")",
"{",
"var",
"options",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"{",
"}",
";",
"Swagger",
"(",
"{",
"url",
":",
"options",
".",
"swaggerURL",
",",
"requestInterceptor",
":",
"function",
"requestInterceptor",
"(",
"req",
")",
"{",
"if",
"(",
"options",
".",
"store",
".",
"state",
".",
"c3s",
"&&",
"options",
".",
"store",
".",
"state",
".",
"c3s",
".",
"user",
")",
"{",
"var",
"u",
"=",
"options",
".",
"store",
".",
"state",
".",
"c3s",
".",
"user",
".",
"currentUser",
";",
"if",
"(",
"u",
")",
"{",
"req",
".",
"headers",
"[",
"'X-API-KEY'",
"]",
"=",
"u",
".",
"api_key",
";",
"}",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'c3s: state not loaded or not found'",
")",
";",
"}",
"return",
"req",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"client",
")",
"{",
"var",
"store",
"=",
"options",
".",
"store",
";",
"var",
"swaggerURL",
"=",
"options",
".",
"swaggerURL",
";",
"if",
"(",
"!",
"store",
"||",
"!",
"swaggerURL",
")",
"{",
"console",
".",
"error",
"(",
"'C3S: Missing store and/or Swagger URL params.'",
")",
";",
"return",
";",
"}",
"console",
".",
"log",
"(",
"'Loaded from '",
"+",
"options",
".",
"swaggerURL",
")",
";",
"for",
"(",
"var",
"i",
"in",
"modules",
")",
"{",
"var",
"m",
"=",
"modules",
"[",
"i",
"]",
";",
"var",
"name",
"=",
"m",
"[",
"'name'",
"]",
";",
"var",
"preserve",
"=",
"true",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"name",
")",
")",
"{",
"if",
"(",
"store",
".",
"state",
".",
"c3s",
"&&",
"store",
".",
"state",
".",
"c3s",
"[",
"name",
"[",
"1",
"]",
"]",
"===",
"undefined",
")",
"{",
"preserve",
"=",
"false",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"store",
".",
"state",
"[",
"name",
"]",
"===",
"undefined",
")",
"{",
"preserve",
"=",
"false",
";",
"}",
"}",
"store",
".",
"registerModule",
"(",
"name",
",",
"m",
"[",
"'module'",
"]",
",",
"{",
"preserveState",
":",
"preserve",
"}",
")",
";",
"}",
"store",
".",
"commit",
"(",
"'c3s/SET_API'",
",",
"client",
")",
";",
"var",
"isLoaded",
"=",
"function",
"isLoaded",
"(",
")",
"{",
"if",
"(",
"store",
".",
"c3s",
"!==",
"undefined",
"&&",
"store",
".",
"c3s",
".",
"client",
"!==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
";",
"Vue",
".",
"prototype",
".",
"$c3s",
"=",
"{",
"store",
":",
"C3SStore",
",",
"loaded",
":",
"isLoaded",
"}",
";",
"Vue",
".",
"c3s",
"=",
"{",
"store",
":",
"C3SStore",
",",
"loaded",
":",
"isLoaded",
"}",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'C3S: URL was not found or an initialisation error occurred'",
")",
";",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | Setup function for the plugin, must provide a store and a Swagger file URL
@param Vue
@param options | [
"Setup",
"function",
"for",
"the",
"plugin",
"must",
"provide",
"a",
"store",
"and",
"a",
"Swagger",
"file",
"URL"
] | 6ecd72fc90ca84e87f1a84de1e32c434afb60e48 | https://github.com/CitizenScienceCenter/vuex-c3s/blob/6ecd72fc90ca84e87f1a84de1e32c434afb60e48/dist/vuex-c3s.es.js#L1622-L1697 | train |
keymetrics/trassingue | src/trace-writer.js | TraceWriter | function TraceWriter(logger, options) {
options = options || {};
EventEmitter.call(this);
/** @private */
this.logger_ = logger;
/** @private */
this.config_ = options;
/** @private {Array<string>} stringified traces to be published */
this.buffer_ = [];
/** @private {Object} default labels to be attached to written spans */
this.defaultLabels_ = {};
/** @private {Boolean} whether the trace writer is active */
this.isActive = true;
} | javascript | function TraceWriter(logger, options) {
options = options || {};
EventEmitter.call(this);
/** @private */
this.logger_ = logger;
/** @private */
this.config_ = options;
/** @private {Array<string>} stringified traces to be published */
this.buffer_ = [];
/** @private {Object} default labels to be attached to written spans */
this.defaultLabels_ = {};
/** @private {Boolean} whether the trace writer is active */
this.isActive = true;
} | [
"function",
"TraceWriter",
"(",
"logger",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"logger_",
"=",
"logger",
";",
"this",
".",
"config_",
"=",
"options",
";",
"this",
".",
"buffer_",
"=",
"[",
"]",
";",
"this",
".",
"defaultLabels_",
"=",
"{",
"}",
";",
"this",
".",
"isActive",
"=",
"true",
";",
"}"
] | Creates a basic trace writer.
@param {!Logger} logger The Trace Agent's logger object.
@param {Object} config A config object containing information about
authorization credentials.
@constructor | [
"Creates",
"a",
"basic",
"trace",
"writer",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/trace-writer.js#L38-L57 | train |
mattbierner/hamt_plus | hamt.js | arraySpliceOut | function arraySpliceOut(mutate, at, arr) {
var newLen = arr.length - 1;
var i = 0;
var g = 0;
var out = arr;
if (mutate) {
i = g = at;
} else {
out = new Array(newLen);
while (i < at) {
out[g++] = arr[i++];
}
}
++i;
while (i <= newLen) {
out[g++] = arr[i++];
}if (mutate) {
out.length = newLen;
}
return out;
} | javascript | function arraySpliceOut(mutate, at, arr) {
var newLen = arr.length - 1;
var i = 0;
var g = 0;
var out = arr;
if (mutate) {
i = g = at;
} else {
out = new Array(newLen);
while (i < at) {
out[g++] = arr[i++];
}
}
++i;
while (i <= newLen) {
out[g++] = arr[i++];
}if (mutate) {
out.length = newLen;
}
return out;
} | [
"function",
"arraySpliceOut",
"(",
"mutate",
",",
"at",
",",
"arr",
")",
"{",
"var",
"newLen",
"=",
"arr",
".",
"length",
"-",
"1",
";",
"var",
"i",
"=",
"0",
";",
"var",
"g",
"=",
"0",
";",
"var",
"out",
"=",
"arr",
";",
"if",
"(",
"mutate",
")",
"{",
"i",
"=",
"g",
"=",
"at",
";",
"}",
"else",
"{",
"out",
"=",
"new",
"Array",
"(",
"newLen",
")",
";",
"while",
"(",
"i",
"<",
"at",
")",
"{",
"out",
"[",
"g",
"++",
"]",
"=",
"arr",
"[",
"i",
"++",
"]",
";",
"}",
"}",
"++",
"i",
";",
"while",
"(",
"i",
"<=",
"newLen",
")",
"{",
"out",
"[",
"g",
"++",
"]",
"=",
"arr",
"[",
"i",
"++",
"]",
";",
"}",
"if",
"(",
"mutate",
")",
"{",
"out",
".",
"length",
"=",
"newLen",
";",
"}",
"return",
"out",
";",
"}"
] | Remove a value from an array.
@param mutate Should the input array be mutated?
@param at Index to remove.
@param arr Array. | [
"Remove",
"a",
"value",
"from",
"an",
"array",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L111-L131 | train |
mattbierner/hamt_plus | hamt.js | arraySpliceIn | function arraySpliceIn(mutate, at, v, arr) {
var len = arr.length;
if (mutate) {
var _i = len;
while (_i >= at) {
arr[_i--] = arr[_i];
}arr[at] = v;
return arr;
}
var i = 0,
g = 0;
var out = new Array(len + 1);
while (i < at) {
out[g++] = arr[i++];
}out[at] = v;
while (i < len) {
out[++g] = arr[i++];
}return out;
} | javascript | function arraySpliceIn(mutate, at, v, arr) {
var len = arr.length;
if (mutate) {
var _i = len;
while (_i >= at) {
arr[_i--] = arr[_i];
}arr[at] = v;
return arr;
}
var i = 0,
g = 0;
var out = new Array(len + 1);
while (i < at) {
out[g++] = arr[i++];
}out[at] = v;
while (i < len) {
out[++g] = arr[i++];
}return out;
} | [
"function",
"arraySpliceIn",
"(",
"mutate",
",",
"at",
",",
"v",
",",
"arr",
")",
"{",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"if",
"(",
"mutate",
")",
"{",
"var",
"_i",
"=",
"len",
";",
"while",
"(",
"_i",
">=",
"at",
")",
"{",
"arr",
"[",
"_i",
"--",
"]",
"=",
"arr",
"[",
"_i",
"]",
";",
"}",
"arr",
"[",
"at",
"]",
"=",
"v",
";",
"return",
"arr",
";",
"}",
"var",
"i",
"=",
"0",
",",
"g",
"=",
"0",
";",
"var",
"out",
"=",
"new",
"Array",
"(",
"len",
"+",
"1",
")",
";",
"while",
"(",
"i",
"<",
"at",
")",
"{",
"out",
"[",
"g",
"++",
"]",
"=",
"arr",
"[",
"i",
"++",
"]",
";",
"}",
"out",
"[",
"at",
"]",
"=",
"v",
";",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"out",
"[",
"++",
"g",
"]",
"=",
"arr",
"[",
"i",
"++",
"]",
";",
"}",
"return",
"out",
";",
"}"
] | Insert a value into an array.
@param mutate Should the input array be mutated?
@param at Index to insert at.
@param v Value to insert,
@param arr Array. | [
"Insert",
"a",
"value",
"into",
"an",
"array",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L141-L159 | train |
mattbierner/hamt_plus | hamt.js | Leaf | function Leaf(edit, hash, key, value) {
return {
type: LEAF,
edit: edit,
hash: hash,
key: key,
value: value,
_modify: Leaf__modify
};
} | javascript | function Leaf(edit, hash, key, value) {
return {
type: LEAF,
edit: edit,
hash: hash,
key: key,
value: value,
_modify: Leaf__modify
};
} | [
"function",
"Leaf",
"(",
"edit",
",",
"hash",
",",
"key",
",",
"value",
")",
"{",
"return",
"{",
"type",
":",
"LEAF",
",",
"edit",
":",
"edit",
",",
"hash",
":",
"hash",
",",
"key",
":",
"key",
",",
"value",
":",
"value",
",",
"_modify",
":",
"Leaf__modify",
"}",
";",
"}"
] | Leaf holding a value.
@member edit Edit of the node.
@member hash Hash of key.
@member key Key.
@member value Value stored. | [
"Leaf",
"holding",
"a",
"value",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L187-L196 | train |
mattbierner/hamt_plus | hamt.js | Collision | function Collision(edit, hash, children) {
return {
type: COLLISION,
edit: edit,
hash: hash,
children: children,
_modify: Collision__modify
};
} | javascript | function Collision(edit, hash, children) {
return {
type: COLLISION,
edit: edit,
hash: hash,
children: children,
_modify: Collision__modify
};
} | [
"function",
"Collision",
"(",
"edit",
",",
"hash",
",",
"children",
")",
"{",
"return",
"{",
"type",
":",
"COLLISION",
",",
"edit",
":",
"edit",
",",
"hash",
":",
"hash",
",",
"children",
":",
"children",
",",
"_modify",
":",
"Collision__modify",
"}",
";",
"}"
] | Leaf holding multiple values with the same hash but different keys.
@member edit Edit of the node.
@member hash Hash of key.
@member children Array of collision children node. | [
"Leaf",
"holding",
"multiple",
"values",
"with",
"the",
"same",
"hash",
"but",
"different",
"keys",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L205-L213 | train |
mattbierner/hamt_plus | hamt.js | IndexedNode | function IndexedNode(edit, mask, children) {
return {
type: INDEX,
edit: edit,
mask: mask,
children: children,
_modify: IndexedNode__modify
};
} | javascript | function IndexedNode(edit, mask, children) {
return {
type: INDEX,
edit: edit,
mask: mask,
children: children,
_modify: IndexedNode__modify
};
} | [
"function",
"IndexedNode",
"(",
"edit",
",",
"mask",
",",
"children",
")",
"{",
"return",
"{",
"type",
":",
"INDEX",
",",
"edit",
":",
"edit",
",",
"mask",
":",
"mask",
",",
"children",
":",
"children",
",",
"_modify",
":",
"IndexedNode__modify",
"}",
";",
"}"
] | Internal node with a sparse set of children.
Uses a bitmap and array to pack children.
@member edit Edit of the node.
@member mask Bitmap that encode the positions of children in the array.
@member children Array of child nodes. | [
"Internal",
"node",
"with",
"a",
"sparse",
"set",
"of",
"children",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L224-L232 | train |
mattbierner/hamt_plus | hamt.js | ArrayNode | function ArrayNode(edit, size, children) {
return {
type: ARRAY,
edit: edit,
size: size,
children: children,
_modify: ArrayNode__modify
};
} | javascript | function ArrayNode(edit, size, children) {
return {
type: ARRAY,
edit: edit,
size: size,
children: children,
_modify: ArrayNode__modify
};
} | [
"function",
"ArrayNode",
"(",
"edit",
",",
"size",
",",
"children",
")",
"{",
"return",
"{",
"type",
":",
"ARRAY",
",",
"edit",
":",
"edit",
",",
"size",
":",
"size",
",",
"children",
":",
"children",
",",
"_modify",
":",
"ArrayNode__modify",
"}",
";",
"}"
] | Internal node with many children.
@member edit Edit of the node.
@member size Number of children.
@member children Array of child nodes. | [
"Internal",
"node",
"with",
"many",
"children",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L241-L249 | train |
mattbierner/hamt_plus | hamt.js | isLeaf | function isLeaf(node) {
return node === empty || node.type === LEAF || node.type === COLLISION;
} | javascript | function isLeaf(node) {
return node === empty || node.type === LEAF || node.type === COLLISION;
} | [
"function",
"isLeaf",
"(",
"node",
")",
"{",
"return",
"node",
"===",
"empty",
"||",
"node",
".",
"type",
"===",
"LEAF",
"||",
"node",
".",
"type",
"===",
"COLLISION",
";",
"}"
] | Is `node` a leaf node? | [
"Is",
"node",
"a",
"leaf",
"node?"
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L254-L256 | train |
mattbierner/hamt_plus | hamt.js | pack | function pack(edit, count, removed, elements) {
var children = new Array(count - 1);
var g = 0;
var bitmap = 0;
for (var i = 0, len = elements.length; i < len; ++i) {
if (i !== removed) {
var elem = elements[i];
if (elem && !isEmptyNode(elem)) {
children[g++] = elem;
bitmap |= 1 << i;
}
}
}
return IndexedNode(edit, bitmap, children);
} | javascript | function pack(edit, count, removed, elements) {
var children = new Array(count - 1);
var g = 0;
var bitmap = 0;
for (var i = 0, len = elements.length; i < len; ++i) {
if (i !== removed) {
var elem = elements[i];
if (elem && !isEmptyNode(elem)) {
children[g++] = elem;
bitmap |= 1 << i;
}
}
}
return IndexedNode(edit, bitmap, children);
} | [
"function",
"pack",
"(",
"edit",
",",
"count",
",",
"removed",
",",
"elements",
")",
"{",
"var",
"children",
"=",
"new",
"Array",
"(",
"count",
"-",
"1",
")",
";",
"var",
"g",
"=",
"0",
";",
"var",
"bitmap",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"elements",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"if",
"(",
"i",
"!==",
"removed",
")",
"{",
"var",
"elem",
"=",
"elements",
"[",
"i",
"]",
";",
"if",
"(",
"elem",
"&&",
"!",
"isEmptyNode",
"(",
"elem",
")",
")",
"{",
"children",
"[",
"g",
"++",
"]",
"=",
"elem",
";",
"bitmap",
"|=",
"1",
"<<",
"i",
";",
"}",
"}",
"}",
"return",
"IndexedNode",
"(",
"edit",
",",
"bitmap",
",",
"children",
")",
";",
"}"
] | Collapse an array node into a indexed node.
@param edit Current edit.
@param count Number of elements in new array.
@param removed Index of removed element.
@param elements Array node children before remove. | [
"Collapse",
"an",
"array",
"node",
"into",
"a",
"indexed",
"node",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L289-L303 | train |
mattbierner/hamt_plus | hamt.js | mergeLeaves | function mergeLeaves(edit, shift, h1, n1, h2, n2) {
if (h1 === h2) return Collision(edit, h1, [n2, n1]);
var subH1 = hashFragment(shift, h1);
var subH2 = hashFragment(shift, h2);
return IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), subH1 === subH2 ? [mergeLeaves(edit, shift + SIZE, h1, n1, h2, n2)] : subH1 < subH2 ? [n1, n2] : [n2, n1]);
} | javascript | function mergeLeaves(edit, shift, h1, n1, h2, n2) {
if (h1 === h2) return Collision(edit, h1, [n2, n1]);
var subH1 = hashFragment(shift, h1);
var subH2 = hashFragment(shift, h2);
return IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), subH1 === subH2 ? [mergeLeaves(edit, shift + SIZE, h1, n1, h2, n2)] : subH1 < subH2 ? [n1, n2] : [n2, n1]);
} | [
"function",
"mergeLeaves",
"(",
"edit",
",",
"shift",
",",
"h1",
",",
"n1",
",",
"h2",
",",
"n2",
")",
"{",
"if",
"(",
"h1",
"===",
"h2",
")",
"return",
"Collision",
"(",
"edit",
",",
"h1",
",",
"[",
"n2",
",",
"n1",
"]",
")",
";",
"var",
"subH1",
"=",
"hashFragment",
"(",
"shift",
",",
"h1",
")",
";",
"var",
"subH2",
"=",
"hashFragment",
"(",
"shift",
",",
"h2",
")",
";",
"return",
"IndexedNode",
"(",
"edit",
",",
"toBitmap",
"(",
"subH1",
")",
"|",
"toBitmap",
"(",
"subH2",
")",
",",
"subH1",
"===",
"subH2",
"?",
"[",
"mergeLeaves",
"(",
"edit",
",",
"shift",
"+",
"SIZE",
",",
"h1",
",",
"n1",
",",
"h2",
",",
"n2",
")",
"]",
":",
"subH1",
"<",
"subH2",
"?",
"[",
"n1",
",",
"n2",
"]",
":",
"[",
"n2",
",",
"n1",
"]",
")",
";",
"}"
] | Merge two leaf nodes.
@param shift Current shift.
@param h1 Node 1 hash.
@param n1 Node 1.
@param h2 Node 2 hash.
@param n2 Node 2. | [
"Merge",
"two",
"leaf",
"nodes",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L314-L320 | train |
mattbierner/hamt_plus | hamt.js | updateCollisionList | function updateCollisionList(mutate, edit, keyEq, h, list, f, k, size) {
var len = list.length;
for (var i = 0; i < len; ++i) {
var child = list[i];
if (keyEq(k, child.key)) {
var value = child.value;
var _newValue = f(value);
if (_newValue === value) return list;
if (_newValue === nothing) {
--size.value;
return arraySpliceOut(mutate, i, list);
}
return arrayUpdate(mutate, i, Leaf(edit, h, k, _newValue), list);
}
}
var newValue = f();
if (newValue === nothing) return list;
++size.value;
return arrayUpdate(mutate, len, Leaf(edit, h, k, newValue), list);
} | javascript | function updateCollisionList(mutate, edit, keyEq, h, list, f, k, size) {
var len = list.length;
for (var i = 0; i < len; ++i) {
var child = list[i];
if (keyEq(k, child.key)) {
var value = child.value;
var _newValue = f(value);
if (_newValue === value) return list;
if (_newValue === nothing) {
--size.value;
return arraySpliceOut(mutate, i, list);
}
return arrayUpdate(mutate, i, Leaf(edit, h, k, _newValue), list);
}
}
var newValue = f();
if (newValue === nothing) return list;
++size.value;
return arrayUpdate(mutate, len, Leaf(edit, h, k, newValue), list);
} | [
"function",
"updateCollisionList",
"(",
"mutate",
",",
"edit",
",",
"keyEq",
",",
"h",
",",
"list",
",",
"f",
",",
"k",
",",
"size",
")",
"{",
"var",
"len",
"=",
"list",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"var",
"child",
"=",
"list",
"[",
"i",
"]",
";",
"if",
"(",
"keyEq",
"(",
"k",
",",
"child",
".",
"key",
")",
")",
"{",
"var",
"value",
"=",
"child",
".",
"value",
";",
"var",
"_newValue",
"=",
"f",
"(",
"value",
")",
";",
"if",
"(",
"_newValue",
"===",
"value",
")",
"return",
"list",
";",
"if",
"(",
"_newValue",
"===",
"nothing",
")",
"{",
"--",
"size",
".",
"value",
";",
"return",
"arraySpliceOut",
"(",
"mutate",
",",
"i",
",",
"list",
")",
";",
"}",
"return",
"arrayUpdate",
"(",
"mutate",
",",
"i",
",",
"Leaf",
"(",
"edit",
",",
"h",
",",
"k",
",",
"_newValue",
")",
",",
"list",
")",
";",
"}",
"}",
"var",
"newValue",
"=",
"f",
"(",
")",
";",
"if",
"(",
"newValue",
"===",
"nothing",
")",
"return",
"list",
";",
"++",
"size",
".",
"value",
";",
"return",
"arrayUpdate",
"(",
"mutate",
",",
"len",
",",
"Leaf",
"(",
"edit",
",",
"h",
",",
"k",
",",
"newValue",
")",
",",
"list",
")",
";",
"}"
] | Update an entry in a collision list.
@param mutate Should mutation be used?
@param edit Current edit.
@param keyEq Key compare function.
@param hash Hash of collision.
@param list Collision list.
@param f Update function.
@param k Key to update.
@param size Size ref. | [
"Update",
"an",
"entry",
"in",
"a",
"collision",
"list",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L334-L355 | train |
mattbierner/hamt_plus | hamt.js | lazyVisitChildren | function lazyVisitChildren(len, children, i, f, k) {
while (i < len) {
var child = children[i++];
if (child && !isEmptyNode(child)) return lazyVisit(child, f, [len, children, i, f, k]);
}
return appk(k);
} | javascript | function lazyVisitChildren(len, children, i, f, k) {
while (i < len) {
var child = children[i++];
if (child && !isEmptyNode(child)) return lazyVisit(child, f, [len, children, i, f, k]);
}
return appk(k);
} | [
"function",
"lazyVisitChildren",
"(",
"len",
",",
"children",
",",
"i",
",",
"f",
",",
"k",
")",
"{",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"var",
"child",
"=",
"children",
"[",
"i",
"++",
"]",
";",
"if",
"(",
"child",
"&&",
"!",
"isEmptyNode",
"(",
"child",
")",
")",
"return",
"lazyVisit",
"(",
"child",
",",
"f",
",",
"[",
"len",
",",
"children",
",",
"i",
",",
"f",
",",
"k",
"]",
")",
";",
"}",
"return",
"appk",
"(",
"k",
")",
";",
"}"
] | Recursively visit all values stored in an array of nodes lazily. | [
"Recursively",
"visit",
"all",
"values",
"stored",
"in",
"an",
"array",
"of",
"nodes",
"lazily",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L788-L794 | train |
mattbierner/hamt_plus | hamt.js | lazyVisit | function lazyVisit(node, f, k) {
switch (node.type) {
case LEAF:
return {
value: f(node),
rest: k
};
case COLLISION:
case ARRAY:
case INDEX:
var children = node.children;
return lazyVisitChildren(children.length, children, 0, f, k);
default:
return appk(k);
}
} | javascript | function lazyVisit(node, f, k) {
switch (node.type) {
case LEAF:
return {
value: f(node),
rest: k
};
case COLLISION:
case ARRAY:
case INDEX:
var children = node.children;
return lazyVisitChildren(children.length, children, 0, f, k);
default:
return appk(k);
}
} | [
"function",
"lazyVisit",
"(",
"node",
",",
"f",
",",
"k",
")",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"LEAF",
":",
"return",
"{",
"value",
":",
"f",
"(",
"node",
")",
",",
"rest",
":",
"k",
"}",
";",
"case",
"COLLISION",
":",
"case",
"ARRAY",
":",
"case",
"INDEX",
":",
"var",
"children",
"=",
"node",
".",
"children",
";",
"return",
"lazyVisitChildren",
"(",
"children",
".",
"length",
",",
"children",
",",
"0",
",",
"f",
",",
"k",
")",
";",
"default",
":",
"return",
"appk",
"(",
"k",
")",
";",
"}",
"}"
] | Recursively visit all values stored in `node` lazily. | [
"Recursively",
"visit",
"all",
"values",
"stored",
"in",
"node",
"lazily",
"."
] | b8845c7343fdde3966f875d732248fec597cf538 | https://github.com/mattbierner/hamt_plus/blob/b8845c7343fdde3966f875d732248fec597cf538/hamt.js#L799-L816 | train |
keymetrics/trassingue | src/util.js | truncate | function truncate(string, length) {
if (Buffer.byteLength(string, 'utf8') <= length) {
return string;
}
string = string.substr(0, length - 3);
while (Buffer.byteLength(string, 'utf8') > length - 3) {
string = string.substr(0, string.length - 1);
}
return string + '...';
} | javascript | function truncate(string, length) {
if (Buffer.byteLength(string, 'utf8') <= length) {
return string;
}
string = string.substr(0, length - 3);
while (Buffer.byteLength(string, 'utf8') > length - 3) {
string = string.substr(0, string.length - 1);
}
return string + '...';
} | [
"function",
"truncate",
"(",
"string",
",",
"length",
")",
"{",
"if",
"(",
"Buffer",
".",
"byteLength",
"(",
"string",
",",
"'utf8'",
")",
"<=",
"length",
")",
"{",
"return",
"string",
";",
"}",
"string",
"=",
"string",
".",
"substr",
"(",
"0",
",",
"length",
"-",
"3",
")",
";",
"while",
"(",
"Buffer",
".",
"byteLength",
"(",
"string",
",",
"'utf8'",
")",
">",
"length",
"-",
"3",
")",
"{",
"string",
"=",
"string",
".",
"substr",
"(",
"0",
",",
"string",
".",
"length",
"-",
"1",
")",
";",
"}",
"return",
"string",
"+",
"'...'",
";",
"}"
] | Truncates the provided `string` to be at most `length` bytes
after utf8 encoding and the appending of '...'.
We produce the result by iterating over input characters to
avoid truncating the string potentially producing partial unicode
characters at the end. | [
"Truncates",
"the",
"provided",
"string",
"to",
"be",
"at",
"most",
"length",
"bytes",
"after",
"utf8",
"encoding",
"and",
"the",
"appending",
"of",
"...",
".",
"We",
"produce",
"the",
"result",
"by",
"iterating",
"over",
"input",
"characters",
"to",
"avoid",
"truncating",
"the",
"string",
"potentially",
"producing",
"partial",
"unicode",
"characters",
"at",
"the",
"end",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/util.js#L30-L39 | train |
keymetrics/trassingue | src/util.js | findModulePath | function findModulePath(request, parent) {
var mainScriptDir = path.dirname(Module._resolveFilename(request, parent));
var resolvedModule = Module._resolveLookupPaths(request, parent);
var paths = resolvedModule[1];
for (var i = 0, PL = paths.length; i < PL; i++) {
if (mainScriptDir.indexOf(paths[i]) === 0) {
return path.join(paths[i], request.replace('/', path.sep));
}
}
return null;
} | javascript | function findModulePath(request, parent) {
var mainScriptDir = path.dirname(Module._resolveFilename(request, parent));
var resolvedModule = Module._resolveLookupPaths(request, parent);
var paths = resolvedModule[1];
for (var i = 0, PL = paths.length; i < PL; i++) {
if (mainScriptDir.indexOf(paths[i]) === 0) {
return path.join(paths[i], request.replace('/', path.sep));
}
}
return null;
} | [
"function",
"findModulePath",
"(",
"request",
",",
"parent",
")",
"{",
"var",
"mainScriptDir",
"=",
"path",
".",
"dirname",
"(",
"Module",
".",
"_resolveFilename",
"(",
"request",
",",
"parent",
")",
")",
";",
"var",
"resolvedModule",
"=",
"Module",
".",
"_resolveLookupPaths",
"(",
"request",
",",
"parent",
")",
";",
"var",
"paths",
"=",
"resolvedModule",
"[",
"1",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"PL",
"=",
"paths",
".",
"length",
";",
"i",
"<",
"PL",
";",
"i",
"++",
")",
"{",
"if",
"(",
"mainScriptDir",
".",
"indexOf",
"(",
"paths",
"[",
"i",
"]",
")",
"===",
"0",
")",
"{",
"return",
"path",
".",
"join",
"(",
"paths",
"[",
"i",
"]",
",",
"request",
".",
"replace",
"(",
"'/'",
",",
"path",
".",
"sep",
")",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Determines the path at which the requested module will be loaded given
the provided parent module.
@param {string} request The name of the module to be loaded.
@param {object} parent The module into which the requested module will be loaded. | [
"Determines",
"the",
"path",
"at",
"which",
"the",
"requested",
"module",
"will",
"be",
"loaded",
"given",
"the",
"provided",
"parent",
"module",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/util.js#L99-L109 | train |
keymetrics/trassingue | src/util.js | findModuleVersion | function findModuleVersion(modulePath, load) {
if (modulePath) {
var pjson = path.join(modulePath, 'package.json');
if (fs.existsSync(pjson)) {
return load(pjson).version;
}
}
return process.version;
} | javascript | function findModuleVersion(modulePath, load) {
if (modulePath) {
var pjson = path.join(modulePath, 'package.json');
if (fs.existsSync(pjson)) {
return load(pjson).version;
}
}
return process.version;
} | [
"function",
"findModuleVersion",
"(",
"modulePath",
",",
"load",
")",
"{",
"if",
"(",
"modulePath",
")",
"{",
"var",
"pjson",
"=",
"path",
".",
"join",
"(",
"modulePath",
",",
"'package.json'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"pjson",
")",
")",
"{",
"return",
"load",
"(",
"pjson",
")",
".",
"version",
";",
"}",
"}",
"return",
"process",
".",
"version",
";",
"}"
] | Determines the version of the module located at `modulePath`.
@param {?string} modulePath The absolute path to the root directory of the
module being loaded. This may be null if we are loading an internal module
such as http. | [
"Determines",
"the",
"version",
"of",
"the",
"module",
"located",
"at",
"modulePath",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/util.js#L118-L126 | train |
oskosk/node-wms-client | index.js | function( queryOptions, callback ) {
var _this = this;
if ( typeof queryOptions === 'function' ) {
callback = queryOptions;
this.capabilities( function( err, capabilities ) {
if ( err ) {
debug( "Error getting layers for server '%s': %j", _this.baseUrl,
err.stack );
return callback( err );
}
try {
callback( null, capabilities.capability.layer.layer );
} catch ( e ) {
callback( e );
}
} );
} else if ( typeof callback === 'function' ) {
this.capabilities( queryOptions, function( err, capabilities ) {
if ( err ) {
debug( "Error getting layers for server '%s': %j", _this.baseUrl,
err.stack );
return callback( err );
}
callback( null, capabilities.capability.layer.layer );
} );
}
} | javascript | function( queryOptions, callback ) {
var _this = this;
if ( typeof queryOptions === 'function' ) {
callback = queryOptions;
this.capabilities( function( err, capabilities ) {
if ( err ) {
debug( "Error getting layers for server '%s': %j", _this.baseUrl,
err.stack );
return callback( err );
}
try {
callback( null, capabilities.capability.layer.layer );
} catch ( e ) {
callback( e );
}
} );
} else if ( typeof callback === 'function' ) {
this.capabilities( queryOptions, function( err, capabilities ) {
if ( err ) {
debug( "Error getting layers for server '%s': %j", _this.baseUrl,
err.stack );
return callback( err );
}
callback( null, capabilities.capability.layer.layer );
} );
}
} | [
"function",
"(",
"queryOptions",
",",
"callback",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"if",
"(",
"typeof",
"queryOptions",
"===",
"'function'",
")",
"{",
"callback",
"=",
"queryOptions",
";",
"this",
".",
"capabilities",
"(",
"function",
"(",
"err",
",",
"capabilities",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"\"Error getting layers for server '%s': %j\"",
",",
"_this",
".",
"baseUrl",
",",
"err",
".",
"stack",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"try",
"{",
"callback",
"(",
"null",
",",
"capabilities",
".",
"capability",
".",
"layer",
".",
"layer",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"this",
".",
"capabilities",
"(",
"queryOptions",
",",
"function",
"(",
"err",
",",
"capabilities",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"\"Error getting layers for server '%s': %j\"",
",",
"_this",
".",
"baseUrl",
",",
"err",
".",
"stack",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"callback",
"(",
"null",
",",
"capabilities",
".",
"capability",
".",
"layer",
".",
"layer",
")",
";",
"}",
")",
";",
"}",
"}"
] | Gets the WMS service layers reported in the capabilities as an array
@param {Object} [Optional] queryOptions. Options passed as GET parameters
@param {Function} callback.
- {Error} null if nothing bad happened
- {Array} WMS layers as an array Plain Objects | [
"Gets",
"the",
"WMS",
"service",
"layers",
"reported",
"in",
"the",
"capabilities",
"as",
"an",
"array"
] | 86aaa8ed7eedbed7fb33c72a8607387a2b130933 | https://github.com/oskosk/node-wms-client/blob/86aaa8ed7eedbed7fb33c72a8607387a2b130933/index.js#L82-L108 | train |
|
oskosk/node-wms-client | index.js | function( queryOptions, callback ) {
var _this = this;
if ( typeof queryOptions === 'function' ) {
callback = queryOptions;
this.capabilities( function( err, capabilities ) {
if ( err ) {
debug( 'Error getting layers: %j', err );
return callback( err );
}
if ( _this.version === '1.3.0' ) {
callback( null, capabilities.capability.layer.crs );
} else {
callback( null, capabilities.capability.layer.srs );
}
} );
} else if ( typeof callback === 'function' ) {
this.capabilities( queryOptions, function( err, capabilities ) {
if ( err ) {
debug( 'Error getting layers: %j', err );
return callback( err );
}
if ( _this.version === '1.3.0' ) {
callback( null, capabilities.capability.layer.crs );
} else {
callback( null, capabilities.capability.layer.srs );
}
} );
}
} | javascript | function( queryOptions, callback ) {
var _this = this;
if ( typeof queryOptions === 'function' ) {
callback = queryOptions;
this.capabilities( function( err, capabilities ) {
if ( err ) {
debug( 'Error getting layers: %j', err );
return callback( err );
}
if ( _this.version === '1.3.0' ) {
callback( null, capabilities.capability.layer.crs );
} else {
callback( null, capabilities.capability.layer.srs );
}
} );
} else if ( typeof callback === 'function' ) {
this.capabilities( queryOptions, function( err, capabilities ) {
if ( err ) {
debug( 'Error getting layers: %j', err );
return callback( err );
}
if ( _this.version === '1.3.0' ) {
callback( null, capabilities.capability.layer.crs );
} else {
callback( null, capabilities.capability.layer.srs );
}
} );
}
} | [
"function",
"(",
"queryOptions",
",",
"callback",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"if",
"(",
"typeof",
"queryOptions",
"===",
"'function'",
")",
"{",
"callback",
"=",
"queryOptions",
";",
"this",
".",
"capabilities",
"(",
"function",
"(",
"err",
",",
"capabilities",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error getting layers: %j'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"_this",
".",
"version",
"===",
"'1.3.0'",
")",
"{",
"callback",
"(",
"null",
",",
"capabilities",
".",
"capability",
".",
"layer",
".",
"crs",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"capabilities",
".",
"capability",
".",
"layer",
".",
"srs",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"this",
".",
"capabilities",
"(",
"queryOptions",
",",
"function",
"(",
"err",
",",
"capabilities",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error getting layers: %j'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"_this",
".",
"version",
"===",
"'1.3.0'",
")",
"{",
"callback",
"(",
"null",
",",
"capabilities",
".",
"capability",
".",
"layer",
".",
"crs",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"capabilities",
".",
"capability",
".",
"layer",
".",
"srs",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Gets the WMS supported Coordinate reference systems reported in the capabilities as an array
@param {Object} [Optional] queryOptions. Options passed as GET parameters
@param {Function} callback.
- {Error} null if nothing bad happened
- {Array} CRSs as an array strings | [
"Gets",
"the",
"WMS",
"supported",
"Coordinate",
"reference",
"systems",
"reported",
"in",
"the",
"capabilities",
"as",
"an",
"array"
] | 86aaa8ed7eedbed7fb33c72a8607387a2b130933 | https://github.com/oskosk/node-wms-client/blob/86aaa8ed7eedbed7fb33c72a8607387a2b130933/index.js#L117-L145 | train |
|
oskosk/node-wms-client | index.js | function( queryOptions, callback ) {
if ( typeof queryOptions === 'function' ) {
callback = queryOptions;
queryOptions = {};
}
this.capabilities( queryOptions, function( err, capabilities ) {
if ( err ) {
debug( 'Error getting service metadata: %j', err );
return callback( err );
}
callback( null, capabilities.service );
} );
} | javascript | function( queryOptions, callback ) {
if ( typeof queryOptions === 'function' ) {
callback = queryOptions;
queryOptions = {};
}
this.capabilities( queryOptions, function( err, capabilities ) {
if ( err ) {
debug( 'Error getting service metadata: %j', err );
return callback( err );
}
callback( null, capabilities.service );
} );
} | [
"function",
"(",
"queryOptions",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"queryOptions",
"===",
"'function'",
")",
"{",
"callback",
"=",
"queryOptions",
";",
"queryOptions",
"=",
"{",
"}",
";",
"}",
"this",
".",
"capabilities",
"(",
"queryOptions",
",",
"function",
"(",
"err",
",",
"capabilities",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error getting service metadata: %j'",
",",
"err",
")",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"callback",
"(",
"null",
",",
"capabilities",
".",
"service",
")",
";",
"}",
")",
";",
"}"
] | Gets the WMS service metadata reported in the capabilities as a plain object
@param {Object} [Optional] queryOptions. Options passed as GET parameters
@param {Function} callback.
- {Error} null if nothing bad happened
- {Array} WMS Service metadata as a Plain Object | [
"Gets",
"the",
"WMS",
"service",
"metadata",
"reported",
"in",
"the",
"capabilities",
"as",
"a",
"plain",
"object"
] | 86aaa8ed7eedbed7fb33c72a8607387a2b130933 | https://github.com/oskosk/node-wms-client/blob/86aaa8ed7eedbed7fb33c72a8607387a2b130933/index.js#L154-L166 | train |
|
oskosk/node-wms-client | index.js | function( wmsBaseUrl, queryOptions ) {
queryOptions = extend( {
request: 'GetCapabilities',
version: this.version,
service: 'WMS'
}, queryOptions );
// Append user provided GET parameters in the URL to required queryOptions
var urlQueryParams = new urijs( wmsBaseUrl ).search( true );
queryOptions = extend( queryOptions, urlQueryParams );
// Merge queryOptions GET parameters to the URL
var url = new urijs( wmsBaseUrl ).search( queryOptions );
debug( 'Using capabilities URL: %s', url );
return url.toString();
} | javascript | function( wmsBaseUrl, queryOptions ) {
queryOptions = extend( {
request: 'GetCapabilities',
version: this.version,
service: 'WMS'
}, queryOptions );
// Append user provided GET parameters in the URL to required queryOptions
var urlQueryParams = new urijs( wmsBaseUrl ).search( true );
queryOptions = extend( queryOptions, urlQueryParams );
// Merge queryOptions GET parameters to the URL
var url = new urijs( wmsBaseUrl ).search( queryOptions );
debug( 'Using capabilities URL: %s', url );
return url.toString();
} | [
"function",
"(",
"wmsBaseUrl",
",",
"queryOptions",
")",
"{",
"queryOptions",
"=",
"extend",
"(",
"{",
"request",
":",
"'GetCapabilities'",
",",
"version",
":",
"this",
".",
"version",
",",
"service",
":",
"'WMS'",
"}",
",",
"queryOptions",
")",
";",
"var",
"urlQueryParams",
"=",
"new",
"urijs",
"(",
"wmsBaseUrl",
")",
".",
"search",
"(",
"true",
")",
";",
"queryOptions",
"=",
"extend",
"(",
"queryOptions",
",",
"urlQueryParams",
")",
";",
"var",
"url",
"=",
"new",
"urijs",
"(",
"wmsBaseUrl",
")",
".",
"search",
"(",
"queryOptions",
")",
";",
"debug",
"(",
"'Using capabilities URL: %s'",
",",
"url",
")",
";",
"return",
"url",
".",
"toString",
"(",
")",
";",
"}"
] | Formats an URL to include specific GET parameters
required for a GETCAPABILITIES WMS method request | [
"Formats",
"an",
"URL",
"to",
"include",
"specific",
"GET",
"parameters",
"required",
"for",
"a",
"GETCAPABILITIES",
"WMS",
"method",
"request"
] | 86aaa8ed7eedbed7fb33c72a8607387a2b130933 | https://github.com/oskosk/node-wms-client/blob/86aaa8ed7eedbed7fb33c72a8607387a2b130933/index.js#L318-L331 | train |
|
oskosk/node-wms-client | index.js | function( minx, miny, maxx, maxy ) {
var bbox = '';
if ( this.version === '1.3.0' ) {
bbox = [minx, miny, maxx, maxy].join( ',' );
} else {
bbox = [miny, minx, maxy, maxx].join( ',' );
}
return bbox;
} | javascript | function( minx, miny, maxx, maxy ) {
var bbox = '';
if ( this.version === '1.3.0' ) {
bbox = [minx, miny, maxx, maxy].join( ',' );
} else {
bbox = [miny, minx, maxy, maxx].join( ',' );
}
return bbox;
} | [
"function",
"(",
"minx",
",",
"miny",
",",
"maxx",
",",
"maxy",
")",
"{",
"var",
"bbox",
"=",
"''",
";",
"if",
"(",
"this",
".",
"version",
"===",
"'1.3.0'",
")",
"{",
"bbox",
"=",
"[",
"minx",
",",
"miny",
",",
"maxx",
",",
"maxy",
"]",
".",
"join",
"(",
"','",
")",
";",
"}",
"else",
"{",
"bbox",
"=",
"[",
"miny",
",",
"minx",
",",
"maxy",
",",
"maxx",
"]",
".",
"join",
"(",
"','",
")",
";",
"}",
"return",
"bbox",
";",
"}"
] | Returns a bbox WMS string.
@param {Float} minx left bound of the bounding box in CRS units
@param {Float} miny lower bound of the bounding box in CRUS units
@param {Float} maxx right bound of the bounding box in CRUS units
@param {Float} maxy upper bound of the bounding box in CRUS units | [
"Returns",
"a",
"bbox",
"WMS",
"string",
"."
] | 86aaa8ed7eedbed7fb33c72a8607387a2b130933 | https://github.com/oskosk/node-wms-client/blob/86aaa8ed7eedbed7fb33c72a8607387a2b130933/index.js#L371-L379 | train |
|
rricard/koa-swagger | lib/checkers.js | checkParameter | function checkParameter(validator, def, context) {
var value = match.fromContext(def.name, def.in, context);
// Check requirement
if(def.required && !value) {
throw new ValidationError(def.name + " is required");
} else if(!value) {
return def.default;
}
// Select the right schema according to the spec
var schema;
if(def.in === "body") {
schema = def.schema;
// TODO: clean and sanitize recursively
} else {
// TODO: coerce other types
if(def.type === "integer") {
value = parseInt(value);
} else if(def.type === "number") {
value = parseFloat(value);
} else if(def.type === "file") {
def.type = "object";
}
if (def.in === "query" && def.type === "array") {
if(!def.collectionFormat || def.collectionFormat === "csv") {
value = value.split(",");
} else if (def.collectionFormat === "tsv") {
value = value.split("\t");
} else if (def.collectionFormat === "ssv") {
value = value.split(" ");
} else if (def.collectionFormat === "psv") {
value = value.split("|");
} else if (def.collectionFormat === "multi") {
throw new ValidationError("multi collectionFormat query parameters currently unsupported");
} else {
throw new ValidationError("unknown collectionFormat " + def.collectionFormat);
}
}
schema = def;
}
var err = validator(value, schema);
if(err.length > 0) {
throw new ValidationError(def.name + " has an invalid format: " +
JSON.stringify(err));
}
return value;
} | javascript | function checkParameter(validator, def, context) {
var value = match.fromContext(def.name, def.in, context);
// Check requirement
if(def.required && !value) {
throw new ValidationError(def.name + " is required");
} else if(!value) {
return def.default;
}
// Select the right schema according to the spec
var schema;
if(def.in === "body") {
schema = def.schema;
// TODO: clean and sanitize recursively
} else {
// TODO: coerce other types
if(def.type === "integer") {
value = parseInt(value);
} else if(def.type === "number") {
value = parseFloat(value);
} else if(def.type === "file") {
def.type = "object";
}
if (def.in === "query" && def.type === "array") {
if(!def.collectionFormat || def.collectionFormat === "csv") {
value = value.split(",");
} else if (def.collectionFormat === "tsv") {
value = value.split("\t");
} else if (def.collectionFormat === "ssv") {
value = value.split(" ");
} else if (def.collectionFormat === "psv") {
value = value.split("|");
} else if (def.collectionFormat === "multi") {
throw new ValidationError("multi collectionFormat query parameters currently unsupported");
} else {
throw new ValidationError("unknown collectionFormat " + def.collectionFormat);
}
}
schema = def;
}
var err = validator(value, schema);
if(err.length > 0) {
throw new ValidationError(def.name + " has an invalid format: " +
JSON.stringify(err));
}
return value;
} | [
"function",
"checkParameter",
"(",
"validator",
",",
"def",
",",
"context",
")",
"{",
"var",
"value",
"=",
"match",
".",
"fromContext",
"(",
"def",
".",
"name",
",",
"def",
".",
"in",
",",
"context",
")",
";",
"if",
"(",
"def",
".",
"required",
"&&",
"!",
"value",
")",
"{",
"throw",
"new",
"ValidationError",
"(",
"def",
".",
"name",
"+",
"\" is required\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"value",
")",
"{",
"return",
"def",
".",
"default",
";",
"}",
"var",
"schema",
";",
"if",
"(",
"def",
".",
"in",
"===",
"\"body\"",
")",
"{",
"schema",
"=",
"def",
".",
"schema",
";",
"}",
"else",
"{",
"if",
"(",
"def",
".",
"type",
"===",
"\"integer\"",
")",
"{",
"value",
"=",
"parseInt",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"def",
".",
"type",
"===",
"\"number\"",
")",
"{",
"value",
"=",
"parseFloat",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"def",
".",
"type",
"===",
"\"file\"",
")",
"{",
"def",
".",
"type",
"=",
"\"object\"",
";",
"}",
"if",
"(",
"def",
".",
"in",
"===",
"\"query\"",
"&&",
"def",
".",
"type",
"===",
"\"array\"",
")",
"{",
"if",
"(",
"!",
"def",
".",
"collectionFormat",
"||",
"def",
".",
"collectionFormat",
"===",
"\"csv\"",
")",
"{",
"value",
"=",
"value",
".",
"split",
"(",
"\",\"",
")",
";",
"}",
"else",
"if",
"(",
"def",
".",
"collectionFormat",
"===",
"\"tsv\"",
")",
"{",
"value",
"=",
"value",
".",
"split",
"(",
"\"\\t\"",
")",
";",
"}",
"else",
"\\t",
"}",
"if",
"(",
"def",
".",
"collectionFormat",
"===",
"\"ssv\"",
")",
"{",
"value",
"=",
"value",
".",
"split",
"(",
"\" \"",
")",
";",
"}",
"else",
"if",
"(",
"def",
".",
"collectionFormat",
"===",
"\"psv\"",
")",
"{",
"value",
"=",
"value",
".",
"split",
"(",
"\"|\"",
")",
";",
"}",
"else",
"if",
"(",
"def",
".",
"collectionFormat",
"===",
"\"multi\"",
")",
"{",
"throw",
"new",
"ValidationError",
"(",
"\"multi collectionFormat query parameters currently unsupported\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ValidationError",
"(",
"\"unknown collectionFormat \"",
"+",
"def",
".",
"collectionFormat",
")",
";",
"}",
"}",
"schema",
"=",
"def",
";",
"var",
"err",
"=",
"validator",
"(",
"value",
",",
"schema",
")",
";",
"if",
"(",
"err",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"ValidationError",
"(",
"def",
".",
"name",
"+",
"\" has an invalid format: \"",
"+",
"JSON",
".",
"stringify",
"(",
"err",
")",
")",
";",
"}",
"}"
] | Check if the context carries the parameter correctly
@param validator {function(object, Schema)} JSON-Schema validator function
@param def {Parameter} The parameter's definition
@param context {Context} A koa context
@return {*} The cleaned value
@throws {ValidationError} A possible validation error | [
"Check",
"if",
"the",
"context",
"carries",
"the",
"parameter",
"correctly"
] | 1c2d6cef6fa594a4b5a7697192b28df512c0ed73 | https://github.com/rricard/koa-swagger/blob/1c2d6cef6fa594a4b5a7697192b28df512c0ed73/lib/checkers.js#L41-L91 | train |
cb1kenobi/cli-kit | src/lib/errors.js | createError | function createError(code, type, desc) {
errors[code] = function (msg, meta) {
const err = new type(msg);
if (desc) {
if (!meta) {
meta = {};
}
meta.desc = desc;
}
return Object.defineProperties(err, {
code: {
configurable: true,
enumerable: true,
writable: true,
value: `ERR_${code}`
},
meta: {
configurable: true,
value: meta || undefined,
writable: true
}
});
};
Object.defineProperties(errors[code], {
name: {
configurable: true,
value: code,
writable: true
},
toString: {
configurable: true,
value: function toString() {
return `ERR_${code}`;
},
writable: true
}
});
} | javascript | function createError(code, type, desc) {
errors[code] = function (msg, meta) {
const err = new type(msg);
if (desc) {
if (!meta) {
meta = {};
}
meta.desc = desc;
}
return Object.defineProperties(err, {
code: {
configurable: true,
enumerable: true,
writable: true,
value: `ERR_${code}`
},
meta: {
configurable: true,
value: meta || undefined,
writable: true
}
});
};
Object.defineProperties(errors[code], {
name: {
configurable: true,
value: code,
writable: true
},
toString: {
configurable: true,
value: function toString() {
return `ERR_${code}`;
},
writable: true
}
});
} | [
"function",
"createError",
"(",
"code",
",",
"type",
",",
"desc",
")",
"{",
"errors",
"[",
"code",
"]",
"=",
"function",
"(",
"msg",
",",
"meta",
")",
"{",
"const",
"err",
"=",
"new",
"type",
"(",
"msg",
")",
";",
"if",
"(",
"desc",
")",
"{",
"if",
"(",
"!",
"meta",
")",
"{",
"meta",
"=",
"{",
"}",
";",
"}",
"meta",
".",
"desc",
"=",
"desc",
";",
"}",
"return",
"Object",
".",
"defineProperties",
"(",
"err",
",",
"{",
"code",
":",
"{",
"configurable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"writable",
":",
"true",
",",
"value",
":",
"`",
"${",
"code",
"}",
"`",
"}",
",",
"meta",
":",
"{",
"configurable",
":",
"true",
",",
"value",
":",
"meta",
"||",
"undefined",
",",
"writable",
":",
"true",
"}",
"}",
")",
";",
"}",
";",
"Object",
".",
"defineProperties",
"(",
"errors",
"[",
"code",
"]",
",",
"{",
"name",
":",
"{",
"configurable",
":",
"true",
",",
"value",
":",
"code",
",",
"writable",
":",
"true",
"}",
",",
"toString",
":",
"{",
"configurable",
":",
"true",
",",
"value",
":",
"function",
"toString",
"(",
")",
"{",
"return",
"`",
"${",
"code",
"}",
"`",
";",
"}",
",",
"writable",
":",
"true",
"}",
"}",
")",
";",
"}"
] | Creates an the error object and populates the message, code, and metadata.
@param {String} code - The error code.
@param {Error|RangeError|TypeError} type - An instantiable error object.
@param {String} desc - A generic error description. | [
"Creates",
"an",
"the",
"error",
"object",
"and",
"populates",
"the",
"message",
"code",
"and",
"metadata",
"."
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/src/lib/errors.js#L39-L79 | train |
cb1kenobi/cli-kit | site/semantic/tasks/config/project/config.js | function(config) {
config = config || extend(false, {}, defaults);
/*--------------
File Paths
---------------*/
var
configPath = this.getPath(),
sourcePaths = {},
outputPaths = {},
folder
;
// resolve paths (config location + base + path)
for(folder in config.paths.source) {
if(config.paths.source.hasOwnProperty(folder)) {
sourcePaths[folder] = path.resolve(path.join(configPath, config.base, config.paths.source[folder]));
}
}
for(folder in config.paths.output) {
if(config.paths.output.hasOwnProperty(folder)) {
outputPaths[folder] = path.resolve(path.join(configPath, config.base, config.paths.output[folder]));
}
}
// set config paths to full paths
config.paths.source = sourcePaths;
config.paths.output = outputPaths;
// resolve "clean" command path
config.paths.clean = path.resolve( path.join(configPath, config.base, config.paths.clean) );
/*--------------
CSS URLs
---------------*/
// determine asset paths in css by finding relative path between themes and output
// force forward slashes
config.paths.assets = {
source : '../../themes', // source asset path is always the same
uncompressed : './' + path.relative(config.paths.output.uncompressed, config.paths.output.themes).replace(/\\/g, '/'),
compressed : './' + path.relative(config.paths.output.compressed, config.paths.output.themes).replace(/\\/g, '/'),
packaged : './' + path.relative(config.paths.output.packaged, config.paths.output.themes).replace(/\\/g, '/')
};
/*--------------
Permission
---------------*/
if(config.permission) {
config.hasPermissions = true;
}
else {
// pass blank object to avoid causing errors
config.permission = {};
config.hasPermissions = false;
}
/*--------------
Globs
---------------*/
if(!config.globs) {
config.globs = {};
}
// remove duplicates from component array
if(config.components instanceof Array) {
config.components = config.components.filter(function(component, index) {
return config.components.indexOf(component) == index;
});
}
// takes component object and creates file glob matching selected components
config.globs.components = (typeof config.components == 'object')
? (config.components.length > 1)
? '{' + config.components.join(',') + '}'
: config.components[0]
: '{' + defaults.components.join(',') + '}'
;
return config;
} | javascript | function(config) {
config = config || extend(false, {}, defaults);
/*--------------
File Paths
---------------*/
var
configPath = this.getPath(),
sourcePaths = {},
outputPaths = {},
folder
;
// resolve paths (config location + base + path)
for(folder in config.paths.source) {
if(config.paths.source.hasOwnProperty(folder)) {
sourcePaths[folder] = path.resolve(path.join(configPath, config.base, config.paths.source[folder]));
}
}
for(folder in config.paths.output) {
if(config.paths.output.hasOwnProperty(folder)) {
outputPaths[folder] = path.resolve(path.join(configPath, config.base, config.paths.output[folder]));
}
}
// set config paths to full paths
config.paths.source = sourcePaths;
config.paths.output = outputPaths;
// resolve "clean" command path
config.paths.clean = path.resolve( path.join(configPath, config.base, config.paths.clean) );
/*--------------
CSS URLs
---------------*/
// determine asset paths in css by finding relative path between themes and output
// force forward slashes
config.paths.assets = {
source : '../../themes', // source asset path is always the same
uncompressed : './' + path.relative(config.paths.output.uncompressed, config.paths.output.themes).replace(/\\/g, '/'),
compressed : './' + path.relative(config.paths.output.compressed, config.paths.output.themes).replace(/\\/g, '/'),
packaged : './' + path.relative(config.paths.output.packaged, config.paths.output.themes).replace(/\\/g, '/')
};
/*--------------
Permission
---------------*/
if(config.permission) {
config.hasPermissions = true;
}
else {
// pass blank object to avoid causing errors
config.permission = {};
config.hasPermissions = false;
}
/*--------------
Globs
---------------*/
if(!config.globs) {
config.globs = {};
}
// remove duplicates from component array
if(config.components instanceof Array) {
config.components = config.components.filter(function(component, index) {
return config.components.indexOf(component) == index;
});
}
// takes component object and creates file glob matching selected components
config.globs.components = (typeof config.components == 'object')
? (config.components.length > 1)
? '{' + config.components.join(',') + '}'
: config.components[0]
: '{' + defaults.components.join(',') + '}'
;
return config;
} | [
"function",
"(",
"config",
")",
"{",
"config",
"=",
"config",
"||",
"extend",
"(",
"false",
",",
"{",
"}",
",",
"defaults",
")",
";",
"var",
"configPath",
"=",
"this",
".",
"getPath",
"(",
")",
",",
"sourcePaths",
"=",
"{",
"}",
",",
"outputPaths",
"=",
"{",
"}",
",",
"folder",
";",
"for",
"(",
"folder",
"in",
"config",
".",
"paths",
".",
"source",
")",
"{",
"if",
"(",
"config",
".",
"paths",
".",
"source",
".",
"hasOwnProperty",
"(",
"folder",
")",
")",
"{",
"sourcePaths",
"[",
"folder",
"]",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"join",
"(",
"configPath",
",",
"config",
".",
"base",
",",
"config",
".",
"paths",
".",
"source",
"[",
"folder",
"]",
")",
")",
";",
"}",
"}",
"for",
"(",
"folder",
"in",
"config",
".",
"paths",
".",
"output",
")",
"{",
"if",
"(",
"config",
".",
"paths",
".",
"output",
".",
"hasOwnProperty",
"(",
"folder",
")",
")",
"{",
"outputPaths",
"[",
"folder",
"]",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"join",
"(",
"configPath",
",",
"config",
".",
"base",
",",
"config",
".",
"paths",
".",
"output",
"[",
"folder",
"]",
")",
")",
";",
"}",
"}",
"config",
".",
"paths",
".",
"source",
"=",
"sourcePaths",
";",
"config",
".",
"paths",
".",
"output",
"=",
"outputPaths",
";",
"config",
".",
"paths",
".",
"clean",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"join",
"(",
"configPath",
",",
"config",
".",
"base",
",",
"config",
".",
"paths",
".",
"clean",
")",
")",
";",
"config",
".",
"paths",
".",
"assets",
"=",
"{",
"source",
":",
"'../../themes'",
",",
"uncompressed",
":",
"'./'",
"+",
"path",
".",
"relative",
"(",
"config",
".",
"paths",
".",
"output",
".",
"uncompressed",
",",
"config",
".",
"paths",
".",
"output",
".",
"themes",
")",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
",",
"compressed",
":",
"'./'",
"+",
"path",
".",
"relative",
"(",
"config",
".",
"paths",
".",
"output",
".",
"compressed",
",",
"config",
".",
"paths",
".",
"output",
".",
"themes",
")",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
",",
"packaged",
":",
"'./'",
"+",
"path",
".",
"relative",
"(",
"config",
".",
"paths",
".",
"output",
".",
"packaged",
",",
"config",
".",
"paths",
".",
"output",
".",
"themes",
")",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
"}",
";",
"if",
"(",
"config",
".",
"permission",
")",
"{",
"config",
".",
"hasPermissions",
"=",
"true",
";",
"}",
"else",
"{",
"config",
".",
"permission",
"=",
"{",
"}",
";",
"config",
".",
"hasPermissions",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"config",
".",
"globs",
")",
"{",
"config",
".",
"globs",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"config",
".",
"components",
"instanceof",
"Array",
")",
"{",
"config",
".",
"components",
"=",
"config",
".",
"components",
".",
"filter",
"(",
"function",
"(",
"component",
",",
"index",
")",
"{",
"return",
"config",
".",
"components",
".",
"indexOf",
"(",
"component",
")",
"==",
"index",
";",
"}",
")",
";",
"}",
"config",
".",
"globs",
".",
"components",
"=",
"(",
"typeof",
"config",
".",
"components",
"==",
"'object'",
")",
"?",
"(",
"config",
".",
"components",
".",
"length",
">",
"1",
")",
"?",
"'{'",
"+",
"config",
".",
"components",
".",
"join",
"(",
"','",
")",
"+",
"'}'",
":",
"config",
".",
"components",
"[",
"0",
"]",
":",
"'{'",
"+",
"defaults",
".",
"components",
".",
"join",
"(",
"','",
")",
"+",
"'}'",
";",
"return",
"config",
";",
"}"
] | adds additional derived values to a config object | [
"adds",
"additional",
"derived",
"values",
"to",
"a",
"config",
"object"
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/site/semantic/tasks/config/project/config.js#L52-L138 | train |
|
jtrussell/svn-npm-crutch | lib/svn-npm-crutch.js | function(exists, cb) {
if(!exists) {
fs.mkdir(rootDir + '/node_modules', function(error) {
cb(error);
});
} else {
cb(null);
}
} | javascript | function(exists, cb) {
if(!exists) {
fs.mkdir(rootDir + '/node_modules', function(error) {
cb(error);
});
} else {
cb(null);
}
} | [
"function",
"(",
"exists",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"fs",
".",
"mkdir",
"(",
"rootDir",
"+",
"'/node_modules'",
",",
"function",
"(",
"error",
")",
"{",
"cb",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
")",
";",
"}",
"}"
] | Make the node_modules folder if we need to | [
"Make",
"the",
"node_modules",
"folder",
"if",
"we",
"need",
"to"
] | 162df18cbb1c20a75bd3d30e73beb4839f10154a | https://github.com/jtrussell/svn-npm-crutch/blob/162df18cbb1c20a75bd3d30e73beb4839f10154a/lib/svn-npm-crutch.js#L40-L48 | train |
|
keymetrics/trassingue | src/span-data.js | SpanData | function SpanData(agent, trace, name, parentSpanId, isRoot, skipFrames) {
var spanId = uid++;
this.agent = agent;
var spanName = traceUtil.truncate(name, constants.TRACE_SERVICE_SPAN_NAME_LIMIT);
this.span = new TraceSpan(spanName, spanId, parentSpanId);
this.trace = trace;
this.isRoot = isRoot;
trace.spans.push(this.span);
if (agent.config().stackTraceLimit > 0) {
// This is a mechanism to get the structured stack trace out of V8.
// prepareStackTrace is called th first time the Error#stack property is
// accessed. The original behavior is to format the stack as an exception
// throw, which is not what we like. We customize it.
//
// See: https://code.google.com/p/v8-wiki/wiki/JavaScriptStackTraceApi
//
var origLimit = Error.stackTraceLimit;
Error.stackTraceLimit = agent.config().stackTraceLimit + skipFrames;
var origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function(error, structured) {
return structured;
};
var e = {};
Error.captureStackTrace(e, SpanData);
var stackFrames = [];
e.stack.forEach(function(callSite, i) {
if (i < skipFrames) {
return;
}
var functionName = callSite.getFunctionName();
var methodName = callSite.getMethodName();
var name = (methodName && functionName) ?
functionName + ' [as ' + methodName + ']' :
functionName || methodName || '<anonymous function>';
stackFrames.push(new StackFrame(undefined, name,
callSite.getFileName(), callSite.getLineNumber(),
callSite.getColumnNumber()));
});
// Set the label on the trace span directly to bypass truncation to
// config.maxLabelValueSize.
this.span.setLabel(TraceLabels.STACK_TRACE_DETAILS_KEY,
traceUtil.truncate(JSON.stringify({stack_frame: stackFrames}),
constants.TRACE_SERVICE_LABEL_VALUE_LIMIT));
Error.stackTraceLimit = origLimit;
Error.prepareStackTrace = origPrepare;
}
} | javascript | function SpanData(agent, trace, name, parentSpanId, isRoot, skipFrames) {
var spanId = uid++;
this.agent = agent;
var spanName = traceUtil.truncate(name, constants.TRACE_SERVICE_SPAN_NAME_LIMIT);
this.span = new TraceSpan(spanName, spanId, parentSpanId);
this.trace = trace;
this.isRoot = isRoot;
trace.spans.push(this.span);
if (agent.config().stackTraceLimit > 0) {
// This is a mechanism to get the structured stack trace out of V8.
// prepareStackTrace is called th first time the Error#stack property is
// accessed. The original behavior is to format the stack as an exception
// throw, which is not what we like. We customize it.
//
// See: https://code.google.com/p/v8-wiki/wiki/JavaScriptStackTraceApi
//
var origLimit = Error.stackTraceLimit;
Error.stackTraceLimit = agent.config().stackTraceLimit + skipFrames;
var origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function(error, structured) {
return structured;
};
var e = {};
Error.captureStackTrace(e, SpanData);
var stackFrames = [];
e.stack.forEach(function(callSite, i) {
if (i < skipFrames) {
return;
}
var functionName = callSite.getFunctionName();
var methodName = callSite.getMethodName();
var name = (methodName && functionName) ?
functionName + ' [as ' + methodName + ']' :
functionName || methodName || '<anonymous function>';
stackFrames.push(new StackFrame(undefined, name,
callSite.getFileName(), callSite.getLineNumber(),
callSite.getColumnNumber()));
});
// Set the label on the trace span directly to bypass truncation to
// config.maxLabelValueSize.
this.span.setLabel(TraceLabels.STACK_TRACE_DETAILS_KEY,
traceUtil.truncate(JSON.stringify({stack_frame: stackFrames}),
constants.TRACE_SERVICE_LABEL_VALUE_LIMIT));
Error.stackTraceLimit = origLimit;
Error.prepareStackTrace = origPrepare;
}
} | [
"function",
"SpanData",
"(",
"agent",
",",
"trace",
",",
"name",
",",
"parentSpanId",
",",
"isRoot",
",",
"skipFrames",
")",
"{",
"var",
"spanId",
"=",
"uid",
"++",
";",
"this",
".",
"agent",
"=",
"agent",
";",
"var",
"spanName",
"=",
"traceUtil",
".",
"truncate",
"(",
"name",
",",
"constants",
".",
"TRACE_SERVICE_SPAN_NAME_LIMIT",
")",
";",
"this",
".",
"span",
"=",
"new",
"TraceSpan",
"(",
"spanName",
",",
"spanId",
",",
"parentSpanId",
")",
";",
"this",
".",
"trace",
"=",
"trace",
";",
"this",
".",
"isRoot",
"=",
"isRoot",
";",
"trace",
".",
"spans",
".",
"push",
"(",
"this",
".",
"span",
")",
";",
"if",
"(",
"agent",
".",
"config",
"(",
")",
".",
"stackTraceLimit",
">",
"0",
")",
"{",
"var",
"origLimit",
"=",
"Error",
".",
"stackTraceLimit",
";",
"Error",
".",
"stackTraceLimit",
"=",
"agent",
".",
"config",
"(",
")",
".",
"stackTraceLimit",
"+",
"skipFrames",
";",
"var",
"origPrepare",
"=",
"Error",
".",
"prepareStackTrace",
";",
"Error",
".",
"prepareStackTrace",
"=",
"function",
"(",
"error",
",",
"structured",
")",
"{",
"return",
"structured",
";",
"}",
";",
"var",
"e",
"=",
"{",
"}",
";",
"Error",
".",
"captureStackTrace",
"(",
"e",
",",
"SpanData",
")",
";",
"var",
"stackFrames",
"=",
"[",
"]",
";",
"e",
".",
"stack",
".",
"forEach",
"(",
"function",
"(",
"callSite",
",",
"i",
")",
"{",
"if",
"(",
"i",
"<",
"skipFrames",
")",
"{",
"return",
";",
"}",
"var",
"functionName",
"=",
"callSite",
".",
"getFunctionName",
"(",
")",
";",
"var",
"methodName",
"=",
"callSite",
".",
"getMethodName",
"(",
")",
";",
"var",
"name",
"=",
"(",
"methodName",
"&&",
"functionName",
")",
"?",
"functionName",
"+",
"' [as '",
"+",
"methodName",
"+",
"']'",
":",
"functionName",
"||",
"methodName",
"||",
"'<anonymous function>'",
";",
"stackFrames",
".",
"push",
"(",
"new",
"StackFrame",
"(",
"undefined",
",",
"name",
",",
"callSite",
".",
"getFileName",
"(",
")",
",",
"callSite",
".",
"getLineNumber",
"(",
")",
",",
"callSite",
".",
"getColumnNumber",
"(",
")",
")",
")",
";",
"}",
")",
";",
"this",
".",
"span",
".",
"setLabel",
"(",
"TraceLabels",
".",
"STACK_TRACE_DETAILS_KEY",
",",
"traceUtil",
".",
"truncate",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"stack_frame",
":",
"stackFrames",
"}",
")",
",",
"constants",
".",
"TRACE_SERVICE_LABEL_VALUE_LIMIT",
")",
")",
";",
"Error",
".",
"stackTraceLimit",
"=",
"origLimit",
";",
"Error",
".",
"prepareStackTrace",
"=",
"origPrepare",
";",
"}",
"}"
] | Creates a trace context object.
@param {Trace} trace The object holding the spans comprising this trace.
@param {string} name The name of the span.
@param {number} parentSpanId The id of the parent span, 0 for root spans.
@param {boolean} isRoot Whether this is a root span.
@param {number} skipFrames the number of frames to remove from the top of the stack.
@constructor | [
"Creates",
"a",
"trace",
"context",
"object",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/span-data.js#L38-L87 | train |
keymetrics/trassingue | src/plugins/plugin-mongodb-core.js | wrapCallback | function wrapCallback(api, span, done) {
var fn = function(err, res) {
if (api.enhancedDatabaseReportingEnabled()) {
if (err) {
// Errors may contain sensitive query parameters.
span.addLabel('mongoError', err);
}
if (res) {
var result = res.result ? res.result : res;
span.addLabel('result', result);
}
}
span.endSpan();
if (done) {
done(err, res);
}
};
return api.wrap(fn);
} | javascript | function wrapCallback(api, span, done) {
var fn = function(err, res) {
if (api.enhancedDatabaseReportingEnabled()) {
if (err) {
// Errors may contain sensitive query parameters.
span.addLabel('mongoError', err);
}
if (res) {
var result = res.result ? res.result : res;
span.addLabel('result', result);
}
}
span.endSpan();
if (done) {
done(err, res);
}
};
return api.wrap(fn);
} | [
"function",
"wrapCallback",
"(",
"api",
",",
"span",
",",
"done",
")",
"{",
"var",
"fn",
"=",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"api",
".",
"enhancedDatabaseReportingEnabled",
"(",
")",
")",
"{",
"if",
"(",
"err",
")",
"{",
"span",
".",
"addLabel",
"(",
"'mongoError'",
",",
"err",
")",
";",
"}",
"if",
"(",
"res",
")",
"{",
"var",
"result",
"=",
"res",
".",
"result",
"?",
"res",
".",
"result",
":",
"res",
";",
"span",
".",
"addLabel",
"(",
"'result'",
",",
"result",
")",
";",
"}",
"}",
"span",
".",
"endSpan",
"(",
")",
";",
"if",
"(",
"done",
")",
"{",
"done",
"(",
"err",
",",
"res",
")",
";",
"}",
"}",
";",
"return",
"api",
".",
"wrap",
"(",
"fn",
")",
";",
"}"
] | Wraps the provided callback so that the provided span will
be closed immediately after the callback is invoked.
@param {Span} span The span to be closed.
@param {Function} done The callback to be wrapped.
@return {Function} The wrapped function. | [
"Wraps",
"the",
"provided",
"callback",
"so",
"that",
"the",
"provided",
"span",
"will",
"be",
"closed",
"immediately",
"after",
"the",
"callback",
"is",
"invoked",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/plugins/plugin-mongodb-core.js#L68-L86 | train |
keymetrics/trassingue | src/trace-span.js | TraceSpan | function TraceSpan(name, spanId, parentSpanId) {
this.name = name;
this.parentSpanId = parentSpanId;
this.spanId = spanId;
this.kind = 'RPC_CLIENT';
this.labels = {};
this.startTime = (new Date()).toISOString();
this.endTime = '';
} | javascript | function TraceSpan(name, spanId, parentSpanId) {
this.name = name;
this.parentSpanId = parentSpanId;
this.spanId = spanId;
this.kind = 'RPC_CLIENT';
this.labels = {};
this.startTime = (new Date()).toISOString();
this.endTime = '';
} | [
"function",
"TraceSpan",
"(",
"name",
",",
"spanId",
",",
"parentSpanId",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"parentSpanId",
"=",
"parentSpanId",
";",
"this",
".",
"spanId",
"=",
"spanId",
";",
"this",
".",
"kind",
"=",
"'RPC_CLIENT'",
";",
"this",
".",
"labels",
"=",
"{",
"}",
";",
"this",
".",
"startTime",
"=",
"(",
"new",
"Date",
"(",
")",
")",
".",
"toISOString",
"(",
")",
";",
"this",
".",
"endTime",
"=",
"''",
";",
"}"
] | Creates a trace span object.
@constructor | [
"Creates",
"a",
"trace",
"span",
"object",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/trace-span.js#L23-L31 | train |
psiphi75/compass-hmc5883l | example.js | printHeadingCB | function printHeadingCB(err, heading) {
if (err) {
console.log(err);
return;
}
console.log(heading * 180 / Math.PI);
} | javascript | function printHeadingCB(err, heading) {
if (err) {
console.log(err);
return;
}
console.log(heading * 180 / Math.PI);
} | [
"function",
"printHeadingCB",
"(",
"err",
",",
"heading",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"return",
";",
"}",
"console",
".",
"log",
"(",
"heading",
"*",
"180",
"/",
"Math",
".",
"PI",
")",
";",
"}"
] | Gets called every time we get the values. | [
"Gets",
"called",
"every",
"time",
"we",
"get",
"the",
"values",
"."
] | 72b25ef2c2d2a8c0d67ab14befea93a346b9086f | https://github.com/psiphi75/compass-hmc5883l/blob/72b25ef2c2d2a8c0d67ab14befea93a346b9086f/example.js#L30-L36 | train |
keymetrics/trassingue | src/trace-api.js | ChildSpan | function ChildSpan(agent, span) {
this.agent_ = agent;
this.span_ = span;
this.serializedTraceContext_ = agent.generateTraceContext(span, true);
} | javascript | function ChildSpan(agent, span) {
this.agent_ = agent;
this.span_ = span;
this.serializedTraceContext_ = agent.generateTraceContext(span, true);
} | [
"function",
"ChildSpan",
"(",
"agent",
",",
"span",
")",
"{",
"this",
".",
"agent_",
"=",
"agent",
";",
"this",
".",
"span_",
"=",
"span",
";",
"this",
".",
"serializedTraceContext_",
"=",
"agent",
".",
"generateTraceContext",
"(",
"span",
",",
"true",
")",
";",
"}"
] | This file describes an interface for third-party plugins to enable tracing
for arbitrary modules.
An object that represents a single child span. It exposes functions for
adding labels to or closing the span.
@param {TraceAgent} agent The underlying trace agent object.
@param {SpanData} span The internal data structure backing the child span. | [
"This",
"file",
"describes",
"an",
"interface",
"for",
"third",
"-",
"party",
"plugins",
"to",
"enable",
"tracing",
"for",
"arbitrary",
"modules",
".",
"An",
"object",
"that",
"represents",
"a",
"single",
"child",
"span",
".",
"It",
"exposes",
"functions",
"for",
"adding",
"labels",
"to",
"or",
"closing",
"the",
"span",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/trace-api.js#L35-L39 | train |
keymetrics/trassingue | src/trace-api.js | RootSpan | function RootSpan(agent, span) {
this.agent_ = agent;
this.span_ = span;
this.serializedTraceContext_ = agent.generateTraceContext(span, true);
} | javascript | function RootSpan(agent, span) {
this.agent_ = agent;
this.span_ = span;
this.serializedTraceContext_ = agent.generateTraceContext(span, true);
} | [
"function",
"RootSpan",
"(",
"agent",
",",
"span",
")",
"{",
"this",
".",
"agent_",
"=",
"agent",
";",
"this",
".",
"span_",
"=",
"span",
";",
"this",
".",
"serializedTraceContext_",
"=",
"agent",
".",
"generateTraceContext",
"(",
"span",
",",
"true",
")",
";",
"}"
] | An object that represents a single root span. It exposes functions for adding
labels to or closing the span.
@param {TraceAgent} agent The underlying trace agent object.
@param {SpanData} span The internal data structure backing the root span. | [
"An",
"object",
"that",
"represents",
"a",
"single",
"root",
"span",
".",
"It",
"exposes",
"functions",
"for",
"adding",
"labels",
"to",
"or",
"closing",
"the",
"span",
"."
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/trace-api.js#L72-L76 | train |
keymetrics/trassingue | src/trace-api.js | TraceApiImplementation | function TraceApiImplementation(agent, pluginName) {
this.agent_ = agent;
this.logger_ = agent.logger;
this.pluginName_ = pluginName;
} | javascript | function TraceApiImplementation(agent, pluginName) {
this.agent_ = agent;
this.logger_ = agent.logger;
this.pluginName_ = pluginName;
} | [
"function",
"TraceApiImplementation",
"(",
"agent",
",",
"pluginName",
")",
"{",
"this",
".",
"agent_",
"=",
"agent",
";",
"this",
".",
"logger_",
"=",
"agent",
".",
"logger",
";",
"this",
".",
"pluginName_",
"=",
"pluginName",
";",
"}"
] | The functional implementation of the Trace API | [
"The",
"functional",
"implementation",
"of",
"the",
"Trace",
"API"
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/trace-api.js#L109-L113 | train |
keymetrics/trassingue | src/trace-api.js | createRootSpan_ | function createRootSpan_(api, options, skipFrames) {
options = options || {};
// If the options object passed in has the getTraceContext field set,
// try to retrieve the header field containing incoming trace metadata.
var incomingTraceContext;
if (is.string(options.traceContext)) {
incomingTraceContext = api.agent_.parseContextFromHeader(options.traceContext);
}
incomingTraceContext = incomingTraceContext || {};
if (!api.agent_.shouldTrace(options, incomingTraceContext.options)) {
cls.setRootContext(nullSpan);
return null;
}
var rootContext = api.agent_.createRootSpanData(options.name,
incomingTraceContext.traceId,
incomingTraceContext.spanId,
skipFrames + 1);
return new RootSpan(api.agent_, rootContext);
} | javascript | function createRootSpan_(api, options, skipFrames) {
options = options || {};
// If the options object passed in has the getTraceContext field set,
// try to retrieve the header field containing incoming trace metadata.
var incomingTraceContext;
if (is.string(options.traceContext)) {
incomingTraceContext = api.agent_.parseContextFromHeader(options.traceContext);
}
incomingTraceContext = incomingTraceContext || {};
if (!api.agent_.shouldTrace(options, incomingTraceContext.options)) {
cls.setRootContext(nullSpan);
return null;
}
var rootContext = api.agent_.createRootSpanData(options.name,
incomingTraceContext.traceId,
incomingTraceContext.spanId,
skipFrames + 1);
return new RootSpan(api.agent_, rootContext);
} | [
"function",
"createRootSpan_",
"(",
"api",
",",
"options",
",",
"skipFrames",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"incomingTraceContext",
";",
"if",
"(",
"is",
".",
"string",
"(",
"options",
".",
"traceContext",
")",
")",
"{",
"incomingTraceContext",
"=",
"api",
".",
"agent_",
".",
"parseContextFromHeader",
"(",
"options",
".",
"traceContext",
")",
";",
"}",
"incomingTraceContext",
"=",
"incomingTraceContext",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"api",
".",
"agent_",
".",
"shouldTrace",
"(",
"options",
",",
"incomingTraceContext",
".",
"options",
")",
")",
"{",
"cls",
".",
"setRootContext",
"(",
"nullSpan",
")",
";",
"return",
"null",
";",
"}",
"var",
"rootContext",
"=",
"api",
".",
"agent_",
".",
"createRootSpanData",
"(",
"options",
".",
"name",
",",
"incomingTraceContext",
".",
"traceId",
",",
"incomingTraceContext",
".",
"spanId",
",",
"skipFrames",
"+",
"1",
")",
";",
"return",
"new",
"RootSpan",
"(",
"api",
".",
"agent_",
",",
"rootContext",
")",
";",
"}"
] | Module-private functions | [
"Module",
"-",
"private",
"functions"
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/trace-api.js#L322-L340 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.