id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
46,400 | ericnishio/finnish-holidays-js | lib/date-utils.js | function(year) {
var self = this;
var month = 6;
var midsummerEve;
self.range(19, 26).forEach(function(day) {
if (!midsummerEve) {
var date = self.createDate(year, month, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.FRIDAY) {
midsummerEve = date;
}
}
});
return midsummerEve;
} | javascript | function(year) {
var self = this;
var month = 6;
var midsummerEve;
self.range(19, 26).forEach(function(day) {
if (!midsummerEve) {
var date = self.createDate(year, month, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.FRIDAY) {
midsummerEve = date;
}
}
});
return midsummerEve;
} | [
"function",
"(",
"year",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"month",
"=",
"6",
";",
"var",
"midsummerEve",
";",
"self",
".",
"range",
"(",
"19",
",",
"26",
")",
".",
"forEach",
"(",
"function",
"(",
"day",
")",
"{",
"if",
"(",
"!",
"midsummerEve",
")",
"{",
"var",
"date",
"=",
"self",
".",
"createDate",
"(",
"year",
",",
"month",
",",
"day",
")",
";",
"var",
"dayOfWeek",
"=",
"self",
".",
"getDayOfWeek",
"(",
"date",
")",
";",
"if",
"(",
"dayOfWeek",
"===",
"self",
".",
"FRIDAY",
")",
"{",
"midsummerEve",
"=",
"date",
";",
"}",
"}",
"}",
")",
";",
"return",
"midsummerEve",
";",
"}"
]
| Determines the date of Midsummer Eve.
Friday between June 19-25
@param {number} year
@return {Date} | [
"Determines",
"the",
"date",
"of",
"Midsummer",
"Eve",
".",
"Friday",
"between",
"June",
"19",
"-",
"25"
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L185-L202 |
|
46,401 | ericnishio/finnish-holidays-js | lib/date-utils.js | function(year) {
var self = this;
var month = 6;
var midsummerDay;
self.range(20, 26).forEach(function(day) {
if (!midsummerDay) {
var date = self.createDate(year, month, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.SATURDAY) {
midsummerDay = date;
}
}
});
return midsummerDay;
} | javascript | function(year) {
var self = this;
var month = 6;
var midsummerDay;
self.range(20, 26).forEach(function(day) {
if (!midsummerDay) {
var date = self.createDate(year, month, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.SATURDAY) {
midsummerDay = date;
}
}
});
return midsummerDay;
} | [
"function",
"(",
"year",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"month",
"=",
"6",
";",
"var",
"midsummerDay",
";",
"self",
".",
"range",
"(",
"20",
",",
"26",
")",
".",
"forEach",
"(",
"function",
"(",
"day",
")",
"{",
"if",
"(",
"!",
"midsummerDay",
")",
"{",
"var",
"date",
"=",
"self",
".",
"createDate",
"(",
"year",
",",
"month",
",",
"day",
")",
";",
"var",
"dayOfWeek",
"=",
"self",
".",
"getDayOfWeek",
"(",
"date",
")",
";",
"if",
"(",
"dayOfWeek",
"===",
"self",
".",
"SATURDAY",
")",
"{",
"midsummerDay",
"=",
"date",
";",
"}",
"}",
"}",
")",
";",
"return",
"midsummerDay",
";",
"}"
]
| Determines the date of Midsummer Day.
Saturday between June 20-26
@param {number} year
@return {Date} | [
"Determines",
"the",
"date",
"of",
"Midsummer",
"Day",
".",
"Saturday",
"between",
"June",
"20",
"-",
"26"
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L210-L227 |
|
46,402 | ericnishio/finnish-holidays-js | lib/date-utils.js | function(year) {
var self = this;
var october31 = self.createDate(year, 10, 31);
var secondMonth = 11;
var allSaintsDay;
if (self.getDayOfWeek(october31) === self.SATURDAY) {
allSaintsDay = october31;
} else {
self.range(1, 6).forEach(function(day) {
if (!allSaintsDay) {
var date = self.createDate(year, secondMonth, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.SATURDAY) {
allSaintsDay = date;
}
}
});
}
return allSaintsDay;
} | javascript | function(year) {
var self = this;
var october31 = self.createDate(year, 10, 31);
var secondMonth = 11;
var allSaintsDay;
if (self.getDayOfWeek(october31) === self.SATURDAY) {
allSaintsDay = october31;
} else {
self.range(1, 6).forEach(function(day) {
if (!allSaintsDay) {
var date = self.createDate(year, secondMonth, day);
var dayOfWeek = self.getDayOfWeek(date);
if (dayOfWeek === self.SATURDAY) {
allSaintsDay = date;
}
}
});
}
return allSaintsDay;
} | [
"function",
"(",
"year",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"october31",
"=",
"self",
".",
"createDate",
"(",
"year",
",",
"10",
",",
"31",
")",
";",
"var",
"secondMonth",
"=",
"11",
";",
"var",
"allSaintsDay",
";",
"if",
"(",
"self",
".",
"getDayOfWeek",
"(",
"october31",
")",
"===",
"self",
".",
"SATURDAY",
")",
"{",
"allSaintsDay",
"=",
"october31",
";",
"}",
"else",
"{",
"self",
".",
"range",
"(",
"1",
",",
"6",
")",
".",
"forEach",
"(",
"function",
"(",
"day",
")",
"{",
"if",
"(",
"!",
"allSaintsDay",
")",
"{",
"var",
"date",
"=",
"self",
".",
"createDate",
"(",
"year",
",",
"secondMonth",
",",
"day",
")",
";",
"var",
"dayOfWeek",
"=",
"self",
".",
"getDayOfWeek",
"(",
"date",
")",
";",
"if",
"(",
"dayOfWeek",
"===",
"self",
".",
"SATURDAY",
")",
"{",
"allSaintsDay",
"=",
"date",
";",
"}",
"}",
"}",
")",
";",
"}",
"return",
"allSaintsDay",
";",
"}"
]
| Determines the date of All Saints' Day.
Saturday between October 31 and November 6
@param {number} year
@return {Date} | [
"Determines",
"the",
"date",
"of",
"All",
"Saints",
"Day",
".",
"Saturday",
"between",
"October",
"31",
"and",
"November",
"6"
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L235-L257 |
|
46,403 | ericnishio/finnish-holidays-js | lib/date-utils.js | function(num) {
num = parseInt(num);
if (num < 10) {
num = '0' + num;
} else {
num = num.toString();
}
return num;
} | javascript | function(num) {
num = parseInt(num);
if (num < 10) {
num = '0' + num;
} else {
num = num.toString();
}
return num;
} | [
"function",
"(",
"num",
")",
"{",
"num",
"=",
"parseInt",
"(",
"num",
")",
";",
"if",
"(",
"num",
"<",
"10",
")",
"{",
"num",
"=",
"'0'",
"+",
"num",
";",
"}",
"else",
"{",
"num",
"=",
"num",
".",
"toString",
"(",
")",
";",
"}",
"return",
"num",
";",
"}"
]
| Adds a leading zero to a single-digit number.
@param {number} num
@return {string} | [
"Adds",
"a",
"leading",
"zero",
"to",
"a",
"single",
"-",
"digit",
"number",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L264-L274 |
|
46,404 | ericnishio/finnish-holidays-js | lib/date-utils.js | function(fromNumber, toNumber) {
if (typeof fromNumber === 'undefined' || typeof toNumber === 'undefined') {
throw Error('Invalid range.');
}
var arr = [];
for (var i = fromNumber; i <= toNumber; i++) {
arr.push(i);
}
return arr;
} | javascript | function(fromNumber, toNumber) {
if (typeof fromNumber === 'undefined' || typeof toNumber === 'undefined') {
throw Error('Invalid range.');
}
var arr = [];
for (var i = fromNumber; i <= toNumber; i++) {
arr.push(i);
}
return arr;
} | [
"function",
"(",
"fromNumber",
",",
"toNumber",
")",
"{",
"if",
"(",
"typeof",
"fromNumber",
"===",
"'undefined'",
"||",
"typeof",
"toNumber",
"===",
"'undefined'",
")",
"{",
"throw",
"Error",
"(",
"'Invalid range.'",
")",
";",
"}",
"var",
"arr",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"fromNumber",
";",
"i",
"<=",
"toNumber",
";",
"i",
"++",
")",
"{",
"arr",
".",
"push",
"(",
"i",
")",
";",
"}",
"return",
"arr",
";",
"}"
]
| Creates an array of a range of numbers.
@param {number} fromNumber
@param {number} toNumber
@return {Array} | [
"Creates",
"an",
"array",
"of",
"a",
"range",
"of",
"numbers",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L282-L294 |
|
46,405 | thehydroimpulse/rollout | index.js | Rollout | function Rollout(client) {
this.client = client || redis.createClient();
this._id = 'id';
this._namespace = null;
this._groups = {};
this.group('all', function(user) { return true; });
} | javascript | function Rollout(client) {
this.client = client || redis.createClient();
this._id = 'id';
this._namespace = null;
this._groups = {};
this.group('all', function(user) { return true; });
} | [
"function",
"Rollout",
"(",
"client",
")",
"{",
"this",
".",
"client",
"=",
"client",
"||",
"redis",
".",
"createClient",
"(",
")",
";",
"this",
".",
"_id",
"=",
"'id'",
";",
"this",
".",
"_namespace",
"=",
"null",
";",
"this",
".",
"_groups",
"=",
"{",
"}",
";",
"this",
".",
"group",
"(",
"'all'",
",",
"function",
"(",
"user",
")",
"{",
"return",
"true",
";",
"}",
")",
";",
"}"
]
| Rollout constructor.
@param {Redis} client A redis instance. | [
"Rollout",
"constructor",
"."
]
| 78f7ed4292defb056641de9c8c9370cd75daee73 | https://github.com/thehydroimpulse/rollout/blob/78f7ed4292defb056641de9c8c9370cd75daee73/index.js#L27-L34 |
46,406 | evaletolab/karibou-wallet | lib/wallet.driver.mongoose.js | objectToSignature | function objectToSignature(source) {
function sortObject(input) {
if(typeof input !== 'object' ||input===null)
return input
var output = {};
Object.keys(input).sort().forEach(function (key) {
output[key] = sortObject(input[key]);
});
return output;
}
var signature={};
//
// what about transactions and transfers ??
// FIXME append 'amount_negative',
['balance','card','id','wid','email','apikey'].forEach(function (key) {
signature[key]=source[key];
});
return sortObject(signature);
} | javascript | function objectToSignature(source) {
function sortObject(input) {
if(typeof input !== 'object' ||input===null)
return input
var output = {};
Object.keys(input).sort().forEach(function (key) {
output[key] = sortObject(input[key]);
});
return output;
}
var signature={};
//
// what about transactions and transfers ??
// FIXME append 'amount_negative',
['balance','card','id','wid','email','apikey'].forEach(function (key) {
signature[key]=source[key];
});
return sortObject(signature);
} | [
"function",
"objectToSignature",
"(",
"source",
")",
"{",
"function",
"sortObject",
"(",
"input",
")",
"{",
"if",
"(",
"typeof",
"input",
"!==",
"'object'",
"||",
"input",
"===",
"null",
")",
"return",
"input",
"var",
"output",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"input",
")",
".",
"sort",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"output",
"[",
"key",
"]",
"=",
"sortObject",
"(",
"input",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"return",
"output",
";",
"}",
"var",
"signature",
"=",
"{",
"}",
";",
"//",
"// what about transactions and transfers ??",
"// FIXME append 'amount_negative',",
"[",
"'balance'",
",",
"'card'",
",",
"'id'",
",",
"'wid'",
",",
"'email'",
",",
"'apikey'",
"]",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"signature",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"sortObject",
"(",
"signature",
")",
";",
"}"
]
| this is used to prepare the object signature | [
"this",
"is",
"used",
"to",
"prepare",
"the",
"object",
"signature"
]
| 2d072b7d1412e8d486be8a8beb77273f1a17c2ef | https://github.com/evaletolab/karibou-wallet/blob/2d072b7d1412e8d486be8a8beb77273f1a17c2ef/lib/wallet.driver.mongoose.js#L62-L81 |
46,407 | mattmcmanus/node-helmsman | helmsman.js | defaultFillCommandData | function defaultFillCommandData(defaults, file, extension) {
var data;
try {
data = require(file).command || {};
} catch (e) {
// If it's JavaScript then return the error
if (extension === '.js') {
data = {failedRequire: e};
}
}
return _.merge(defaults, data);
} | javascript | function defaultFillCommandData(defaults, file, extension) {
var data;
try {
data = require(file).command || {};
} catch (e) {
// If it's JavaScript then return the error
if (extension === '.js') {
data = {failedRequire: e};
}
}
return _.merge(defaults, data);
} | [
"function",
"defaultFillCommandData",
"(",
"defaults",
",",
"file",
",",
"extension",
")",
"{",
"var",
"data",
";",
"try",
"{",
"data",
"=",
"require",
"(",
"file",
")",
".",
"command",
"||",
"{",
"}",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// If it's JavaScript then return the error",
"if",
"(",
"extension",
"===",
"'.js'",
")",
"{",
"data",
"=",
"{",
"failedRequire",
":",
"e",
"}",
";",
"}",
"}",
"return",
"_",
".",
"merge",
"(",
"defaults",
",",
"data",
")",
";",
"}"
]
| The default function used to get metadata from a command | [
"The",
"default",
"function",
"used",
"to",
"get",
"metadata",
"from",
"a",
"command"
]
| 50b285676f077a72c7408e28b2c5b3a395db1f6a | https://github.com/mattmcmanus/node-helmsman/blob/50b285676f077a72c7408e28b2c5b3a395db1f6a/helmsman.js#L22-L35 |
46,408 | mattmcmanus/node-helmsman | helmsman.js | isOneOrMore | function isOneOrMore(commands, iterator) {
var list = commands.filter(iterator);
if (list.length === 1) {
return list[0];
} else if (list.length > 1) {
return new Error(util.format('There are %d options for "%s": %s',
list.length, cmd, list.join(', ')));
}
return false;
} | javascript | function isOneOrMore(commands, iterator) {
var list = commands.filter(iterator);
if (list.length === 1) {
return list[0];
} else if (list.length > 1) {
return new Error(util.format('There are %d options for "%s": %s',
list.length, cmd, list.join(', ')));
}
return false;
} | [
"function",
"isOneOrMore",
"(",
"commands",
",",
"iterator",
")",
"{",
"var",
"list",
"=",
"commands",
".",
"filter",
"(",
"iterator",
")",
";",
"if",
"(",
"list",
".",
"length",
"===",
"1",
")",
"{",
"return",
"list",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"list",
".",
"length",
">",
"1",
")",
"{",
"return",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"'There are %d options for \"%s\": %s'",
",",
"list",
".",
"length",
",",
"cmd",
",",
"list",
".",
"join",
"(",
"', '",
")",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Determine how many commands match the iterator. Return one if command, | [
"Determine",
"how",
"many",
"commands",
"match",
"the",
"iterator",
".",
"Return",
"one",
"if",
"command"
]
| 50b285676f077a72c7408e28b2c5b3a395db1f6a | https://github.com/mattmcmanus/node-helmsman/blob/50b285676f077a72c7408e28b2c5b3a395db1f6a/helmsman.js#L205-L216 |
46,409 | AXErunners/axecore-p2p | lib/messages/commands/filteradd.js | FilteraddMessage | function FilteraddMessage(arg, options) {
Message.call(this, options);
this.command = 'filteradd';
$.checkArgument(
_.isUndefined(arg) || BufferUtil.isBuffer(arg),
'First argument is expected to be a Buffer or undefined'
);
this.data = arg || BufferUtil.EMPTY_BUFFER;
} | javascript | function FilteraddMessage(arg, options) {
Message.call(this, options);
this.command = 'filteradd';
$.checkArgument(
_.isUndefined(arg) || BufferUtil.isBuffer(arg),
'First argument is expected to be a Buffer or undefined'
);
this.data = arg || BufferUtil.EMPTY_BUFFER;
} | [
"function",
"FilteraddMessage",
"(",
"arg",
",",
"options",
")",
"{",
"Message",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"command",
"=",
"'filteradd'",
";",
"$",
".",
"checkArgument",
"(",
"_",
".",
"isUndefined",
"(",
"arg",
")",
"||",
"BufferUtil",
".",
"isBuffer",
"(",
"arg",
")",
",",
"'First argument is expected to be a Buffer or undefined'",
")",
";",
"this",
".",
"data",
"=",
"arg",
"||",
"BufferUtil",
".",
"EMPTY_BUFFER",
";",
"}"
]
| Request peer to add data to a bloom filter already set by 'filterload'
@param {Buffer=} data - Array of bytes representing bloom filter data
@param {Object=} options
@extends Message
@constructor | [
"Request",
"peer",
"to",
"add",
"data",
"to",
"a",
"bloom",
"filter",
"already",
"set",
"by",
"filterload"
]
| c06d0e1d7b9ed44b7ee3061feb394d3896240da9 | https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/filteradd.js#L20-L28 |
46,410 | flipside/gulp-graphql | index.js | function (dirname, options) {
var src = options.graphqlPath || (dirname + '/node_modules/graphql');
// console.log(src);
try {
graphql = require(src).graphql;
var graphqlUtil = require(src + '/utilities');
introspectionQuery = graphqlUtil.introspectionQuery;
printSchema = graphqlUtil.printSchema;
} catch (err) {
throw new gutil.PluginError('gulp-graphql', err, {
message: 'failed to load graphql from ' + src
});
}
if (!graphql || !introspectionQuery || !printSchema) {
throw new gutil.PluginError('gulp-graphql',
'failed to load graphql from ' + src);
}
} | javascript | function (dirname, options) {
var src = options.graphqlPath || (dirname + '/node_modules/graphql');
// console.log(src);
try {
graphql = require(src).graphql;
var graphqlUtil = require(src + '/utilities');
introspectionQuery = graphqlUtil.introspectionQuery;
printSchema = graphqlUtil.printSchema;
} catch (err) {
throw new gutil.PluginError('gulp-graphql', err, {
message: 'failed to load graphql from ' + src
});
}
if (!graphql || !introspectionQuery || !printSchema) {
throw new gutil.PluginError('gulp-graphql',
'failed to load graphql from ' + src);
}
} | [
"function",
"(",
"dirname",
",",
"options",
")",
"{",
"var",
"src",
"=",
"options",
".",
"graphqlPath",
"||",
"(",
"dirname",
"+",
"'/node_modules/graphql'",
")",
";",
"// console.log(src);",
"try",
"{",
"graphql",
"=",
"require",
"(",
"src",
")",
".",
"graphql",
";",
"var",
"graphqlUtil",
"=",
"require",
"(",
"src",
"+",
"'/utilities'",
")",
";",
"introspectionQuery",
"=",
"graphqlUtil",
".",
"introspectionQuery",
";",
"printSchema",
"=",
"graphqlUtil",
".",
"printSchema",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"gutil",
".",
"PluginError",
"(",
"'gulp-graphql'",
",",
"err",
",",
"{",
"message",
":",
"'failed to load graphql from '",
"+",
"src",
"}",
")",
";",
"}",
"if",
"(",
"!",
"graphql",
"||",
"!",
"introspectionQuery",
"||",
"!",
"printSchema",
")",
"{",
"throw",
"new",
"gutil",
".",
"PluginError",
"(",
"'gulp-graphql'",
",",
"'failed to load graphql from '",
"+",
"src",
")",
";",
"}",
"}"
]
| loads graphql via absolute path to base directory | [
"loads",
"graphql",
"via",
"absolute",
"path",
"to",
"base",
"directory"
]
| 5b8c5044180b92ce3948330040ae474fa73acce0 | https://github.com/flipside/gulp-graphql/blob/5b8c5044180b92ce3948330040ae474fa73acce0/index.js#L9-L28 |
|
46,411 | TimeMagazine/elastic-svg | index.js | resize | function resize() {
console.log("resizing base");
base.width = parent.clientWidth;
svg.setAttributeNS(null, "width", base.width);
// only resize the height if aspect was specified instead of height
if (opts.aspect) {
base.height = base.width * opts.aspect;
svg.setAttributeNS(null, "height", base.height);
}
base.scale = base.width / base.original_width;
// optional callback
if (opts.onResize) {
opts.onResize(base.width, base.height, base.scale);
}
} | javascript | function resize() {
console.log("resizing base");
base.width = parent.clientWidth;
svg.setAttributeNS(null, "width", base.width);
// only resize the height if aspect was specified instead of height
if (opts.aspect) {
base.height = base.width * opts.aspect;
svg.setAttributeNS(null, "height", base.height);
}
base.scale = base.width / base.original_width;
// optional callback
if (opts.onResize) {
opts.onResize(base.width, base.height, base.scale);
}
} | [
"function",
"resize",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"resizing base\"",
")",
";",
"base",
".",
"width",
"=",
"parent",
".",
"clientWidth",
";",
"svg",
".",
"setAttributeNS",
"(",
"null",
",",
"\"width\"",
",",
"base",
".",
"width",
")",
";",
"// only resize the height if aspect was specified instead of height",
"if",
"(",
"opts",
".",
"aspect",
")",
"{",
"base",
".",
"height",
"=",
"base",
".",
"width",
"*",
"opts",
".",
"aspect",
";",
"svg",
".",
"setAttributeNS",
"(",
"null",
",",
"\"height\"",
",",
"base",
".",
"height",
")",
";",
"}",
"base",
".",
"scale",
"=",
"base",
".",
"width",
"/",
"base",
".",
"original_width",
";",
"// optional callback",
"if",
"(",
"opts",
".",
"onResize",
")",
"{",
"opts",
".",
"onResize",
"(",
"base",
".",
"width",
",",
"base",
".",
"height",
",",
"base",
".",
"scale",
")",
";",
"}",
"}"
]
| function called when the window resizes | [
"function",
"called",
"when",
"the",
"window",
"resizes"
]
| 39ab1051953c3c4947803c3badf7776ffbc25cbc | https://github.com/TimeMagazine/elastic-svg/blob/39ab1051953c3c4947803c3badf7776ffbc25cbc/index.js#L52-L69 |
46,412 | dschenkelman/z-schema-errors | lib/index.js | distinct | function distinct(array){
return Object.keys(array.reduce(function(current, value){
current[value] = true;
return current;
}, {}));
} | javascript | function distinct(array){
return Object.keys(array.reduce(function(current, value){
current[value] = true;
return current;
}, {}));
} | [
"function",
"distinct",
"(",
"array",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"array",
".",
"reduce",
"(",
"function",
"(",
"current",
",",
"value",
")",
"{",
"current",
"[",
"value",
"]",
"=",
"true",
";",
"return",
"current",
";",
"}",
",",
"{",
"}",
")",
")",
";",
"}"
]
| only for array of strings | [
"only",
"for",
"array",
"of",
"strings"
]
| ddf02965869d34e7cbf11db0e16c4bf14f1d4e53 | https://github.com/dschenkelman/z-schema-errors/blob/ddf02965869d34e7cbf11db0e16c4bf14f1d4e53/lib/index.js#L8-L13 |
46,413 | NiklasGollenstede/web-ext-utils | utils/files.js | readFile | async function readFile(path, encoding) {
const url = browser.extension.getURL(realpath(path));
return new Promise((resolve, reject) => {
const xhr = new global.XMLHttpRequest;
xhr.responseType = encoding == null ? 'arraybuffer' : 'text';
xhr.addEventListener('load', () => resolve(xhr.response));
xhr.addEventListener('error', reject);
xhr.open('GET', url);
xhr.send();
});
} | javascript | async function readFile(path, encoding) {
const url = browser.extension.getURL(realpath(path));
return new Promise((resolve, reject) => {
const xhr = new global.XMLHttpRequest;
xhr.responseType = encoding == null ? 'arraybuffer' : 'text';
xhr.addEventListener('load', () => resolve(xhr.response));
xhr.addEventListener('error', reject);
xhr.open('GET', url);
xhr.send();
});
} | [
"async",
"function",
"readFile",
"(",
"path",
",",
"encoding",
")",
"{",
"const",
"url",
"=",
"browser",
".",
"extension",
".",
"getURL",
"(",
"realpath",
"(",
"path",
")",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"xhr",
"=",
"new",
"global",
".",
"XMLHttpRequest",
";",
"xhr",
".",
"responseType",
"=",
"encoding",
"==",
"null",
"?",
"'arraybuffer'",
":",
"'text'",
";",
"xhr",
".",
"addEventListener",
"(",
"'load'",
",",
"(",
")",
"=>",
"resolve",
"(",
"xhr",
".",
"response",
")",
")",
";",
"xhr",
".",
"addEventListener",
"(",
"'error'",
",",
"reject",
")",
";",
"xhr",
".",
"open",
"(",
"'GET'",
",",
"url",
")",
";",
"xhr",
".",
"send",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Loads a file included in the extension.
@param {string} path Absolute path of the file to read.
@param {string} encoding Optional. Allowed values: 'utf-8'
@return {any} [description] | [
"Loads",
"a",
"file",
"included",
"in",
"the",
"extension",
"."
]
| 395698c633da88db86377d583b9b4eac6d9cc299 | https://github.com/NiklasGollenstede/web-ext-utils/blob/395698c633da88db86377d583b9b4eac6d9cc299/utils/files.js#L60-L71 |
46,414 | AXErunners/axecore-p2p | lib/messages/commands/version.js | VersionMessage | function VersionMessage(arg, options) {
/* jshint maxcomplexity: 10 */
if (!arg) {
arg = {};
}
Message.call(this, options);
this.command = 'version';
this.version = arg.version || options.protocolVersion;
this.nonce = arg.nonce || utils.getNonce();
this.services = arg.services || new BN(1, 10);
this.timestamp = arg.timestamp || new Date();
this.subversion = arg.subversion || '/axecore:' + packageInfo.version + '/';
this.startHeight = arg.startHeight || 0;
this.relay = arg.relay === false ? false : true;
} | javascript | function VersionMessage(arg, options) {
/* jshint maxcomplexity: 10 */
if (!arg) {
arg = {};
}
Message.call(this, options);
this.command = 'version';
this.version = arg.version || options.protocolVersion;
this.nonce = arg.nonce || utils.getNonce();
this.services = arg.services || new BN(1, 10);
this.timestamp = arg.timestamp || new Date();
this.subversion = arg.subversion || '/axecore:' + packageInfo.version + '/';
this.startHeight = arg.startHeight || 0;
this.relay = arg.relay === false ? false : true;
} | [
"function",
"VersionMessage",
"(",
"arg",
",",
"options",
")",
"{",
"/* jshint maxcomplexity: 10 */",
"if",
"(",
"!",
"arg",
")",
"{",
"arg",
"=",
"{",
"}",
";",
"}",
"Message",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"command",
"=",
"'version'",
";",
"this",
".",
"version",
"=",
"arg",
".",
"version",
"||",
"options",
".",
"protocolVersion",
";",
"this",
".",
"nonce",
"=",
"arg",
".",
"nonce",
"||",
"utils",
".",
"getNonce",
"(",
")",
";",
"this",
".",
"services",
"=",
"arg",
".",
"services",
"||",
"new",
"BN",
"(",
"1",
",",
"10",
")",
";",
"this",
".",
"timestamp",
"=",
"arg",
".",
"timestamp",
"||",
"new",
"Date",
"(",
")",
";",
"this",
".",
"subversion",
"=",
"arg",
".",
"subversion",
"||",
"'/axecore:'",
"+",
"packageInfo",
".",
"version",
"+",
"'/'",
";",
"this",
".",
"startHeight",
"=",
"arg",
".",
"startHeight",
"||",
"0",
";",
"this",
".",
"relay",
"=",
"arg",
".",
"relay",
"===",
"false",
"?",
"false",
":",
"true",
";",
"}"
]
| The version message is used on connection creation to advertise
the type of node. The remote node will respond with its version, and no
communication is possible until both peers have exchanged their versions.
@see https://en.bitcoin.it/wiki/Protocol_documentation#version
@param {Object=} arg - properties for the version message
@param {Buffer=} arg.nonce - a random 8 byte buffer
@param {String=} arg.subversion - version of the client
@param {BN=} arg.services
@param {Date=} arg.timestamp
@param {Number=} arg.startHeight
@param {Object} options
@extends Message
@constructor | [
"The",
"version",
"message",
"is",
"used",
"on",
"connection",
"creation",
"to",
"advertise",
"the",
"type",
"of",
"node",
".",
"The",
"remote",
"node",
"will",
"respond",
"with",
"its",
"version",
"and",
"no",
"communication",
"is",
"possible",
"until",
"both",
"peers",
"have",
"exchanged",
"their",
"versions",
"."
]
| c06d0e1d7b9ed44b7ee3061feb394d3896240da9 | https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/version.js#L29-L43 |
46,415 | chriswongtv/node-all-paths | libs/populateMap.js | validateNode | function validateNode (cost) {
cost = Number(cost)
if (isNaN(cost)) {
throw new TypeError(`Cost must be a number, istead got ${cost}`)
}
if (cost <= 0) {
throw new TypeError(`The cost must be a number above 0, instead got ${cost}`)
}
return cost
} | javascript | function validateNode (cost) {
cost = Number(cost)
if (isNaN(cost)) {
throw new TypeError(`Cost must be a number, istead got ${cost}`)
}
if (cost <= 0) {
throw new TypeError(`The cost must be a number above 0, instead got ${cost}`)
}
return cost
} | [
"function",
"validateNode",
"(",
"cost",
")",
"{",
"cost",
"=",
"Number",
"(",
"cost",
")",
"if",
"(",
"isNaN",
"(",
"cost",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"cost",
"}",
"`",
")",
"}",
"if",
"(",
"cost",
"<=",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"cost",
"}",
"`",
")",
"}",
"return",
"cost",
"}"
]
| Assert that the provided cost in a positive number
@private
@param {number} cost Cost to validate
@return {number} cost | [
"Assert",
"that",
"the",
"provided",
"cost",
"in",
"a",
"positive",
"number"
]
| 69cc7d0a834e1d7179c2ba7990624ca7468ded1d | https://github.com/chriswongtv/node-all-paths/blob/69cc7d0a834e1d7179c2ba7990624ca7468ded1d/libs/populateMap.js#L10-L22 |
46,416 | chriswongtv/node-all-paths | libs/populateMap.js | populateMap | function populateMap (map, object, keys) {
// Return the map once all the keys have been populated
if (!keys.length) return map
let key = keys.shift()
let value = object[key]
if (value !== null && typeof value === 'object') {
// When the key is an object, we recursevely populate its proprieties into
// a new `Map`
value = populateMap(new Map(), value, Object.keys(value))
} else {
// Ensure the node is a positive number
value = validateNode(value)
}
// Set the value into the map
map.set(key, value)
// Recursive call
return populateMap(map, object, keys)
} | javascript | function populateMap (map, object, keys) {
// Return the map once all the keys have been populated
if (!keys.length) return map
let key = keys.shift()
let value = object[key]
if (value !== null && typeof value === 'object') {
// When the key is an object, we recursevely populate its proprieties into
// a new `Map`
value = populateMap(new Map(), value, Object.keys(value))
} else {
// Ensure the node is a positive number
value = validateNode(value)
}
// Set the value into the map
map.set(key, value)
// Recursive call
return populateMap(map, object, keys)
} | [
"function",
"populateMap",
"(",
"map",
",",
"object",
",",
"keys",
")",
"{",
"// Return the map once all the keys have been populated",
"if",
"(",
"!",
"keys",
".",
"length",
")",
"return",
"map",
"let",
"key",
"=",
"keys",
".",
"shift",
"(",
")",
"let",
"value",
"=",
"object",
"[",
"key",
"]",
"if",
"(",
"value",
"!==",
"null",
"&&",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"// When the key is an object, we recursevely populate its proprieties into",
"// a new `Map`",
"value",
"=",
"populateMap",
"(",
"new",
"Map",
"(",
")",
",",
"value",
",",
"Object",
".",
"keys",
"(",
"value",
")",
")",
"}",
"else",
"{",
"// Ensure the node is a positive number",
"value",
"=",
"validateNode",
"(",
"value",
")",
"}",
"// Set the value into the map",
"map",
".",
"set",
"(",
"key",
",",
"value",
")",
"// Recursive call",
"return",
"populateMap",
"(",
"map",
",",
"object",
",",
"keys",
")",
"}"
]
| Populates the `Map` passed as first agument with the values in the provided
object. Supports nested objects, recursively adding them to a `Map`
@param {Map} map `Map` to populate with the values from the object
@param {object} object Object to translate into the `Map`
@param {array} keys Keys of the object to assign to the `Map`
@return {Map} Populated `Map` with nested `Map`s | [
"Populates",
"the",
"Map",
"passed",
"as",
"first",
"agument",
"with",
"the",
"values",
"in",
"the",
"provided",
"object",
".",
"Supports",
"nested",
"objects",
"recursively",
"adding",
"them",
"to",
"a",
"Map"
]
| 69cc7d0a834e1d7179c2ba7990624ca7468ded1d | https://github.com/chriswongtv/node-all-paths/blob/69cc7d0a834e1d7179c2ba7990624ca7468ded1d/libs/populateMap.js#L34-L55 |
46,417 | traedamatic/bunyan-mongodb-stream | lib/logStream.js | LogStream | function LogStream(options) {
this.model = options.model || false;
if (!this.model) {
throw new Error('[LogStream] - Fatal Error - No mongoose model provided!');
}
Writable.call(this, options);
} | javascript | function LogStream(options) {
this.model = options.model || false;
if (!this.model) {
throw new Error('[LogStream] - Fatal Error - No mongoose model provided!');
}
Writable.call(this, options);
} | [
"function",
"LogStream",
"(",
"options",
")",
"{",
"this",
".",
"model",
"=",
"options",
".",
"model",
"||",
"false",
";",
"if",
"(",
"!",
"this",
".",
"model",
")",
"{",
"throw",
"new",
"Error",
"(",
"'[LogStream] - Fatal Error - No mongoose model provided!'",
")",
";",
"}",
"Writable",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"}"
]
| the LogStream constructor.
it inherits all methods of a writable stream
the constructor takes a options object. A important field is the model, the model will
be used for saving the log entry to the mongo db instance.
@param options
@constructor | [
"the",
"LogStream",
"constructor",
".",
"it",
"inherits",
"all",
"methods",
"of",
"a",
"writable",
"stream",
"the",
"constructor",
"takes",
"a",
"options",
"object",
".",
"A",
"important",
"field",
"is",
"the",
"model",
"the",
"model",
"will",
"be",
"used",
"for",
"saving",
"the",
"log",
"entry",
"to",
"the",
"mongo",
"db",
"instance",
"."
]
| d28cd8d7f4266287ebc502986e94c683e45b5587 | https://github.com/traedamatic/bunyan-mongodb-stream/blob/d28cd8d7f4266287ebc502986e94c683e45b5587/lib/logStream.js#L14-L23 |
46,418 | AXErunners/axecore-p2p | lib/messages/commands/headers.js | HeadersMessage | function HeadersMessage(arg, options) {
Message.call(this, options);
this.BlockHeader = options.BlockHeader;
this.command = 'headers';
$.checkArgument(
_.isUndefined(arg) || (Array.isArray(arg) && arg[0] instanceof this.BlockHeader),
'First argument is expected to be an array of BlockHeader instances'
);
this.headers = arg;
} | javascript | function HeadersMessage(arg, options) {
Message.call(this, options);
this.BlockHeader = options.BlockHeader;
this.command = 'headers';
$.checkArgument(
_.isUndefined(arg) || (Array.isArray(arg) && arg[0] instanceof this.BlockHeader),
'First argument is expected to be an array of BlockHeader instances'
);
this.headers = arg;
} | [
"function",
"HeadersMessage",
"(",
"arg",
",",
"options",
")",
"{",
"Message",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"BlockHeader",
"=",
"options",
".",
"BlockHeader",
";",
"this",
".",
"command",
"=",
"'headers'",
";",
"$",
".",
"checkArgument",
"(",
"_",
".",
"isUndefined",
"(",
"arg",
")",
"||",
"(",
"Array",
".",
"isArray",
"(",
"arg",
")",
"&&",
"arg",
"[",
"0",
"]",
"instanceof",
"this",
".",
"BlockHeader",
")",
",",
"'First argument is expected to be an array of BlockHeader instances'",
")",
";",
"this",
".",
"headers",
"=",
"arg",
";",
"}"
]
| Sent in response to a `getheaders` message. It contains information about
block headers.
@param {Array} arg - An array of BlockHeader instances
@param {Object=} options
@param {Array=} options.headers - array of block headers
@param {Function} options.BlockHeader - a BlockHeader constructor
@extends Message
@constructor | [
"Sent",
"in",
"response",
"to",
"a",
"getheaders",
"message",
".",
"It",
"contains",
"information",
"about",
"block",
"headers",
"."
]
| c06d0e1d7b9ed44b7ee3061feb394d3896240da9 | https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/headers.js#L22-L31 |
46,419 | NiklasGollenstede/web-ext-utils | loader/index.js | runInFrame | async function runInFrame(tabId, frameId, script, ...args) {
if (typeof tabId !== 'number') { tabId = (await getActiveTabId()); }
return (await Frame.get(tabId, frameId || 0)).call(getScource(script), args);
} | javascript | async function runInFrame(tabId, frameId, script, ...args) {
if (typeof tabId !== 'number') { tabId = (await getActiveTabId()); }
return (await Frame.get(tabId, frameId || 0)).call(getScource(script), args);
} | [
"async",
"function",
"runInFrame",
"(",
"tabId",
",",
"frameId",
",",
"script",
",",
"...",
"args",
")",
"{",
"if",
"(",
"typeof",
"tabId",
"!==",
"'number'",
")",
"{",
"tabId",
"=",
"(",
"await",
"getActiveTabId",
"(",
")",
")",
";",
"}",
"return",
"(",
"await",
"Frame",
".",
"get",
"(",
"tabId",
",",
"frameId",
"||",
"0",
")",
")",
".",
"call",
"(",
"getScource",
"(",
"script",
")",
",",
"args",
")",
";",
"}"
]
| Dynamically executes functions as content scripts.
@param {natural|null} tabId The id of the tab to run in. Default to an active tab, preferably in the current window.
@param {natural|null} frameId The id of the frame within the tab to run in. Defaults to the top level frame.
@param {function|string} script A function that will be decompiled and run as content script.
If the "contentEval" manifest permission is set, this may also be a code string that will be wrapped in a function.
@param {...any} args Arguments that will be cloned to call the function with.
`this` in the function will be the global object (not necessarily `window`).
@return {any} The value returned or promised by `script`.
@throws {any} If `script` throws or otherwise fails to execute. | [
"Dynamically",
"executes",
"functions",
"as",
"content",
"scripts",
"."
]
| 395698c633da88db86377d583b9b4eac6d9cc299 | https://github.com/NiklasGollenstede/web-ext-utils/blob/395698c633da88db86377d583b9b4eac6d9cc299/loader/index.js#L22-L25 |
46,420 | hakobera/mai | lib/mai.js | function(conf) {
if (!conf) {
throw new Error("'conf' is required");
}
var text, headers, message, smtpClient,
callback = conf.callback || function(){};
text = this._buildTemplate(conf.templateName, conf.params);
headers = this._buildHeaders(conf, text);
message = email.message.create(headers);
this._processAttachments(message, conf.attachments);
debug(message);
if (ENV !== 'test') {
smtpClient = new email.server.connect(this.smtpConf);
smtpClient.send(message, callback);
} else {
conf.callback.call(this, null, message);
}
} | javascript | function(conf) {
if (!conf) {
throw new Error("'conf' is required");
}
var text, headers, message, smtpClient,
callback = conf.callback || function(){};
text = this._buildTemplate(conf.templateName, conf.params);
headers = this._buildHeaders(conf, text);
message = email.message.create(headers);
this._processAttachments(message, conf.attachments);
debug(message);
if (ENV !== 'test') {
smtpClient = new email.server.connect(this.smtpConf);
smtpClient.send(message, callback);
} else {
conf.callback.call(this, null, message);
}
} | [
"function",
"(",
"conf",
")",
"{",
"if",
"(",
"!",
"conf",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"'conf' is required\"",
")",
";",
"}",
"var",
"text",
",",
"headers",
",",
"message",
",",
"smtpClient",
",",
"callback",
"=",
"conf",
".",
"callback",
"||",
"function",
"(",
")",
"{",
"}",
";",
"text",
"=",
"this",
".",
"_buildTemplate",
"(",
"conf",
".",
"templateName",
",",
"conf",
".",
"params",
")",
";",
"headers",
"=",
"this",
".",
"_buildHeaders",
"(",
"conf",
",",
"text",
")",
";",
"message",
"=",
"email",
".",
"message",
".",
"create",
"(",
"headers",
")",
";",
"this",
".",
"_processAttachments",
"(",
"message",
",",
"conf",
".",
"attachments",
")",
";",
"debug",
"(",
"message",
")",
";",
"if",
"(",
"ENV",
"!==",
"'test'",
")",
"{",
"smtpClient",
"=",
"new",
"email",
".",
"server",
".",
"connect",
"(",
"this",
".",
"smtpConf",
")",
";",
"smtpClient",
".",
"send",
"(",
"message",
",",
"callback",
")",
";",
"}",
"else",
"{",
"conf",
".",
"callback",
".",
"call",
"(",
"this",
",",
"null",
",",
"message",
")",
";",
"}",
"}"
]
| Send e-mail.
@param {Object} conf Configuration.
- from {String} Sender of the format (address or name <address> or "name" <address>)
- to {String} Recipients (same format as above), multiple recipients are separated by a comma
- cc {String} [optional] Carbon copied recipients (same format as above)
- bcc {String} [optional] Blind carbon copied recipients (same format as above)
- subject {String} Subject of the email
- templateName {String} Template name to send
- params {Object} [optional] Parameter to bind to template
- attachments {Array.<Object>}
- path {String} String to where the file is located
- type {String} String of the file mime type
- name {String} Name to give the file as perceived by the recipient
- callback {Function} [optional] Callback function, which called when send finished. | [
"Send",
"e",
"-",
"mail",
"."
]
| 0e8e56fc66c31a59588ff6fbea04152674c5910e | https://github.com/hakobera/mai/blob/0e8e56fc66c31a59588ff6fbea04152674c5910e/lib/mai.js#L86-L107 |
|
46,421 | pgherveou/gulp-file-cache | index.js | FileCache | function FileCache(name) {
this._filename = name || '.gulp-cache';
// load cache
try {
this._cache = JSON.parse(fs.readFileSync(this._filename, 'utf8'));
} catch (err) {
this._cache = {};
}
} | javascript | function FileCache(name) {
this._filename = name || '.gulp-cache';
// load cache
try {
this._cache = JSON.parse(fs.readFileSync(this._filename, 'utf8'));
} catch (err) {
this._cache = {};
}
} | [
"function",
"FileCache",
"(",
"name",
")",
"{",
"this",
".",
"_filename",
"=",
"name",
"||",
"'.gulp-cache'",
";",
"// load cache",
"try",
"{",
"this",
".",
"_cache",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"this",
".",
"_filename",
",",
"'utf8'",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"this",
".",
"_cache",
"=",
"{",
"}",
";",
"}",
"}"
]
| create a new FileCache instance | [
"create",
"a",
"new",
"FileCache",
"instance"
]
| 43bc6f48525c04f79a127d5775bf1d5489c65990 | https://github.com/pgherveou/gulp-file-cache/blob/43bc6f48525c04f79a127d5775bf1d5489c65990/index.js#L8-L17 |
46,422 | pgherveou/gulp-file-cache | index.js | flush | function flush(callback) {
fs.writeFile(_this._filename, JSON.stringify(_this._cache), callback);
} | javascript | function flush(callback) {
fs.writeFile(_this._filename, JSON.stringify(_this._cache), callback);
} | [
"function",
"flush",
"(",
"callback",
")",
"{",
"fs",
".",
"writeFile",
"(",
"_this",
".",
"_filename",
",",
"JSON",
".",
"stringify",
"(",
"_this",
".",
"_cache",
")",
",",
"callback",
")",
";",
"}"
]
| flush cache to disk | [
"flush",
"cache",
"to",
"disk"
]
| 43bc6f48525c04f79a127d5775bf1d5489c65990 | https://github.com/pgherveou/gulp-file-cache/blob/43bc6f48525c04f79a127d5775bf1d5489c65990/index.js#L40-L42 |
46,423 | mpayetta/statsd-newrelic-backend | lib/dispatcher/metric-name.js | function (metricType, statsdKey) {
statsdKey = statsdKey.replace(/([^a-zA-Z0-9:_])/g, '_');
return [prefixes[metricType], '_', statsdKey].join('');
} | javascript | function (metricType, statsdKey) {
statsdKey = statsdKey.replace(/([^a-zA-Z0-9:_])/g, '_');
return [prefixes[metricType], '_', statsdKey].join('');
} | [
"function",
"(",
"metricType",
",",
"statsdKey",
")",
"{",
"statsdKey",
"=",
"statsdKey",
".",
"replace",
"(",
"/",
"([^a-zA-Z0-9:_])",
"/",
"g",
",",
"'_'",
")",
";",
"return",
"[",
"prefixes",
"[",
"metricType",
"]",
",",
"'_'",
",",
"statsdKey",
"]",
".",
"join",
"(",
"''",
")",
";",
"}"
]
| Custom events don't allow to have dots in the name so we need to replace them with '_' | [
"Custom",
"events",
"don",
"t",
"allow",
"to",
"have",
"dots",
"in",
"the",
"name",
"so",
"we",
"need",
"to",
"replace",
"them",
"with",
"_"
]
| 64caaa368d9732c6bab916c91f46492eeb2392ba | https://github.com/mpayetta/statsd-newrelic-backend/blob/64caaa368d9732c6bab916c91f46492eeb2392ba/lib/dispatcher/metric-name.js#L22-L25 |
|
46,424 | wooorm/bcp-47-match | index.js | factory | function factory(check, filter) {
return match
function match(tags, ranges) {
var values = normalize(tags, ranges)
var result = []
var next
var tagIndex
var tagLength
var tag
var rangeIndex
var rangeLength
var range
var matches
tags = values.tags
ranges = values.ranges
rangeLength = ranges.length
rangeIndex = -1
while (++rangeIndex < rangeLength) {
range = ranges[rangeIndex]
// Ignore wildcards in lookup mode.
if (!filter && range === asterisk) {
continue
}
tagLength = tags.length
tagIndex = -1
next = []
while (++tagIndex < tagLength) {
tag = tags[tagIndex]
matches = check(tag, range)
;(matches ? result : next).push(tag)
// Exit if this is a lookup and we have a match.
if (!filter && matches) {
return tag
}
}
tags = next
}
// If this is a filter, return the list. If it’s a lookup, we didn’t find
// a match, so return `undefined`.
return filter ? result : undefined
}
} | javascript | function factory(check, filter) {
return match
function match(tags, ranges) {
var values = normalize(tags, ranges)
var result = []
var next
var tagIndex
var tagLength
var tag
var rangeIndex
var rangeLength
var range
var matches
tags = values.tags
ranges = values.ranges
rangeLength = ranges.length
rangeIndex = -1
while (++rangeIndex < rangeLength) {
range = ranges[rangeIndex]
// Ignore wildcards in lookup mode.
if (!filter && range === asterisk) {
continue
}
tagLength = tags.length
tagIndex = -1
next = []
while (++tagIndex < tagLength) {
tag = tags[tagIndex]
matches = check(tag, range)
;(matches ? result : next).push(tag)
// Exit if this is a lookup and we have a match.
if (!filter && matches) {
return tag
}
}
tags = next
}
// If this is a filter, return the list. If it’s a lookup, we didn’t find
// a match, so return `undefined`.
return filter ? result : undefined
}
} | [
"function",
"factory",
"(",
"check",
",",
"filter",
")",
"{",
"return",
"match",
"function",
"match",
"(",
"tags",
",",
"ranges",
")",
"{",
"var",
"values",
"=",
"normalize",
"(",
"tags",
",",
"ranges",
")",
"var",
"result",
"=",
"[",
"]",
"var",
"next",
"var",
"tagIndex",
"var",
"tagLength",
"var",
"tag",
"var",
"rangeIndex",
"var",
"rangeLength",
"var",
"range",
"var",
"matches",
"tags",
"=",
"values",
".",
"tags",
"ranges",
"=",
"values",
".",
"ranges",
"rangeLength",
"=",
"ranges",
".",
"length",
"rangeIndex",
"=",
"-",
"1",
"while",
"(",
"++",
"rangeIndex",
"<",
"rangeLength",
")",
"{",
"range",
"=",
"ranges",
"[",
"rangeIndex",
"]",
"// Ignore wildcards in lookup mode.",
"if",
"(",
"!",
"filter",
"&&",
"range",
"===",
"asterisk",
")",
"{",
"continue",
"}",
"tagLength",
"=",
"tags",
".",
"length",
"tagIndex",
"=",
"-",
"1",
"next",
"=",
"[",
"]",
"while",
"(",
"++",
"tagIndex",
"<",
"tagLength",
")",
"{",
"tag",
"=",
"tags",
"[",
"tagIndex",
"]",
"matches",
"=",
"check",
"(",
"tag",
",",
"range",
")",
";",
"(",
"matches",
"?",
"result",
":",
"next",
")",
".",
"push",
"(",
"tag",
")",
"// Exit if this is a lookup and we have a match.",
"if",
"(",
"!",
"filter",
"&&",
"matches",
")",
"{",
"return",
"tag",
"}",
"}",
"tags",
"=",
"next",
"}",
"// If this is a filter, return the list. If it’s a lookup, we didn’t find",
"// a match, so return `undefined`.",
"return",
"filter",
"?",
"result",
":",
"undefined",
"}",
"}"
]
| Factory to perform a filter or a lookup. This factory creates a function that accepts a list of tags and a list of ranges, and contains logic to exit early for lookups. `check` just has to deal with one tag and one range. This match function iterates over ranges, and for each range, iterates over tags. That way, earlier ranges matching any tag have precedence over later ranges. | [
"Factory",
"to",
"perform",
"a",
"filter",
"or",
"a",
"lookup",
".",
"This",
"factory",
"creates",
"a",
"function",
"that",
"accepts",
"a",
"list",
"of",
"tags",
"and",
"a",
"list",
"of",
"ranges",
"and",
"contains",
"logic",
"to",
"exit",
"early",
"for",
"lookups",
".",
"check",
"just",
"has",
"to",
"deal",
"with",
"one",
"tag",
"and",
"one",
"range",
".",
"This",
"match",
"function",
"iterates",
"over",
"ranges",
"and",
"for",
"each",
"range",
"iterates",
"over",
"tags",
".",
"That",
"way",
"earlier",
"ranges",
"matching",
"any",
"tag",
"have",
"precedence",
"over",
"later",
"ranges",
"."
]
| 7f726bc9ed245b63c87b597952135d4d00981e3b | https://github.com/wooorm/bcp-47-match/blob/7f726bc9ed245b63c87b597952135d4d00981e3b/index.js#L113-L163 |
46,425 | wooorm/bcp-47-match | index.js | cast | function cast(values, name) {
var value = values && typeof values === 'string' ? [values] : values
if (!value || typeof value !== 'object' || !('length' in value)) {
throw new Error(
'Invalid ' + name + ' `' + value + '`, expected non-empty string'
)
}
return value
} | javascript | function cast(values, name) {
var value = values && typeof values === 'string' ? [values] : values
if (!value || typeof value !== 'object' || !('length' in value)) {
throw new Error(
'Invalid ' + name + ' `' + value + '`, expected non-empty string'
)
}
return value
} | [
"function",
"cast",
"(",
"values",
",",
"name",
")",
"{",
"var",
"value",
"=",
"values",
"&&",
"typeof",
"values",
"===",
"'string'",
"?",
"[",
"values",
"]",
":",
"values",
"if",
"(",
"!",
"value",
"||",
"typeof",
"value",
"!==",
"'object'",
"||",
"!",
"(",
"'length'",
"in",
"value",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid '",
"+",
"name",
"+",
"' `'",
"+",
"value",
"+",
"'`, expected non-empty string'",
")",
"}",
"return",
"value",
"}"
]
| Validate tags or ranges, and cast them to arrays. | [
"Validate",
"tags",
"or",
"ranges",
"and",
"cast",
"them",
"to",
"arrays",
"."
]
| 7f726bc9ed245b63c87b597952135d4d00981e3b | https://github.com/wooorm/bcp-47-match/blob/7f726bc9ed245b63c87b597952135d4d00981e3b/index.js#L173-L183 |
46,426 | chrahunt/tagpro-navmesh | gulpfile.js | watchifyFile | function watchifyFile(src, out) {
var opts = assign({}, watchify.args, {
entries: src,
standalone: "NavMesh",
debug: true
});
var b = watchify(browserify(opts));
function bundle() {
return b.bundle()
.on('error', gutil.log.bind(gutil, "Browserify Error"))
.pipe(source(src.replace(/^src\//, '')))
.pipe(derequire())
.pipe(gulp.dest(out));
}
b.on('update', bundle);
b.on('log', gutil.log);
return bundle();
} | javascript | function watchifyFile(src, out) {
var opts = assign({}, watchify.args, {
entries: src,
standalone: "NavMesh",
debug: true
});
var b = watchify(browserify(opts));
function bundle() {
return b.bundle()
.on('error', gutil.log.bind(gutil, "Browserify Error"))
.pipe(source(src.replace(/^src\//, '')))
.pipe(derequire())
.pipe(gulp.dest(out));
}
b.on('update', bundle);
b.on('log', gutil.log);
return bundle();
} | [
"function",
"watchifyFile",
"(",
"src",
",",
"out",
")",
"{",
"var",
"opts",
"=",
"assign",
"(",
"{",
"}",
",",
"watchify",
".",
"args",
",",
"{",
"entries",
":",
"src",
",",
"standalone",
":",
"\"NavMesh\"",
",",
"debug",
":",
"true",
"}",
")",
";",
"var",
"b",
"=",
"watchify",
"(",
"browserify",
"(",
"opts",
")",
")",
";",
"function",
"bundle",
"(",
")",
"{",
"return",
"b",
".",
"bundle",
"(",
")",
".",
"on",
"(",
"'error'",
",",
"gutil",
".",
"log",
".",
"bind",
"(",
"gutil",
",",
"\"Browserify Error\"",
")",
")",
".",
"pipe",
"(",
"source",
"(",
"src",
".",
"replace",
"(",
"/",
"^src\\/",
"/",
",",
"''",
")",
")",
")",
".",
"pipe",
"(",
"derequire",
"(",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"out",
")",
")",
";",
"}",
"b",
".",
"on",
"(",
"'update'",
",",
"bundle",
")",
";",
"b",
".",
"on",
"(",
"'log'",
",",
"gutil",
".",
"log",
")",
";",
"return",
"bundle",
"(",
")",
";",
"}"
]
| Compile and watchify sourced file. | [
"Compile",
"and",
"watchify",
"sourced",
"file",
"."
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/gulpfile.js#L53-L70 |
46,427 | chrahunt/tagpro-navmesh | src/navmesh.js | function(tile) {
var x = tile.x;
var y = tile.y;
var xUp = x + 1 < xUpperBound;
var xDown = x >= 0;
var yUp = y + 1 < yUpperBound;
var yDown = y >= 0;
var adjacents = [];
if (xUp) {
adjacents.push({x: x + 1, y: y});
if (yUp) {
adjacents.push({x: x + 1, y: y + 1});
}
if (yDown) {
adjacents.push({x: x + 1, y: y - 1});
}
}
if (xDown) {
adjacents.push({x: x - 1, y: y});
if (yUp) {
adjacents.push({x: x - 1, y: y + 1});
}
if (yDown) {
adjacents.push({x: x - 1, y: y - 1});
}
}
if (yUp) {
adjacents.push({x: x, y: y + 1});
}
if (yDown) {
adjacents.push({x: x, y: y - 1});
}
return adjacents;
} | javascript | function(tile) {
var x = tile.x;
var y = tile.y;
var xUp = x + 1 < xUpperBound;
var xDown = x >= 0;
var yUp = y + 1 < yUpperBound;
var yDown = y >= 0;
var adjacents = [];
if (xUp) {
adjacents.push({x: x + 1, y: y});
if (yUp) {
adjacents.push({x: x + 1, y: y + 1});
}
if (yDown) {
adjacents.push({x: x + 1, y: y - 1});
}
}
if (xDown) {
adjacents.push({x: x - 1, y: y});
if (yUp) {
adjacents.push({x: x - 1, y: y + 1});
}
if (yDown) {
adjacents.push({x: x - 1, y: y - 1});
}
}
if (yUp) {
adjacents.push({x: x, y: y + 1});
}
if (yDown) {
adjacents.push({x: x, y: y - 1});
}
return adjacents;
} | [
"function",
"(",
"tile",
")",
"{",
"var",
"x",
"=",
"tile",
".",
"x",
";",
"var",
"y",
"=",
"tile",
".",
"y",
";",
"var",
"xUp",
"=",
"x",
"+",
"1",
"<",
"xUpperBound",
";",
"var",
"xDown",
"=",
"x",
">=",
"0",
";",
"var",
"yUp",
"=",
"y",
"+",
"1",
"<",
"yUpperBound",
";",
"var",
"yDown",
"=",
"y",
">=",
"0",
";",
"var",
"adjacents",
"=",
"[",
"]",
";",
"if",
"(",
"xUp",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
"+",
"1",
",",
"y",
":",
"y",
"}",
")",
";",
"if",
"(",
"yUp",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
"+",
"1",
",",
"y",
":",
"y",
"+",
"1",
"}",
")",
";",
"}",
"if",
"(",
"yDown",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
"+",
"1",
",",
"y",
":",
"y",
"-",
"1",
"}",
")",
";",
"}",
"}",
"if",
"(",
"xDown",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
"-",
"1",
",",
"y",
":",
"y",
"}",
")",
";",
"if",
"(",
"yUp",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
"-",
"1",
",",
"y",
":",
"y",
"+",
"1",
"}",
")",
";",
"}",
"if",
"(",
"yDown",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
"-",
"1",
",",
"y",
":",
"y",
"-",
"1",
"}",
")",
";",
"}",
"}",
"if",
"(",
"yUp",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
",",
"y",
":",
"y",
"+",
"1",
"}",
")",
";",
"}",
"if",
"(",
"yDown",
")",
"{",
"adjacents",
".",
"push",
"(",
"{",
"x",
":",
"x",
",",
"y",
":",
"y",
"-",
"1",
"}",
")",
";",
"}",
"return",
"adjacents",
";",
"}"
]
| Get the locations adjacent to a given tile in the map. | [
"Get",
"the",
"locations",
"adjacent",
"to",
"a",
"given",
"tile",
"in",
"the",
"map",
"."
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/navmesh.js#L762-L796 |
|
46,428 | AXErunners/axecore-p2p | lib/messages/commands/merkleblock.js | MerkleblockMessage | function MerkleblockMessage(arg, options) {
Message.call(this, options);
this.MerkleBlock = options.MerkleBlock; // constructor
this.command = 'merkleblock';
$.checkArgument(
_.isUndefined(arg) || arg instanceof this.MerkleBlock,
'An instance of MerkleBlock or undefined is expected'
);
this.merkleBlock = arg;
} | javascript | function MerkleblockMessage(arg, options) {
Message.call(this, options);
this.MerkleBlock = options.MerkleBlock; // constructor
this.command = 'merkleblock';
$.checkArgument(
_.isUndefined(arg) || arg instanceof this.MerkleBlock,
'An instance of MerkleBlock or undefined is expected'
);
this.merkleBlock = arg;
} | [
"function",
"MerkleblockMessage",
"(",
"arg",
",",
"options",
")",
"{",
"Message",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"MerkleBlock",
"=",
"options",
".",
"MerkleBlock",
";",
"// constructor",
"this",
".",
"command",
"=",
"'merkleblock'",
";",
"$",
".",
"checkArgument",
"(",
"_",
".",
"isUndefined",
"(",
"arg",
")",
"||",
"arg",
"instanceof",
"this",
".",
"MerkleBlock",
",",
"'An instance of MerkleBlock or undefined is expected'",
")",
";",
"this",
".",
"merkleBlock",
"=",
"arg",
";",
"}"
]
| Contains information about a MerkleBlock
@see https://en.bitcoin.it/wiki/Protocol_documentation
@param {MerkleBlock} arg - An instance of MerkleBlock
@param {Object=} options
@param {Function} options.MerkleBlock - a MerkleBlock constructor
@extends Message
@constructor | [
"Contains",
"information",
"about",
"a",
"MerkleBlock"
]
| c06d0e1d7b9ed44b7ee3061feb394d3896240da9 | https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/merkleblock.js#L19-L28 |
46,429 | mike182uk/cellref | index.js | cellref | function cellref (ref) {
if (R1C1.test(ref)) {
return convertR1C1toA1(ref)
}
if (A1.test(ref)) {
return convertA1toR1C1(ref)
}
throw new Error(`could not detect cell reference notation for ${ref}`)
} | javascript | function cellref (ref) {
if (R1C1.test(ref)) {
return convertR1C1toA1(ref)
}
if (A1.test(ref)) {
return convertA1toR1C1(ref)
}
throw new Error(`could not detect cell reference notation for ${ref}`)
} | [
"function",
"cellref",
"(",
"ref",
")",
"{",
"if",
"(",
"R1C1",
".",
"test",
"(",
"ref",
")",
")",
"{",
"return",
"convertR1C1toA1",
"(",
"ref",
")",
"}",
"if",
"(",
"A1",
".",
"test",
"(",
"ref",
")",
")",
"{",
"return",
"convertA1toR1C1",
"(",
"ref",
")",
"}",
"throw",
"new",
"Error",
"(",
"`",
"${",
"ref",
"}",
"`",
")",
"}"
]
| Auto detect notation used and convert to the opposite notation
@param {String} ref
@returns {String}
@throws {Error} | [
"Auto",
"detect",
"notation",
"used",
"and",
"convert",
"to",
"the",
"opposite",
"notation"
]
| 0f1c9d94bc71632c8f19b52d72632fd5718e4a26 | https://github.com/mike182uk/cellref/blob/0f1c9d94bc71632c8f19b52d72632fd5718e4a26/index.js#L33-L43 |
46,430 | mike182uk/cellref | index.js | convertA1toR1C1 | function convertA1toR1C1 (ref) {
if (!A1.test(ref)) {
throw new Error(`${ref} is not a valid A1 cell reference`)
}
var refParts = ref
.replace(A1, '$1,$2')
.split(',')
var columnStr = refParts[0]
var row = refParts[1]
var column = 0
for (var i = 0; i < columnStr.length; i++) {
column = 26 * column + columnStr.charCodeAt(i) - 64
}
return `R${row}C${column}`
} | javascript | function convertA1toR1C1 (ref) {
if (!A1.test(ref)) {
throw new Error(`${ref} is not a valid A1 cell reference`)
}
var refParts = ref
.replace(A1, '$1,$2')
.split(',')
var columnStr = refParts[0]
var row = refParts[1]
var column = 0
for (var i = 0; i < columnStr.length; i++) {
column = 26 * column + columnStr.charCodeAt(i) - 64
}
return `R${row}C${column}`
} | [
"function",
"convertA1toR1C1",
"(",
"ref",
")",
"{",
"if",
"(",
"!",
"A1",
".",
"test",
"(",
"ref",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"ref",
"}",
"`",
")",
"}",
"var",
"refParts",
"=",
"ref",
".",
"replace",
"(",
"A1",
",",
"'$1,$2'",
")",
".",
"split",
"(",
"','",
")",
"var",
"columnStr",
"=",
"refParts",
"[",
"0",
"]",
"var",
"row",
"=",
"refParts",
"[",
"1",
"]",
"var",
"column",
"=",
"0",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"columnStr",
".",
"length",
";",
"i",
"++",
")",
"{",
"column",
"=",
"26",
"*",
"column",
"+",
"columnStr",
".",
"charCodeAt",
"(",
"i",
")",
"-",
"64",
"}",
"return",
"`",
"${",
"row",
"}",
"${",
"column",
"}",
"`",
"}"
]
| Convert A1 notation to R1C1 notation
@param {String} ref
@returns {String}
@throws {Error} | [
"Convert",
"A1",
"notation",
"to",
"R1C1",
"notation"
]
| 0f1c9d94bc71632c8f19b52d72632fd5718e4a26 | https://github.com/mike182uk/cellref/blob/0f1c9d94bc71632c8f19b52d72632fd5718e4a26/index.js#L53-L71 |
46,431 | mike182uk/cellref | index.js | convertR1C1toA1 | function convertR1C1toA1 (ref) {
if (!R1C1.test(ref)) {
throw new Error(`${ref} is not a valid R1C1 cell reference`)
}
var refParts = ref
.replace(R1C1, '$1,$2')
.split(',')
var row = refParts[0]
var column = refParts[1]
var columnStr = ''
for (; column; column = Math.floor((column - 1) / 26)) {
columnStr = String.fromCharCode(((column - 1) % 26) + 65) + columnStr
}
return columnStr + row
} | javascript | function convertR1C1toA1 (ref) {
if (!R1C1.test(ref)) {
throw new Error(`${ref} is not a valid R1C1 cell reference`)
}
var refParts = ref
.replace(R1C1, '$1,$2')
.split(',')
var row = refParts[0]
var column = refParts[1]
var columnStr = ''
for (; column; column = Math.floor((column - 1) / 26)) {
columnStr = String.fromCharCode(((column - 1) % 26) + 65) + columnStr
}
return columnStr + row
} | [
"function",
"convertR1C1toA1",
"(",
"ref",
")",
"{",
"if",
"(",
"!",
"R1C1",
".",
"test",
"(",
"ref",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"ref",
"}",
"`",
")",
"}",
"var",
"refParts",
"=",
"ref",
".",
"replace",
"(",
"R1C1",
",",
"'$1,$2'",
")",
".",
"split",
"(",
"','",
")",
"var",
"row",
"=",
"refParts",
"[",
"0",
"]",
"var",
"column",
"=",
"refParts",
"[",
"1",
"]",
"var",
"columnStr",
"=",
"''",
"for",
"(",
";",
"column",
";",
"column",
"=",
"Math",
".",
"floor",
"(",
"(",
"column",
"-",
"1",
")",
"/",
"26",
")",
")",
"{",
"columnStr",
"=",
"String",
".",
"fromCharCode",
"(",
"(",
"(",
"column",
"-",
"1",
")",
"%",
"26",
")",
"+",
"65",
")",
"+",
"columnStr",
"}",
"return",
"columnStr",
"+",
"row",
"}"
]
| Convert R1C1 notation to A1 notation
@param {String} ref
@returns {String}
@throws {Error} | [
"Convert",
"R1C1",
"notation",
"to",
"A1",
"notation"
]
| 0f1c9d94bc71632c8f19b52d72632fd5718e4a26 | https://github.com/mike182uk/cellref/blob/0f1c9d94bc71632c8f19b52d72632fd5718e4a26/index.js#L81-L99 |
46,432 | bda-research/gearman-node | lib/gearmanode/worker.js | function (data) {
data = data || '';
var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
Worker.logger.log('debug', 'work data, handle=%s, data=%s', this.handle, data.toString());
jobServer.send(protocol.encodePacket(protocol.PACKET_TYPES.WORK_DATA, [this.handle, data]));
} | javascript | function (data) {
data = data || '';
var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
Worker.logger.log('debug', 'work data, handle=%s, data=%s', this.handle, data.toString());
jobServer.send(protocol.encodePacket(protocol.PACKET_TYPES.WORK_DATA, [this.handle, data]));
} | [
"function",
"(",
"data",
")",
"{",
"data",
"=",
"data",
"||",
"''",
";",
"var",
"jobServer",
"=",
"this",
".",
"clientOrWorker",
".",
"_getJobServerByUid",
"(",
"this",
".",
"jobServerUid",
")",
";",
"Worker",
".",
"logger",
".",
"log",
"(",
"'debug'",
",",
"'work data, handle=%s, data=%s'",
",",
"this",
".",
"handle",
",",
"data",
".",
"toString",
"(",
")",
")",
";",
"jobServer",
".",
"send",
"(",
"protocol",
".",
"encodePacket",
"(",
"protocol",
".",
"PACKET_TYPES",
".",
"WORK_DATA",
",",
"[",
"this",
".",
"handle",
",",
"data",
"]",
")",
")",
";",
"}"
]
| This is sent to update the client with data from a running job.
A worker should use this when it needs to send updates,
send partial results, or flush data during long running jobs.
@method
@memberof Job
@param {string|Buffer} data to be sent to client
@returns {void} nothing | [
"This",
"is",
"sent",
"to",
"update",
"the",
"client",
"with",
"data",
"from",
"a",
"running",
"job",
".",
"A",
"worker",
"should",
"use",
"this",
"when",
"it",
"needs",
"to",
"send",
"updates",
"send",
"partial",
"results",
"or",
"flush",
"data",
"during",
"long",
"running",
"jobs",
"."
]
| f4df581cea7e184b03a20e27db75beff67e54acc | https://github.com/bda-research/gearman-node/blob/f4df581cea7e184b03a20e27db75beff67e54acc/lib/gearmanode/worker.js#L353-L358 |
|
46,433 | bda-research/gearman-node | lib/gearmanode/worker.js | function (packetType, packetData) {
var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
jobServer.send(protocol.encodePacket(packetType, packetData));
if(!this.clientOrWorker.readyReset)// ensure the worker won't exit
jobServer.send(protocol.encodePacket(protocol.PACKET_TYPES.GRAB_JOB));
this.close();
} | javascript | function (packetType, packetData) {
var jobServer = this.clientOrWorker._getJobServerByUid(this.jobServerUid);
jobServer.send(protocol.encodePacket(packetType, packetData));
if(!this.clientOrWorker.readyReset)// ensure the worker won't exit
jobServer.send(protocol.encodePacket(protocol.PACKET_TYPES.GRAB_JOB));
this.close();
} | [
"function",
"(",
"packetType",
",",
"packetData",
")",
"{",
"var",
"jobServer",
"=",
"this",
".",
"clientOrWorker",
".",
"_getJobServerByUid",
"(",
"this",
".",
"jobServerUid",
")",
";",
"jobServer",
".",
"send",
"(",
"protocol",
".",
"encodePacket",
"(",
"packetType",
",",
"packetData",
")",
")",
";",
"if",
"(",
"!",
"this",
".",
"clientOrWorker",
".",
"readyReset",
")",
"// ensure the worker won't exit",
"jobServer",
".",
"send",
"(",
"protocol",
".",
"encodePacket",
"(",
"protocol",
".",
"PACKET_TYPES",
".",
"GRAB_JOB",
")",
")",
";",
"this",
".",
"close",
"(",
")",
";",
"}"
]
| Re-usable helper method to send data to client and close this job.
@method
@access private | [
"Re",
"-",
"usable",
"helper",
"method",
"to",
"send",
"data",
"to",
"client",
"and",
"close",
"this",
"job",
"."
]
| f4df581cea7e184b03a20e27db75beff67e54acc | https://github.com/bda-research/gearman-node/blob/f4df581cea7e184b03a20e27db75beff67e54acc/lib/gearmanode/worker.js#L423-L431 |
|
46,434 | ericnishio/finnish-holidays-js | lib/translator.js | function(english, language) {
if (typeof translations[english] !== 'undefined' && typeof translations[english][language] !== 'undefined') {
return translations[english][language];
} else {
return english;
}
} | javascript | function(english, language) {
if (typeof translations[english] !== 'undefined' && typeof translations[english][language] !== 'undefined') {
return translations[english][language];
} else {
return english;
}
} | [
"function",
"(",
"english",
",",
"language",
")",
"{",
"if",
"(",
"typeof",
"translations",
"[",
"english",
"]",
"!==",
"'undefined'",
"&&",
"typeof",
"translations",
"[",
"english",
"]",
"[",
"language",
"]",
"!==",
"'undefined'",
")",
"{",
"return",
"translations",
"[",
"english",
"]",
"[",
"language",
"]",
";",
"}",
"else",
"{",
"return",
"english",
";",
"}",
"}"
]
| Translates the name of a holiday.
@param {string} english
@param {string} language
@return {string} | [
"Translates",
"the",
"name",
"of",
"a",
"holiday",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/translator.js#L71-L77 |
|
46,435 | souporserious/animation-bus | example/index.js | scrollHandler | function scrollHandler() {
for (let i = 0; i < scrollElements.length; i++) {
animationBus.applyStyles(scrollElements[i])
}
isTicking = false
} | javascript | function scrollHandler() {
for (let i = 0; i < scrollElements.length; i++) {
animationBus.applyStyles(scrollElements[i])
}
isTicking = false
} | [
"function",
"scrollHandler",
"(",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"scrollElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"animationBus",
".",
"applyStyles",
"(",
"scrollElements",
"[",
"i",
"]",
")",
"}",
"isTicking",
"=",
"false",
"}"
]
| Listen for window scroll and apply transforms to elements | [
"Listen",
"for",
"window",
"scroll",
"and",
"apply",
"transforms",
"to",
"elements"
]
| 6b711e937533d427cc1e3505836fb0d88fe14974 | https://github.com/souporserious/animation-bus/blob/6b711e937533d427cc1e3505836fb0d88fe14974/example/index.js#L46-L51 |
46,436 | mpayetta/statsd-newrelic-backend | lib/index.js | function (time, metrics) {
/**
* Iterate over every kind of metric we want to send to new relic
*/
options.dispatchMetrics.forEach(function (metricType) {
var statsdKeysForType = metrics[metricType],
statsdKey,
statsdValue,
dispatchMetric = function (dispatcherType) {
dispatcher[dispatcherType](metricType, statsdKey, statsdValue);
};
for (statsdKey in statsdKeysForType) {
if (statsdKeysForType.hasOwnProperty(statsdKey)) {
statsdValue = metrics[metricType][statsdKey];
options.dispatchers.forEach(dispatchMetric);
}
}
});
} | javascript | function (time, metrics) {
/**
* Iterate over every kind of metric we want to send to new relic
*/
options.dispatchMetrics.forEach(function (metricType) {
var statsdKeysForType = metrics[metricType],
statsdKey,
statsdValue,
dispatchMetric = function (dispatcherType) {
dispatcher[dispatcherType](metricType, statsdKey, statsdValue);
};
for (statsdKey in statsdKeysForType) {
if (statsdKeysForType.hasOwnProperty(statsdKey)) {
statsdValue = metrics[metricType][statsdKey];
options.dispatchers.forEach(dispatchMetric);
}
}
});
} | [
"function",
"(",
"time",
",",
"metrics",
")",
"{",
"/**\n * Iterate over every kind of metric we want to send to new relic\n */",
"options",
".",
"dispatchMetrics",
".",
"forEach",
"(",
"function",
"(",
"metricType",
")",
"{",
"var",
"statsdKeysForType",
"=",
"metrics",
"[",
"metricType",
"]",
",",
"statsdKey",
",",
"statsdValue",
",",
"dispatchMetric",
"=",
"function",
"(",
"dispatcherType",
")",
"{",
"dispatcher",
"[",
"dispatcherType",
"]",
"(",
"metricType",
",",
"statsdKey",
",",
"statsdValue",
")",
";",
"}",
";",
"for",
"(",
"statsdKey",
"in",
"statsdKeysForType",
")",
"{",
"if",
"(",
"statsdKeysForType",
".",
"hasOwnProperty",
"(",
"statsdKey",
")",
")",
"{",
"statsdValue",
"=",
"metrics",
"[",
"metricType",
"]",
"[",
"statsdKey",
"]",
";",
"options",
".",
"dispatchers",
".",
"forEach",
"(",
"dispatchMetric",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Handle the flush event triggered by StatsD.
This handler will read the gauges and counters data and send them to New Relic as Custom Metrics
through the agent API recordMetric.
Unless other names are provided as part of the configuration, the Custom Metrics naming
follows the New Relic suggested convention:
- Custom/[gauge.key.metric]
- Custom/[counter.key.metric]
... | [
"Handle",
"the",
"flush",
"event",
"triggered",
"by",
"StatsD",
".",
"This",
"handler",
"will",
"read",
"the",
"gauges",
"and",
"counters",
"data",
"and",
"send",
"them",
"to",
"New",
"Relic",
"as",
"Custom",
"Metrics",
"through",
"the",
"agent",
"API",
"recordMetric",
"."
]
| 64caaa368d9732c6bab916c91f46492eeb2392ba | https://github.com/mpayetta/statsd-newrelic-backend/blob/64caaa368d9732c6bab916c91f46492eeb2392ba/lib/index.js#L53-L73 |
|
46,437 | atmin/freak | freak.js | mixin | function mixin(target, properties) {
Object.keys(properties).forEach(function(prop) {
target[prop] = properties[prop];
});
} | javascript | function mixin(target, properties) {
Object.keys(properties).forEach(function(prop) {
target[prop] = properties[prop];
});
} | [
"function",
"mixin",
"(",
"target",
",",
"properties",
")",
"{",
"Object",
".",
"keys",
"(",
"properties",
")",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"target",
"[",
"prop",
"]",
"=",
"properties",
"[",
"prop",
"]",
";",
"}",
")",
";",
"}"
]
| Mix properties into target | [
"Mix",
"properties",
"into",
"target"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L11-L15 |
46,438 | atmin/freak | freak.js | off | function off(event, callback) {
if (callback) {
listeners[event].splice(listeners[event].indexOf(callback), 1);
}
else {
listeners[event] = [];
}
} | javascript | function off(event, callback) {
if (callback) {
listeners[event].splice(listeners[event].indexOf(callback), 1);
}
else {
listeners[event] = [];
}
} | [
"function",
"off",
"(",
"event",
",",
"callback",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"listeners",
"[",
"event",
"]",
".",
"splice",
"(",
"listeners",
"[",
"event",
"]",
".",
"indexOf",
"(",
"callback",
")",
",",
"1",
")",
";",
"}",
"else",
"{",
"listeners",
"[",
"event",
"]",
"=",
"[",
"]",
";",
"}",
"}"
]
| Remove all or specified listeners given event and property | [
"Remove",
"all",
"or",
"specified",
"listeners",
"given",
"event",
"and",
"property"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L36-L43 |
46,439 | atmin/freak | freak.js | tracker | function tracker(prop) {
function _tracker(context) {
return function(_prop, _arg) {
context.deps[_prop] = context.deps[_prop] || [];
if (!context.deps[_prop].reduce(function found(prev, curr) {
return prev || (curr[0] === prop);
}, false)) {
context.deps[_prop].push([prop, instance]);
}
return context(_prop, _arg, true);
}
}
var result = _tracker(instance);
construct(result);
result.parent = parent ? _tracker(parent) : null;
result.root = _tracker(root || instance);
return result;
} | javascript | function tracker(prop) {
function _tracker(context) {
return function(_prop, _arg) {
context.deps[_prop] = context.deps[_prop] || [];
if (!context.deps[_prop].reduce(function found(prev, curr) {
return prev || (curr[0] === prop);
}, false)) {
context.deps[_prop].push([prop, instance]);
}
return context(_prop, _arg, true);
}
}
var result = _tracker(instance);
construct(result);
result.parent = parent ? _tracker(parent) : null;
result.root = _tracker(root || instance);
return result;
} | [
"function",
"tracker",
"(",
"prop",
")",
"{",
"function",
"_tracker",
"(",
"context",
")",
"{",
"return",
"function",
"(",
"_prop",
",",
"_arg",
")",
"{",
"context",
".",
"deps",
"[",
"_prop",
"]",
"=",
"context",
".",
"deps",
"[",
"_prop",
"]",
"||",
"[",
"]",
";",
"if",
"(",
"!",
"context",
".",
"deps",
"[",
"_prop",
"]",
".",
"reduce",
"(",
"function",
"found",
"(",
"prev",
",",
"curr",
")",
"{",
"return",
"prev",
"||",
"(",
"curr",
"[",
"0",
"]",
"===",
"prop",
")",
";",
"}",
",",
"false",
")",
")",
"{",
"context",
".",
"deps",
"[",
"_prop",
"]",
".",
"push",
"(",
"[",
"prop",
",",
"instance",
"]",
")",
";",
"}",
"return",
"context",
"(",
"_prop",
",",
"_arg",
",",
"true",
")",
";",
"}",
"}",
"var",
"result",
"=",
"_tracker",
"(",
"instance",
")",
";",
"construct",
"(",
"result",
")",
";",
"result",
".",
"parent",
"=",
"parent",
"?",
"_tracker",
"(",
"parent",
")",
":",
"null",
";",
"result",
".",
"root",
"=",
"_tracker",
"(",
"root",
"||",
"instance",
")",
";",
"return",
"result",
";",
"}"
]
| Proxy the accessor function to record all accessed properties | [
"Proxy",
"the",
"accessor",
"function",
"to",
"record",
"all",
"accessed",
"properties"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L89-L106 |
46,440 | atmin/freak | freak.js | _get | function _get(prop) {
var val = obj[prop];
return cache[prop] = (typeof val === 'function') ?
val.call(tracker(prop)) : val;
} | javascript | function _get(prop) {
var val = obj[prop];
return cache[prop] = (typeof val === 'function') ?
val.call(tracker(prop)) : val;
} | [
"function",
"_get",
"(",
"prop",
")",
"{",
"var",
"val",
"=",
"obj",
"[",
"prop",
"]",
";",
"return",
"cache",
"[",
"prop",
"]",
"=",
"(",
"typeof",
"val",
"===",
"'function'",
")",
"?",
"val",
".",
"call",
"(",
"tracker",
"(",
"prop",
")",
")",
":",
"val",
";",
"}"
]
| Getter for prop | [
"Getter",
"for",
"prop"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L109-L113 |
46,441 | atmin/freak | freak.js | setter | function setter(prop, val) {
var oldVal = _get(prop);
if (typeof obj[prop] === 'function') {
// Computed property setter
obj[prop].call(tracker(prop), val);
}
else {
// Simple property
obj[prop] = val;
}
delete cache[prop];
delete children[prop];
return (oldVal !== val) && trigger('update', prop);
} | javascript | function setter(prop, val) {
var oldVal = _get(prop);
if (typeof obj[prop] === 'function') {
// Computed property setter
obj[prop].call(tracker(prop), val);
}
else {
// Simple property
obj[prop] = val;
}
delete cache[prop];
delete children[prop];
return (oldVal !== val) && trigger('update', prop);
} | [
"function",
"setter",
"(",
"prop",
",",
"val",
")",
"{",
"var",
"oldVal",
"=",
"_get",
"(",
"prop",
")",
";",
"if",
"(",
"typeof",
"obj",
"[",
"prop",
"]",
"===",
"'function'",
")",
"{",
"// Computed property setter",
"obj",
"[",
"prop",
"]",
".",
"call",
"(",
"tracker",
"(",
"prop",
")",
",",
"val",
")",
";",
"}",
"else",
"{",
"// Simple property",
"obj",
"[",
"prop",
"]",
"=",
"val",
";",
"}",
"delete",
"cache",
"[",
"prop",
"]",
";",
"delete",
"children",
"[",
"prop",
"]",
";",
"return",
"(",
"oldVal",
"!==",
"val",
")",
"&&",
"trigger",
"(",
"'update'",
",",
"prop",
")",
";",
"}"
]
| Set prop to val | [
"Set",
"prop",
"to",
"val"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L127-L143 |
46,442 | atmin/freak | freak.js | accessor | function accessor(prop, arg) {
return (arg === undefined) ? getter(prop) : setter(prop, arg);
} | javascript | function accessor(prop, arg) {
return (arg === undefined) ? getter(prop) : setter(prop, arg);
} | [
"function",
"accessor",
"(",
"prop",
",",
"arg",
")",
"{",
"return",
"(",
"arg",
"===",
"undefined",
")",
"?",
"getter",
"(",
"prop",
")",
":",
"setter",
"(",
"prop",
",",
"arg",
")",
";",
"}"
]
| Functional accessor, unify getter and setter | [
"Functional",
"accessor",
"unify",
"getter",
"and",
"setter"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L146-L148 |
46,443 | atmin/freak | freak.js | construct | function construct(target) {
mixin(target, {
values: obj,
parent: parent || null,
root: root || target,
prop: prop === undefined ? null : prop,
// .on(event[, prop], callback)
on: on,
// .off(event[, prop][, callback])
off: off,
// .trigger(event[, prop])
trigger: trigger,
toJSON: toJSON,
// internal: dependency tracking
deps: deps
});
// Wrap mutating array method to update
// state and notify listeners
function wrapMutatingArrayMethod(method, func) {
return function() {
var result = [][method].apply(obj, arguments);
this.len = this.values.length;
cache = {};
children = {};
func.apply(this, arguments);
target.parent.trigger('update', target.prop);
return result;
};
}
// Wrap callback of an array method to
// provide this content to the currently processed item
function proxyArrayMethod(method) {
return function(callback) {
return [][method].apply(
obj,
[function(el, i) {
return callback.apply(target(i), [].slice.call(arguments));
}].concat([].slice.call(arguments, 1))
);
};
}
if (Array.isArray(obj)) {
mixin(target, {
// Function prototype already contains length
// `len` specifies array length
len: obj.length,
pop: wrapMutatingArrayMethod('pop', function() {
trigger('delete', this.len, 1);
}),
push: wrapMutatingArrayMethod('push', function() {
trigger('insert', this.len - 1, 1);
}),
reverse: wrapMutatingArrayMethod('reverse', function() {
trigger('delete', 0, this.len);
trigger('insert', 0, this.len);
}),
shift: wrapMutatingArrayMethod('shift', function() {
trigger('delete', 0, 1);
}),
unshift: wrapMutatingArrayMethod('unshift', function() {
trigger('insert', 0, 1);
}),
sort: wrapMutatingArrayMethod('sort', function() {
trigger('delete', 0, this.len);
trigger('insert', 0, this.len);
}),
splice: wrapMutatingArrayMethod('splice', function() {
if (arguments[1]) {
trigger('delete', arguments[0], arguments[1]);
}
if (arguments.length > 2) {
trigger('insert', arguments[0], arguments.length - 2);
}
})
});
['forEach', 'every', 'some', 'filter', 'map', 'reduce', 'reduceRight']
.forEach(function(method) {
target[method] = proxyArrayMethod(method);
});
}
} | javascript | function construct(target) {
mixin(target, {
values: obj,
parent: parent || null,
root: root || target,
prop: prop === undefined ? null : prop,
// .on(event[, prop], callback)
on: on,
// .off(event[, prop][, callback])
off: off,
// .trigger(event[, prop])
trigger: trigger,
toJSON: toJSON,
// internal: dependency tracking
deps: deps
});
// Wrap mutating array method to update
// state and notify listeners
function wrapMutatingArrayMethod(method, func) {
return function() {
var result = [][method].apply(obj, arguments);
this.len = this.values.length;
cache = {};
children = {};
func.apply(this, arguments);
target.parent.trigger('update', target.prop);
return result;
};
}
// Wrap callback of an array method to
// provide this content to the currently processed item
function proxyArrayMethod(method) {
return function(callback) {
return [][method].apply(
obj,
[function(el, i) {
return callback.apply(target(i), [].slice.call(arguments));
}].concat([].slice.call(arguments, 1))
);
};
}
if (Array.isArray(obj)) {
mixin(target, {
// Function prototype already contains length
// `len` specifies array length
len: obj.length,
pop: wrapMutatingArrayMethod('pop', function() {
trigger('delete', this.len, 1);
}),
push: wrapMutatingArrayMethod('push', function() {
trigger('insert', this.len - 1, 1);
}),
reverse: wrapMutatingArrayMethod('reverse', function() {
trigger('delete', 0, this.len);
trigger('insert', 0, this.len);
}),
shift: wrapMutatingArrayMethod('shift', function() {
trigger('delete', 0, 1);
}),
unshift: wrapMutatingArrayMethod('unshift', function() {
trigger('insert', 0, 1);
}),
sort: wrapMutatingArrayMethod('sort', function() {
trigger('delete', 0, this.len);
trigger('insert', 0, this.len);
}),
splice: wrapMutatingArrayMethod('splice', function() {
if (arguments[1]) {
trigger('delete', arguments[0], arguments[1]);
}
if (arguments.length > 2) {
trigger('insert', arguments[0], arguments.length - 2);
}
})
});
['forEach', 'every', 'some', 'filter', 'map', 'reduce', 'reduceRight']
.forEach(function(method) {
target[method] = proxyArrayMethod(method);
});
}
} | [
"function",
"construct",
"(",
"target",
")",
"{",
"mixin",
"(",
"target",
",",
"{",
"values",
":",
"obj",
",",
"parent",
":",
"parent",
"||",
"null",
",",
"root",
":",
"root",
"||",
"target",
",",
"prop",
":",
"prop",
"===",
"undefined",
"?",
"null",
":",
"prop",
",",
"// .on(event[, prop], callback)",
"on",
":",
"on",
",",
"// .off(event[, prop][, callback])",
"off",
":",
"off",
",",
"// .trigger(event[, prop])",
"trigger",
":",
"trigger",
",",
"toJSON",
":",
"toJSON",
",",
"// internal: dependency tracking",
"deps",
":",
"deps",
"}",
")",
";",
"// Wrap mutating array method to update",
"// state and notify listeners",
"function",
"wrapMutatingArrayMethod",
"(",
"method",
",",
"func",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"result",
"=",
"[",
"]",
"[",
"method",
"]",
".",
"apply",
"(",
"obj",
",",
"arguments",
")",
";",
"this",
".",
"len",
"=",
"this",
".",
"values",
".",
"length",
";",
"cache",
"=",
"{",
"}",
";",
"children",
"=",
"{",
"}",
";",
"func",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"target",
".",
"parent",
".",
"trigger",
"(",
"'update'",
",",
"target",
".",
"prop",
")",
";",
"return",
"result",
";",
"}",
";",
"}",
"// Wrap callback of an array method to",
"// provide this content to the currently processed item",
"function",
"proxyArrayMethod",
"(",
"method",
")",
"{",
"return",
"function",
"(",
"callback",
")",
"{",
"return",
"[",
"]",
"[",
"method",
"]",
".",
"apply",
"(",
"obj",
",",
"[",
"function",
"(",
"el",
",",
"i",
")",
"{",
"return",
"callback",
".",
"apply",
"(",
"target",
"(",
"i",
")",
",",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
";",
"}",
"]",
".",
"concat",
"(",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
")",
")",
";",
"}",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"mixin",
"(",
"target",
",",
"{",
"// Function prototype already contains length",
"// `len` specifies array length",
"len",
":",
"obj",
".",
"length",
",",
"pop",
":",
"wrapMutatingArrayMethod",
"(",
"'pop'",
",",
"function",
"(",
")",
"{",
"trigger",
"(",
"'delete'",
",",
"this",
".",
"len",
",",
"1",
")",
";",
"}",
")",
",",
"push",
":",
"wrapMutatingArrayMethod",
"(",
"'push'",
",",
"function",
"(",
")",
"{",
"trigger",
"(",
"'insert'",
",",
"this",
".",
"len",
"-",
"1",
",",
"1",
")",
";",
"}",
")",
",",
"reverse",
":",
"wrapMutatingArrayMethod",
"(",
"'reverse'",
",",
"function",
"(",
")",
"{",
"trigger",
"(",
"'delete'",
",",
"0",
",",
"this",
".",
"len",
")",
";",
"trigger",
"(",
"'insert'",
",",
"0",
",",
"this",
".",
"len",
")",
";",
"}",
")",
",",
"shift",
":",
"wrapMutatingArrayMethod",
"(",
"'shift'",
",",
"function",
"(",
")",
"{",
"trigger",
"(",
"'delete'",
",",
"0",
",",
"1",
")",
";",
"}",
")",
",",
"unshift",
":",
"wrapMutatingArrayMethod",
"(",
"'unshift'",
",",
"function",
"(",
")",
"{",
"trigger",
"(",
"'insert'",
",",
"0",
",",
"1",
")",
";",
"}",
")",
",",
"sort",
":",
"wrapMutatingArrayMethod",
"(",
"'sort'",
",",
"function",
"(",
")",
"{",
"trigger",
"(",
"'delete'",
",",
"0",
",",
"this",
".",
"len",
")",
";",
"trigger",
"(",
"'insert'",
",",
"0",
",",
"this",
".",
"len",
")",
";",
"}",
")",
",",
"splice",
":",
"wrapMutatingArrayMethod",
"(",
"'splice'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"arguments",
"[",
"1",
"]",
")",
"{",
"trigger",
"(",
"'delete'",
",",
"arguments",
"[",
"0",
"]",
",",
"arguments",
"[",
"1",
"]",
")",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"2",
")",
"{",
"trigger",
"(",
"'insert'",
",",
"arguments",
"[",
"0",
"]",
",",
"arguments",
".",
"length",
"-",
"2",
")",
";",
"}",
"}",
")",
"}",
")",
";",
"[",
"'forEach'",
",",
"'every'",
",",
"'some'",
",",
"'filter'",
",",
"'map'",
",",
"'reduce'",
",",
"'reduceRight'",
"]",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"target",
"[",
"method",
"]",
"=",
"proxyArrayMethod",
"(",
"method",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Attach instance members | [
"Attach",
"instance",
"members"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L151-L243 |
46,444 | atmin/freak | freak.js | wrapMutatingArrayMethod | function wrapMutatingArrayMethod(method, func) {
return function() {
var result = [][method].apply(obj, arguments);
this.len = this.values.length;
cache = {};
children = {};
func.apply(this, arguments);
target.parent.trigger('update', target.prop);
return result;
};
} | javascript | function wrapMutatingArrayMethod(method, func) {
return function() {
var result = [][method].apply(obj, arguments);
this.len = this.values.length;
cache = {};
children = {};
func.apply(this, arguments);
target.parent.trigger('update', target.prop);
return result;
};
} | [
"function",
"wrapMutatingArrayMethod",
"(",
"method",
",",
"func",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"result",
"=",
"[",
"]",
"[",
"method",
"]",
".",
"apply",
"(",
"obj",
",",
"arguments",
")",
";",
"this",
".",
"len",
"=",
"this",
".",
"values",
".",
"length",
";",
"cache",
"=",
"{",
"}",
";",
"children",
"=",
"{",
"}",
";",
"func",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"target",
".",
"parent",
".",
"trigger",
"(",
"'update'",
",",
"target",
".",
"prop",
")",
";",
"return",
"result",
";",
"}",
";",
"}"
]
| Wrap mutating array method to update state and notify listeners | [
"Wrap",
"mutating",
"array",
"method",
"to",
"update",
"state",
"and",
"notify",
"listeners"
]
| c32494ff1ab60aac2952a998d695023a533b8066 | https://github.com/atmin/freak/blob/c32494ff1ab60aac2952a998d695023a533b8066/freak.js#L170-L180 |
46,445 | rkirsling/formula-parser | formulaParser.js | matchOperator | function matchOperator(str, operatorList) {
return operatorList.reduce((match, operator) => {
return match ||
(str.startsWith(operator.symbol) ? operator : null);
}, null);
} | javascript | function matchOperator(str, operatorList) {
return operatorList.reduce((match, operator) => {
return match ||
(str.startsWith(operator.symbol) ? operator : null);
}, null);
} | [
"function",
"matchOperator",
"(",
"str",
",",
"operatorList",
")",
"{",
"return",
"operatorList",
".",
"reduce",
"(",
"(",
"match",
",",
"operator",
")",
"=>",
"{",
"return",
"match",
"||",
"(",
"str",
".",
"startsWith",
"(",
"operator",
".",
"symbol",
")",
"?",
"operator",
":",
"null",
")",
";",
"}",
",",
"null",
")",
";",
"}"
]
| Attempts to match a given list of operators against the head of a given string.
Returns the first match if successful, otherwise null.
@private
@static
@param {string} str - a string to match against
@param {Object[]} operatorList - an array of operator definitions, sorted by longest symbol
@returns {?Object} | [
"Attempts",
"to",
"match",
"a",
"given",
"list",
"of",
"operators",
"against",
"the",
"head",
"of",
"a",
"given",
"string",
".",
"Returns",
"the",
"first",
"match",
"if",
"successful",
"otherwise",
"null",
"."
]
| 8f792a333339231f8bfc38a315b777bdd7207ef2 | https://github.com/rkirsling/formula-parser/blob/8f792a333339231f8bfc38a315b777bdd7207ef2/formulaParser.js#L28-L33 |
46,446 | rkirsling/formula-parser | formulaParser.js | _parseParenthesizedSubformula | function _parseParenthesizedSubformula(self, currentString) {
if (currentString.charAt(0) !== '(') {
return null;
}
const parsedSubformula = _parseFormula(self, sliceSymbol(currentString, '('), MIN_PRECEDENCE);
if (parsedSubformula.remainder.charAt(0) !== ')') {
throw new SyntaxError('Invalid formula! Found unmatched parenthesis.');
}
return {
json: parsedSubformula.json,
remainder: sliceSymbol(parsedSubformula.remainder, ')')
};
} | javascript | function _parseParenthesizedSubformula(self, currentString) {
if (currentString.charAt(0) !== '(') {
return null;
}
const parsedSubformula = _parseFormula(self, sliceSymbol(currentString, '('), MIN_PRECEDENCE);
if (parsedSubformula.remainder.charAt(0) !== ')') {
throw new SyntaxError('Invalid formula! Found unmatched parenthesis.');
}
return {
json: parsedSubformula.json,
remainder: sliceSymbol(parsedSubformula.remainder, ')')
};
} | [
"function",
"_parseParenthesizedSubformula",
"(",
"self",
",",
"currentString",
")",
"{",
"if",
"(",
"currentString",
".",
"charAt",
"(",
"0",
")",
"!==",
"'('",
")",
"{",
"return",
"null",
";",
"}",
"const",
"parsedSubformula",
"=",
"_parseFormula",
"(",
"self",
",",
"sliceSymbol",
"(",
"currentString",
",",
"'('",
")",
",",
"MIN_PRECEDENCE",
")",
";",
"if",
"(",
"parsedSubformula",
".",
"remainder",
".",
"charAt",
"(",
"0",
")",
"!==",
"')'",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Invalid formula! Found unmatched parenthesis.'",
")",
";",
"}",
"return",
"{",
"json",
":",
"parsedSubformula",
".",
"json",
",",
"remainder",
":",
"sliceSymbol",
"(",
"parsedSubformula",
".",
"remainder",
",",
"')'",
")",
"}",
";",
"}"
]
| Attempts to parse a parenthesized subformula at the head of a given string.
Returns an AST node and string remainder if successful, otherwise null.
@private
@param {FormulaParser} self
@param {string} currentString - remainder of input string left to parse
@returns {?Object} | [
"Attempts",
"to",
"parse",
"a",
"parenthesized",
"subformula",
"at",
"the",
"head",
"of",
"a",
"given",
"string",
".",
"Returns",
"an",
"AST",
"node",
"and",
"string",
"remainder",
"if",
"successful",
"otherwise",
"null",
"."
]
| 8f792a333339231f8bfc38a315b777bdd7207ef2 | https://github.com/rkirsling/formula-parser/blob/8f792a333339231f8bfc38a315b777bdd7207ef2/formulaParser.js#L65-L79 |
46,447 | rkirsling/formula-parser | formulaParser.js | _parseUnarySubformula | function _parseUnarySubformula(self, currentString) {
const unary = matchOperator(currentString, self.unaries);
if (!unary) {
return null;
}
const parsedSubformula = _parseFormula(self, sliceSymbol(currentString, unary.symbol), unary.precedence);
return {
json: { [unary.key]: parsedSubformula.json },
remainder: parsedSubformula.remainder
};
} | javascript | function _parseUnarySubformula(self, currentString) {
const unary = matchOperator(currentString, self.unaries);
if (!unary) {
return null;
}
const parsedSubformula = _parseFormula(self, sliceSymbol(currentString, unary.symbol), unary.precedence);
return {
json: { [unary.key]: parsedSubformula.json },
remainder: parsedSubformula.remainder
};
} | [
"function",
"_parseUnarySubformula",
"(",
"self",
",",
"currentString",
")",
"{",
"const",
"unary",
"=",
"matchOperator",
"(",
"currentString",
",",
"self",
".",
"unaries",
")",
";",
"if",
"(",
"!",
"unary",
")",
"{",
"return",
"null",
";",
"}",
"const",
"parsedSubformula",
"=",
"_parseFormula",
"(",
"self",
",",
"sliceSymbol",
"(",
"currentString",
",",
"unary",
".",
"symbol",
")",
",",
"unary",
".",
"precedence",
")",
";",
"return",
"{",
"json",
":",
"{",
"[",
"unary",
".",
"key",
"]",
":",
"parsedSubformula",
".",
"json",
"}",
",",
"remainder",
":",
"parsedSubformula",
".",
"remainder",
"}",
";",
"}"
]
| Attempts to parse a unary subformula at the head of a given string.
Returns an AST node and string remainder if successful, otherwise null.
@private
@param {FormulaParser} self
@param {string} currentString - remainder of input string left to parse
@returns {?Object} | [
"Attempts",
"to",
"parse",
"a",
"unary",
"subformula",
"at",
"the",
"head",
"of",
"a",
"given",
"string",
".",
"Returns",
"an",
"AST",
"node",
"and",
"string",
"remainder",
"if",
"successful",
"otherwise",
"null",
"."
]
| 8f792a333339231f8bfc38a315b777bdd7207ef2 | https://github.com/rkirsling/formula-parser/blob/8f792a333339231f8bfc38a315b777bdd7207ef2/formulaParser.js#L90-L102 |
46,448 | rkirsling/formula-parser | formulaParser.js | _parseBinarySubformula | function _parseBinarySubformula(self, currentString, currentPrecedence, leftOperandJSON) {
const binary = matchOperator(currentString, self.binaries);
if (!binary || binary.precedence < currentPrecedence) {
return null;
}
const nextPrecedence = binary.precedence + (binary.associativity === 'left');
const parsedRightOperand = _parseFormula(self, sliceSymbol(currentString, binary.symbol), nextPrecedence);
return {
json: { [binary.key]: [leftOperandJSON, parsedRightOperand.json] },
remainder: parsedRightOperand.remainder
};
} | javascript | function _parseBinarySubformula(self, currentString, currentPrecedence, leftOperandJSON) {
const binary = matchOperator(currentString, self.binaries);
if (!binary || binary.precedence < currentPrecedence) {
return null;
}
const nextPrecedence = binary.precedence + (binary.associativity === 'left');
const parsedRightOperand = _parseFormula(self, sliceSymbol(currentString, binary.symbol), nextPrecedence);
return {
json: { [binary.key]: [leftOperandJSON, parsedRightOperand.json] },
remainder: parsedRightOperand.remainder
};
} | [
"function",
"_parseBinarySubformula",
"(",
"self",
",",
"currentString",
",",
"currentPrecedence",
",",
"leftOperandJSON",
")",
"{",
"const",
"binary",
"=",
"matchOperator",
"(",
"currentString",
",",
"self",
".",
"binaries",
")",
";",
"if",
"(",
"!",
"binary",
"||",
"binary",
".",
"precedence",
"<",
"currentPrecedence",
")",
"{",
"return",
"null",
";",
"}",
"const",
"nextPrecedence",
"=",
"binary",
".",
"precedence",
"+",
"(",
"binary",
".",
"associativity",
"===",
"'left'",
")",
";",
"const",
"parsedRightOperand",
"=",
"_parseFormula",
"(",
"self",
",",
"sliceSymbol",
"(",
"currentString",
",",
"binary",
".",
"symbol",
")",
",",
"nextPrecedence",
")",
";",
"return",
"{",
"json",
":",
"{",
"[",
"binary",
".",
"key",
"]",
":",
"[",
"leftOperandJSON",
",",
"parsedRightOperand",
".",
"json",
"]",
"}",
",",
"remainder",
":",
"parsedRightOperand",
".",
"remainder",
"}",
";",
"}"
]
| Attempts to parse a binary subformula at the head of a given string,
given a lower precedence bound and an AST node to be used as a left operand.
Returns an AST node and string remainder if successful, otherwise null.
@private
@param {FormulaParser} self
@param {string} currentString - remainder of input string left to parse
@param {number} currentPrecedence - lowest binary precedence allowable at current parse stage
@param {Object} leftOperandJSON - AST node for already-parsed left operand
@returns {?Object} | [
"Attempts",
"to",
"parse",
"a",
"binary",
"subformula",
"at",
"the",
"head",
"of",
"a",
"given",
"string",
"given",
"a",
"lower",
"precedence",
"bound",
"and",
"an",
"AST",
"node",
"to",
"be",
"used",
"as",
"a",
"left",
"operand",
".",
"Returns",
"an",
"AST",
"node",
"and",
"string",
"remainder",
"if",
"successful",
"otherwise",
"null",
"."
]
| 8f792a333339231f8bfc38a315b777bdd7207ef2 | https://github.com/rkirsling/formula-parser/blob/8f792a333339231f8bfc38a315b777bdd7207ef2/formulaParser.js#L116-L129 |
46,449 | chrahunt/tagpro-navmesh | src/partition.js | convertPolyToP2TPoly | function convertPolyToP2TPoly(poly) {
return poly.points.map(function(p) {
return new poly2tri.Point(p.x, p.y);
});
} | javascript | function convertPolyToP2TPoly(poly) {
return poly.points.map(function(p) {
return new poly2tri.Point(p.x, p.y);
});
} | [
"function",
"convertPolyToP2TPoly",
"(",
"poly",
")",
"{",
"return",
"poly",
".",
"points",
".",
"map",
"(",
"function",
"(",
"p",
")",
"{",
"return",
"new",
"poly2tri",
".",
"Point",
"(",
"p",
".",
"x",
",",
"p",
".",
"y",
")",
";",
"}",
")",
";",
"}"
]
| A polygon for use with poly2tri.
@private
@typedef P2TPoly
@type {Array.<P2TPoint>}
Convert a polygon into format required by poly2tri.
@private
@param {Poly} poly - The polygon to convert.
@return {P2TPoly} - The converted polygon. | [
"A",
"polygon",
"for",
"use",
"with",
"poly2tri",
"."
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/partition.js#L33-L37 |
46,450 | chrahunt/tagpro-navmesh | src/partition.js | separatePolys | function separatePolys(polys, offset) {
offset = offset || 1;
var discovered = {};
var dupes = {};
// Offset to use in calculation.
// Find duplicates.
for (var s1 = 0; s1 < polys.length; s1++) {
var poly = polys[s1];
for (var i = 0; i < poly.numpoints; i++) {
var point = poly.points[i].toString();
if (!discovered.hasOwnProperty(point)) {
discovered[point] = true;
} else {
dupes[point] = true;
}
}
}
// Get duplicate points.
var dupe_points = [];
var dupe;
for (var s1 = 0; s1 < polys.length; s1++) {
var poly = polys[s1];
for (var i = 0; i < poly.numpoints; i++) {
var point = poly.points[i];
if (dupes.hasOwnProperty(point.toString())) {
dupe = [point, i, poly];
dupe_points.push(dupe);
}
}
}
// Sort elements in descending order based on their indices to
// prevent future indices from becoming invalid when changes are made.
dupe_points.sort(function(a, b) {
return b[1] - a[1]
});
// Edit duplicates.
var prev, next, point, index, p1, p2;
dupe_points.forEach(function(e, i, ary) {
point = e[0], index = e[1], poly = e[2];
prev = poly.points[poly.getPrevI(index)];
next = poly.points[poly.getNextI(index)];
p1 = point.add(prev.sub(point).normalize().mul(offset));
p2 = point.add(next.sub(point).normalize().mul(offset));
// Insert new points.
poly.points.splice(index, 1, p1, p2);
poly.update();
});
} | javascript | function separatePolys(polys, offset) {
offset = offset || 1;
var discovered = {};
var dupes = {};
// Offset to use in calculation.
// Find duplicates.
for (var s1 = 0; s1 < polys.length; s1++) {
var poly = polys[s1];
for (var i = 0; i < poly.numpoints; i++) {
var point = poly.points[i].toString();
if (!discovered.hasOwnProperty(point)) {
discovered[point] = true;
} else {
dupes[point] = true;
}
}
}
// Get duplicate points.
var dupe_points = [];
var dupe;
for (var s1 = 0; s1 < polys.length; s1++) {
var poly = polys[s1];
for (var i = 0; i < poly.numpoints; i++) {
var point = poly.points[i];
if (dupes.hasOwnProperty(point.toString())) {
dupe = [point, i, poly];
dupe_points.push(dupe);
}
}
}
// Sort elements in descending order based on their indices to
// prevent future indices from becoming invalid when changes are made.
dupe_points.sort(function(a, b) {
return b[1] - a[1]
});
// Edit duplicates.
var prev, next, point, index, p1, p2;
dupe_points.forEach(function(e, i, ary) {
point = e[0], index = e[1], poly = e[2];
prev = poly.points[poly.getPrevI(index)];
next = poly.points[poly.getNextI(index)];
p1 = point.add(prev.sub(point).normalize().mul(offset));
p2 = point.add(next.sub(point).normalize().mul(offset));
// Insert new points.
poly.points.splice(index, 1, p1, p2);
poly.update();
});
} | [
"function",
"separatePolys",
"(",
"polys",
",",
"offset",
")",
"{",
"offset",
"=",
"offset",
"||",
"1",
";",
"var",
"discovered",
"=",
"{",
"}",
";",
"var",
"dupes",
"=",
"{",
"}",
";",
"// Offset to use in calculation.",
"// Find duplicates.",
"for",
"(",
"var",
"s1",
"=",
"0",
";",
"s1",
"<",
"polys",
".",
"length",
";",
"s1",
"++",
")",
"{",
"var",
"poly",
"=",
"polys",
"[",
"s1",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"poly",
".",
"numpoints",
";",
"i",
"++",
")",
"{",
"var",
"point",
"=",
"poly",
".",
"points",
"[",
"i",
"]",
".",
"toString",
"(",
")",
";",
"if",
"(",
"!",
"discovered",
".",
"hasOwnProperty",
"(",
"point",
")",
")",
"{",
"discovered",
"[",
"point",
"]",
"=",
"true",
";",
"}",
"else",
"{",
"dupes",
"[",
"point",
"]",
"=",
"true",
";",
"}",
"}",
"}",
"// Get duplicate points.",
"var",
"dupe_points",
"=",
"[",
"]",
";",
"var",
"dupe",
";",
"for",
"(",
"var",
"s1",
"=",
"0",
";",
"s1",
"<",
"polys",
".",
"length",
";",
"s1",
"++",
")",
"{",
"var",
"poly",
"=",
"polys",
"[",
"s1",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"poly",
".",
"numpoints",
";",
"i",
"++",
")",
"{",
"var",
"point",
"=",
"poly",
".",
"points",
"[",
"i",
"]",
";",
"if",
"(",
"dupes",
".",
"hasOwnProperty",
"(",
"point",
".",
"toString",
"(",
")",
")",
")",
"{",
"dupe",
"=",
"[",
"point",
",",
"i",
",",
"poly",
"]",
";",
"dupe_points",
".",
"push",
"(",
"dupe",
")",
";",
"}",
"}",
"}",
"// Sort elements in descending order based on their indices to",
"// prevent future indices from becoming invalid when changes are made.",
"dupe_points",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"b",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"}",
")",
";",
"// Edit duplicates.",
"var",
"prev",
",",
"next",
",",
"point",
",",
"index",
",",
"p1",
",",
"p2",
";",
"dupe_points",
".",
"forEach",
"(",
"function",
"(",
"e",
",",
"i",
",",
"ary",
")",
"{",
"point",
"=",
"e",
"[",
"0",
"]",
",",
"index",
"=",
"e",
"[",
"1",
"]",
",",
"poly",
"=",
"e",
"[",
"2",
"]",
";",
"prev",
"=",
"poly",
".",
"points",
"[",
"poly",
".",
"getPrevI",
"(",
"index",
")",
"]",
";",
"next",
"=",
"poly",
".",
"points",
"[",
"poly",
".",
"getNextI",
"(",
"index",
")",
"]",
";",
"p1",
"=",
"point",
".",
"add",
"(",
"prev",
".",
"sub",
"(",
"point",
")",
".",
"normalize",
"(",
")",
".",
"mul",
"(",
"offset",
")",
")",
";",
"p2",
"=",
"point",
".",
"add",
"(",
"next",
".",
"sub",
"(",
"point",
")",
".",
"normalize",
"(",
")",
".",
"mul",
"(",
"offset",
")",
")",
";",
"// Insert new points.",
"poly",
".",
"points",
".",
"splice",
"(",
"index",
",",
"1",
",",
"p1",
",",
"p2",
")",
";",
"poly",
".",
"update",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Takes an array of polygons that overlap themselves and others
at discrete corner points and separate those overlapping corners
slightly so the polygons are suitable for triangulation by
poly2tri.js. This changes the Poly objects in the array.
@private
@param {Array.<Poly>} polys - The polygons to separate.
@param {number} [offset=1] - The number of units the vertices
should be moved away from each other. | [
"Takes",
"an",
"array",
"of",
"polygons",
"that",
"overlap",
"themselves",
"and",
"others",
"at",
"discrete",
"corner",
"points",
"and",
"separate",
"those",
"overlapping",
"corners",
"slightly",
"so",
"the",
"polygons",
"are",
"suitable",
"for",
"triangulation",
"by",
"poly2tri",
".",
"js",
".",
"This",
"changes",
"the",
"Poly",
"objects",
"in",
"the",
"array",
"."
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/partition.js#L69-L118 |
46,451 | ericnishio/finnish-holidays-js | lib/calendar.js | function(count, includeWeekends) {
initialize();
count = count || 3;
includeWeekends = includeWeekends || false;
var self = this;
var holidays = [];
if (count > self.MAX_HOLIDAYS) {
throw Error('Cannot request more than {MAX_HOLIDAYS} holidays at once.'.replace('{MAX HOLIDAYS}', self.MAX_HOLIDAYS));
}
/**
* Collects holidays.
*/
function collectHolidays() {
if (typeof self.year.holidays[self.m] !== 'undefined' && typeof self.year.holidays[self.m] !== 'undefined') {
self.year.holidays[self.m].forEach(function(holiday) {
if (holidays.length < count && holiday.day >= self.d) {
holidays.push(holiday);
}
});
}
}
while (holidays.length < count) {
if (!includeWeekends) {
self.year.discardWeekends();
}
collectHolidays();
if (holidays.length < count) {
nextMonth();
}
}
return holidays;
} | javascript | function(count, includeWeekends) {
initialize();
count = count || 3;
includeWeekends = includeWeekends || false;
var self = this;
var holidays = [];
if (count > self.MAX_HOLIDAYS) {
throw Error('Cannot request more than {MAX_HOLIDAYS} holidays at once.'.replace('{MAX HOLIDAYS}', self.MAX_HOLIDAYS));
}
/**
* Collects holidays.
*/
function collectHolidays() {
if (typeof self.year.holidays[self.m] !== 'undefined' && typeof self.year.holidays[self.m] !== 'undefined') {
self.year.holidays[self.m].forEach(function(holiday) {
if (holidays.length < count && holiday.day >= self.d) {
holidays.push(holiday);
}
});
}
}
while (holidays.length < count) {
if (!includeWeekends) {
self.year.discardWeekends();
}
collectHolidays();
if (holidays.length < count) {
nextMonth();
}
}
return holidays;
} | [
"function",
"(",
"count",
",",
"includeWeekends",
")",
"{",
"initialize",
"(",
")",
";",
"count",
"=",
"count",
"||",
"3",
";",
"includeWeekends",
"=",
"includeWeekends",
"||",
"false",
";",
"var",
"self",
"=",
"this",
";",
"var",
"holidays",
"=",
"[",
"]",
";",
"if",
"(",
"count",
">",
"self",
".",
"MAX_HOLIDAYS",
")",
"{",
"throw",
"Error",
"(",
"'Cannot request more than {MAX_HOLIDAYS} holidays at once.'",
".",
"replace",
"(",
"'{MAX HOLIDAYS}'",
",",
"self",
".",
"MAX_HOLIDAYS",
")",
")",
";",
"}",
"/**\n * Collects holidays.\n */",
"function",
"collectHolidays",
"(",
")",
"{",
"if",
"(",
"typeof",
"self",
".",
"year",
".",
"holidays",
"[",
"self",
".",
"m",
"]",
"!==",
"'undefined'",
"&&",
"typeof",
"self",
".",
"year",
".",
"holidays",
"[",
"self",
".",
"m",
"]",
"!==",
"'undefined'",
")",
"{",
"self",
".",
"year",
".",
"holidays",
"[",
"self",
".",
"m",
"]",
".",
"forEach",
"(",
"function",
"(",
"holiday",
")",
"{",
"if",
"(",
"holidays",
".",
"length",
"<",
"count",
"&&",
"holiday",
".",
"day",
">=",
"self",
".",
"d",
")",
"{",
"holidays",
".",
"push",
"(",
"holiday",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"while",
"(",
"holidays",
".",
"length",
"<",
"count",
")",
"{",
"if",
"(",
"!",
"includeWeekends",
")",
"{",
"self",
".",
"year",
".",
"discardWeekends",
"(",
")",
";",
"}",
"collectHolidays",
"(",
")",
";",
"if",
"(",
"holidays",
".",
"length",
"<",
"count",
")",
"{",
"nextMonth",
"(",
")",
";",
"}",
"}",
"return",
"holidays",
";",
"}"
]
| Returns the next holidays.
@param {number} [count] number of holidays to list (default: 3)
@param {boolean} [includeWeekends] include holidays falling on a weekend (default: false)
@return {Array} | [
"Returns",
"the",
"next",
"holidays",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/calendar.js#L13-L52 |
|
46,452 | ericnishio/finnish-holidays-js | lib/calendar.js | collectHolidays | function collectHolidays() {
if (typeof self.year.holidays[self.m] !== 'undefined' && typeof self.year.holidays[self.m] !== 'undefined') {
self.year.holidays[self.m].forEach(function(holiday) {
if (holidays.length < count && holiday.day >= self.d) {
holidays.push(holiday);
}
});
}
} | javascript | function collectHolidays() {
if (typeof self.year.holidays[self.m] !== 'undefined' && typeof self.year.holidays[self.m] !== 'undefined') {
self.year.holidays[self.m].forEach(function(holiday) {
if (holidays.length < count && holiday.day >= self.d) {
holidays.push(holiday);
}
});
}
} | [
"function",
"collectHolidays",
"(",
")",
"{",
"if",
"(",
"typeof",
"self",
".",
"year",
".",
"holidays",
"[",
"self",
".",
"m",
"]",
"!==",
"'undefined'",
"&&",
"typeof",
"self",
".",
"year",
".",
"holidays",
"[",
"self",
".",
"m",
"]",
"!==",
"'undefined'",
")",
"{",
"self",
".",
"year",
".",
"holidays",
"[",
"self",
".",
"m",
"]",
".",
"forEach",
"(",
"function",
"(",
"holiday",
")",
"{",
"if",
"(",
"holidays",
".",
"length",
"<",
"count",
"&&",
"holiday",
".",
"day",
">=",
"self",
".",
"d",
")",
"{",
"holidays",
".",
"push",
"(",
"holiday",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Collects holidays. | [
"Collects",
"holidays",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/calendar.js#L29-L37 |
46,453 | ericnishio/finnish-holidays-js | lib/calendar.js | function(year, includeWeekends) {
initialize(year);
includeWeekends = includeWeekends || false;
var self = this;
var holidays = [];
if (!includeWeekends) {
self.year.discardWeekends();
}
Object.keys(self.year.holidays).forEach(function(month) {
self.year.holidays[month].forEach(function(holiday) {
holidays.push(holiday);
});
});
return holidays;
} | javascript | function(year, includeWeekends) {
initialize(year);
includeWeekends = includeWeekends || false;
var self = this;
var holidays = [];
if (!includeWeekends) {
self.year.discardWeekends();
}
Object.keys(self.year.holidays).forEach(function(month) {
self.year.holidays[month].forEach(function(holiday) {
holidays.push(holiday);
});
});
return holidays;
} | [
"function",
"(",
"year",
",",
"includeWeekends",
")",
"{",
"initialize",
"(",
"year",
")",
";",
"includeWeekends",
"=",
"includeWeekends",
"||",
"false",
";",
"var",
"self",
"=",
"this",
";",
"var",
"holidays",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"includeWeekends",
")",
"{",
"self",
".",
"year",
".",
"discardWeekends",
"(",
")",
";",
"}",
"Object",
".",
"keys",
"(",
"self",
".",
"year",
".",
"holidays",
")",
".",
"forEach",
"(",
"function",
"(",
"month",
")",
"{",
"self",
".",
"year",
".",
"holidays",
"[",
"month",
"]",
".",
"forEach",
"(",
"function",
"(",
"holiday",
")",
"{",
"holidays",
".",
"push",
"(",
"holiday",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"holidays",
";",
"}"
]
| Returns holidays by year.
@param {number} year
@param {boolean} [includeWeekends] include holidays falling on a weekend (default: false)
@return {Array} | [
"Returns",
"holidays",
"by",
"year",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/calendar.js#L60-L79 |
|
46,454 | ericnishio/finnish-holidays-js | lib/calendar.js | function(month, year, includeWeekends) {
initialize(year, month);
includeWeekends = includeWeekends || false;
if (!month || !year) {
throw Error('Month or year missing.');
}
var self = this;
var holidays = [];
if (!includeWeekends) {
self.year.discardWeekends();
}
if (typeof self.year.holidays[month] !== 'undefined') {
self.year.holidays[month].forEach(function(holiday) {
holidays.push(holiday);
});
}
return holidays;
} | javascript | function(month, year, includeWeekends) {
initialize(year, month);
includeWeekends = includeWeekends || false;
if (!month || !year) {
throw Error('Month or year missing.');
}
var self = this;
var holidays = [];
if (!includeWeekends) {
self.year.discardWeekends();
}
if (typeof self.year.holidays[month] !== 'undefined') {
self.year.holidays[month].forEach(function(holiday) {
holidays.push(holiday);
});
}
return holidays;
} | [
"function",
"(",
"month",
",",
"year",
",",
"includeWeekends",
")",
"{",
"initialize",
"(",
"year",
",",
"month",
")",
";",
"includeWeekends",
"=",
"includeWeekends",
"||",
"false",
";",
"if",
"(",
"!",
"month",
"||",
"!",
"year",
")",
"{",
"throw",
"Error",
"(",
"'Month or year missing.'",
")",
";",
"}",
"var",
"self",
"=",
"this",
";",
"var",
"holidays",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"includeWeekends",
")",
"{",
"self",
".",
"year",
".",
"discardWeekends",
"(",
")",
";",
"}",
"if",
"(",
"typeof",
"self",
".",
"year",
".",
"holidays",
"[",
"month",
"]",
"!==",
"'undefined'",
")",
"{",
"self",
".",
"year",
".",
"holidays",
"[",
"month",
"]",
".",
"forEach",
"(",
"function",
"(",
"holiday",
")",
"{",
"holidays",
".",
"push",
"(",
"holiday",
")",
";",
"}",
")",
";",
"}",
"return",
"holidays",
";",
"}"
]
| Returns holidays by month and year.
@param {number} month
@param {number} year
@param {boolean} [includeWeekends] include holidays falling on a weekend (default: false) | [
"Returns",
"holidays",
"by",
"month",
"and",
"year",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/calendar.js#L87-L110 |
|
46,455 | ericnishio/finnish-holidays-js | lib/calendar.js | initialize | function initialize(y, m, d) {
var today = dateUtils.today();
var thisDay = dateUtils.getDay(today);
var thisMonth = dateUtils.getMonth(today);
var thisYear = dateUtils.getYear(today);
calendar.y = y || thisYear;
calendar.m = m || thisMonth;
calendar.d = d || thisDay;
calendar.year = yearFactory.get(calendar.y);
} | javascript | function initialize(y, m, d) {
var today = dateUtils.today();
var thisDay = dateUtils.getDay(today);
var thisMonth = dateUtils.getMonth(today);
var thisYear = dateUtils.getYear(today);
calendar.y = y || thisYear;
calendar.m = m || thisMonth;
calendar.d = d || thisDay;
calendar.year = yearFactory.get(calendar.y);
} | [
"function",
"initialize",
"(",
"y",
",",
"m",
",",
"d",
")",
"{",
"var",
"today",
"=",
"dateUtils",
".",
"today",
"(",
")",
";",
"var",
"thisDay",
"=",
"dateUtils",
".",
"getDay",
"(",
"today",
")",
";",
"var",
"thisMonth",
"=",
"dateUtils",
".",
"getMonth",
"(",
"today",
")",
";",
"var",
"thisYear",
"=",
"dateUtils",
".",
"getYear",
"(",
"today",
")",
";",
"calendar",
".",
"y",
"=",
"y",
"||",
"thisYear",
";",
"calendar",
".",
"m",
"=",
"m",
"||",
"thisMonth",
";",
"calendar",
".",
"d",
"=",
"d",
"||",
"thisDay",
";",
"calendar",
".",
"year",
"=",
"yearFactory",
".",
"get",
"(",
"calendar",
".",
"y",
")",
";",
"}"
]
| Initializes the calendar.
@param {number} [y] year (default: this year)
@param {number} [m] month (default: this month)
@param {number} [d] day (default: this day)
@private | [
"Initializes",
"the",
"calendar",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/calendar.js#L120-L131 |
46,456 | ericnishio/finnish-holidays-js | lib/calendar.js | nextMonth | function nextMonth() {
if (calendar.m === 12) {
calendar.m = 1;
calendar.y += 1;
calendar.d = 1;
} else {
calendar.m += 1;
calendar.d = 1;
}
calendar.year = yearFactory.get(calendar.y);
} | javascript | function nextMonth() {
if (calendar.m === 12) {
calendar.m = 1;
calendar.y += 1;
calendar.d = 1;
} else {
calendar.m += 1;
calendar.d = 1;
}
calendar.year = yearFactory.get(calendar.y);
} | [
"function",
"nextMonth",
"(",
")",
"{",
"if",
"(",
"calendar",
".",
"m",
"===",
"12",
")",
"{",
"calendar",
".",
"m",
"=",
"1",
";",
"calendar",
".",
"y",
"+=",
"1",
";",
"calendar",
".",
"d",
"=",
"1",
";",
"}",
"else",
"{",
"calendar",
".",
"m",
"+=",
"1",
";",
"calendar",
".",
"d",
"=",
"1",
";",
"}",
"calendar",
".",
"year",
"=",
"yearFactory",
".",
"get",
"(",
"calendar",
".",
"y",
")",
";",
"}"
]
| Goes to the next month.
@private | [
"Goes",
"to",
"the",
"next",
"month",
"."
]
| 33416bd96b18bf7b18c331c831212aefb2a6f9c2 | https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/calendar.js#L137-L148 |
46,457 | julescarbon/grunt-dentist | tasks/dentist.js | parse_html | function parse_html() {
var reading_js = false, reading_css = false;
var parser = new htmlparser.Parser({
onopentag: function(name, attribs){
if (name === "script" && ! attribs.src && (attribs.type === "text/javascript" || ! attribs.type)){
reading_js = true;
}
else if (name === "style") {
reading_css = true;
}
},
ontext: function(text){
if (reading_js) {
scripts.push(text);
}
if (reading_css) {
styles.push(text);
}
},
onclosetag: function(tagname){
if (tagname === "script"){
reading_js = false;
}
else if (tagname === "style"){
reading_css = false;
}
}
});
parser.write(src);
parser.end();
return true;
} | javascript | function parse_html() {
var reading_js = false, reading_css = false;
var parser = new htmlparser.Parser({
onopentag: function(name, attribs){
if (name === "script" && ! attribs.src && (attribs.type === "text/javascript" || ! attribs.type)){
reading_js = true;
}
else if (name === "style") {
reading_css = true;
}
},
ontext: function(text){
if (reading_js) {
scripts.push(text);
}
if (reading_css) {
styles.push(text);
}
},
onclosetag: function(tagname){
if (tagname === "script"){
reading_js = false;
}
else if (tagname === "style"){
reading_css = false;
}
}
});
parser.write(src);
parser.end();
return true;
} | [
"function",
"parse_html",
"(",
")",
"{",
"var",
"reading_js",
"=",
"false",
",",
"reading_css",
"=",
"false",
";",
"var",
"parser",
"=",
"new",
"htmlparser",
".",
"Parser",
"(",
"{",
"onopentag",
":",
"function",
"(",
"name",
",",
"attribs",
")",
"{",
"if",
"(",
"name",
"===",
"\"script\"",
"&&",
"!",
"attribs",
".",
"src",
"&&",
"(",
"attribs",
".",
"type",
"===",
"\"text/javascript\"",
"||",
"!",
"attribs",
".",
"type",
")",
")",
"{",
"reading_js",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"name",
"===",
"\"style\"",
")",
"{",
"reading_css",
"=",
"true",
";",
"}",
"}",
",",
"ontext",
":",
"function",
"(",
"text",
")",
"{",
"if",
"(",
"reading_js",
")",
"{",
"scripts",
".",
"push",
"(",
"text",
")",
";",
"}",
"if",
"(",
"reading_css",
")",
"{",
"styles",
".",
"push",
"(",
"text",
")",
";",
"}",
"}",
",",
"onclosetag",
":",
"function",
"(",
"tagname",
")",
"{",
"if",
"(",
"tagname",
"===",
"\"script\"",
")",
"{",
"reading_js",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"tagname",
"===",
"\"style\"",
")",
"{",
"reading_css",
"=",
"false",
";",
"}",
"}",
"}",
")",
";",
"parser",
".",
"write",
"(",
"src",
")",
";",
"parser",
".",
"end",
"(",
")",
";",
"return",
"true",
";",
"}"
]
| Use the HTML parser to grab anything inside script and style tags. | [
"Use",
"the",
"HTML",
"parser",
"to",
"grab",
"anything",
"inside",
"script",
"and",
"style",
"tags",
"."
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L83-L115 |
46,458 | julescarbon/grunt-dentist | tasks/dentist.js | remove_inline_scripts | function remove_inline_scripts(){
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].length && scripts[i] !== "\n") {
html = html.replace(scripts[i], "");
}
}
} | javascript | function remove_inline_scripts(){
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].length && scripts[i] !== "\n") {
html = html.replace(scripts[i], "");
}
}
} | [
"function",
"remove_inline_scripts",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"scripts",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"scripts",
"[",
"i",
"]",
".",
"length",
"&&",
"scripts",
"[",
"i",
"]",
"!==",
"\"\\n\"",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"scripts",
"[",
"i",
"]",
",",
"\"\"",
")",
";",
"}",
"}",
"}"
]
| Remove inlined scripts from HTML | [
"Remove",
"inlined",
"scripts",
"from",
"HTML"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L118-L124 |
46,459 | julescarbon/grunt-dentist | tasks/dentist.js | remove_inline_stylesheets | function remove_inline_stylesheets(){
for (var i = 0; i < styles.length; i++) {
if (styles[i].length && styles[i] !== "\n") {
html = html.replace(styles[i], "");
}
}
} | javascript | function remove_inline_stylesheets(){
for (var i = 0; i < styles.length; i++) {
if (styles[i].length && styles[i] !== "\n") {
html = html.replace(styles[i], "");
}
}
} | [
"function",
"remove_inline_stylesheets",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"styles",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"styles",
"[",
"i",
"]",
".",
"length",
"&&",
"styles",
"[",
"i",
"]",
"!==",
"\"\\n\"",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"styles",
"[",
"i",
"]",
",",
"\"\"",
")",
";",
"}",
"}",
"}"
]
| Remove inlined stylesheets from HTML | [
"Remove",
"inlined",
"stylesheets",
"from",
"HTML"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L127-L133 |
46,460 | julescarbon/grunt-dentist | tasks/dentist.js | remove_script_tags | function remove_script_tags(){
html = html.replace(/<script[^>]*>.*?<\/script>/g, function(str){
if (str.match(/ type=/) && ! str.match(/text\/javascript/)) { return str; }
else if (str.match(/src=['"]?(https?)/)) { return str; }
else if (str.match(/src=['"]?\/\//)) { return str; }
else if (! options.clean_scripts && str.match(/src=['"]/)) { return str; }
else { return ""; }
});
} | javascript | function remove_script_tags(){
html = html.replace(/<script[^>]*>.*?<\/script>/g, function(str){
if (str.match(/ type=/) && ! str.match(/text\/javascript/)) { return str; }
else if (str.match(/src=['"]?(https?)/)) { return str; }
else if (str.match(/src=['"]?\/\//)) { return str; }
else if (! options.clean_scripts && str.match(/src=['"]/)) { return str; }
else { return ""; }
});
} | [
"function",
"remove_script_tags",
"(",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"/",
"<script[^>]*>.*?<\\/script>",
"/",
"g",
",",
"function",
"(",
"str",
")",
"{",
"if",
"(",
"str",
".",
"match",
"(",
"/",
" type=",
"/",
")",
"&&",
"!",
"str",
".",
"match",
"(",
"/",
"text\\/javascript",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"src=['\"]?(https?)",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"src=['\"]?\\/\\/",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"if",
"(",
"!",
"options",
".",
"clean_scripts",
"&&",
"str",
".",
"match",
"(",
"/",
"src=['\"]",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"{",
"return",
"\"\"",
";",
"}",
"}",
")",
";",
"}"
]
| Remove script tags pointing at local assets. Avoid wiping external dependencies and non-JS content inside script tags | [
"Remove",
"script",
"tags",
"pointing",
"at",
"local",
"assets",
".",
"Avoid",
"wiping",
"external",
"dependencies",
"and",
"non",
"-",
"JS",
"content",
"inside",
"script",
"tags"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L137-L145 |
46,461 | julescarbon/grunt-dentist | tasks/dentist.js | remove_stylesheet_tags | function remove_stylesheet_tags() {
// We can remove the style tag with impunity, it is always inlining.
html = html.replace(/<style.+?<\/style>/g, "");
// External style resources use the link tag, check again for externals.
if (options.clean_stylesheets) {
html = html.replace(/<link[^>]+>/g, function(str){
if (str.match(/src=/)) {
grunt.log.warn('Found LINK tag with SRC attribute.');
return str;
}
else if (! str.match(/ rel=['"]?stylesheet/)) { return str; }
else if (str.match(/href=['"]?https?/)) { return str; }
else if (str.match(/href=['"]?\/\//)) { return str; }
else { return ""; }
});
}
} | javascript | function remove_stylesheet_tags() {
// We can remove the style tag with impunity, it is always inlining.
html = html.replace(/<style.+?<\/style>/g, "");
// External style resources use the link tag, check again for externals.
if (options.clean_stylesheets) {
html = html.replace(/<link[^>]+>/g, function(str){
if (str.match(/src=/)) {
grunt.log.warn('Found LINK tag with SRC attribute.');
return str;
}
else if (! str.match(/ rel=['"]?stylesheet/)) { return str; }
else if (str.match(/href=['"]?https?/)) { return str; }
else if (str.match(/href=['"]?\/\//)) { return str; }
else { return ""; }
});
}
} | [
"function",
"remove_stylesheet_tags",
"(",
")",
"{",
"// We can remove the style tag with impunity, it is always inlining.",
"html",
"=",
"html",
".",
"replace",
"(",
"/",
"<style.+?<\\/style>",
"/",
"g",
",",
"\"\"",
")",
";",
"// External style resources use the link tag, check again for externals.",
"if",
"(",
"options",
".",
"clean_stylesheets",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"/",
"<link[^>]+>",
"/",
"g",
",",
"function",
"(",
"str",
")",
"{",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"src=",
"/",
")",
")",
"{",
"grunt",
".",
"log",
".",
"warn",
"(",
"'Found LINK tag with SRC attribute.'",
")",
";",
"return",
"str",
";",
"}",
"else",
"if",
"(",
"!",
"str",
".",
"match",
"(",
"/",
" rel=['\"]?stylesheet",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"href=['\"]?https?",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"href=['\"]?\\/\\/",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"{",
"return",
"\"\"",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Remove style and link tags pointing at local stylesheets | [
"Remove",
"style",
"and",
"link",
"tags",
"pointing",
"at",
"local",
"stylesheets"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L148-L165 |
46,462 | julescarbon/grunt-dentist | tasks/dentist.js | remove_comments | function remove_comments(){
if (options.clean_comments) {
html = html.replace(/<!--[\s\S]*?-->/g, function(str){
if (str.match(/<!--\[if /)) { return str; }
if (str.match(/\n/)) { return str; }
else { return ""; }
});
}
} | javascript | function remove_comments(){
if (options.clean_comments) {
html = html.replace(/<!--[\s\S]*?-->/g, function(str){
if (str.match(/<!--\[if /)) { return str; }
if (str.match(/\n/)) { return str; }
else { return ""; }
});
}
} | [
"function",
"remove_comments",
"(",
")",
"{",
"if",
"(",
"options",
".",
"clean_comments",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"/",
"<!--[\\s\\S]*?-->",
"/",
"g",
",",
"function",
"(",
"str",
")",
"{",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"<!--\\[if ",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"str",
".",
"match",
"(",
"/",
"\\n",
"/",
")",
")",
"{",
"return",
"str",
";",
"}",
"else",
"{",
"return",
"\"\"",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Remove HTML comments | [
"Remove",
"HTML",
"comments"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L168-L176 |
46,463 | julescarbon/grunt-dentist | tasks/dentist.js | inject | function inject (tag, shims){
var added = shims.some(function(shim){
var i = html.lastIndexOf(shim);
if (i !== -1) {
html = html.substr(0, i) + tag + html.substr(i);
return true;
}
return false;
});
// Failing that, just append it.
if (! added) {
html += tag;
}
} | javascript | function inject (tag, shims){
var added = shims.some(function(shim){
var i = html.lastIndexOf(shim);
if (i !== -1) {
html = html.substr(0, i) + tag + html.substr(i);
return true;
}
return false;
});
// Failing that, just append it.
if (! added) {
html += tag;
}
} | [
"function",
"inject",
"(",
"tag",
",",
"shims",
")",
"{",
"var",
"added",
"=",
"shims",
".",
"some",
"(",
"function",
"(",
"shim",
")",
"{",
"var",
"i",
"=",
"html",
".",
"lastIndexOf",
"(",
"shim",
")",
";",
"if",
"(",
"i",
"!==",
"-",
"1",
")",
"{",
"html",
"=",
"html",
".",
"substr",
"(",
"0",
",",
"i",
")",
"+",
"tag",
"+",
"html",
".",
"substr",
"(",
"i",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"// Failing that, just append it.",
"if",
"(",
"!",
"added",
")",
"{",
"html",
"+=",
"tag",
";",
"}",
"}"
]
| Inject some text before a specified tag | [
"Inject",
"some",
"text",
"before",
"a",
"specified",
"tag"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L179-L192 |
46,464 | julescarbon/grunt-dentist | tasks/dentist.js | inject_script_shim | function inject_script_shim () {
if (options.include_js) {
var script_tag = '<script type="text/javascript" src="' + options.include_js + '"></script>';
if (options.js_insert_marker && html.indexOf(options.js_insert_marker) !== -1) {
html = html.replace(options.js_insert_marker, script_tag);
}
else {
var shims = ["</body>", "</html>", "</head>"];
inject(script_tag, shims);
}
}
} | javascript | function inject_script_shim () {
if (options.include_js) {
var script_tag = '<script type="text/javascript" src="' + options.include_js + '"></script>';
if (options.js_insert_marker && html.indexOf(options.js_insert_marker) !== -1) {
html = html.replace(options.js_insert_marker, script_tag);
}
else {
var shims = ["</body>", "</html>", "</head>"];
inject(script_tag, shims);
}
}
} | [
"function",
"inject_script_shim",
"(",
")",
"{",
"if",
"(",
"options",
".",
"include_js",
")",
"{",
"var",
"script_tag",
"=",
"'<script type=\"text/javascript\" src=\"'",
"+",
"options",
".",
"include_js",
"+",
"'\"></script>'",
";",
"if",
"(",
"options",
".",
"js_insert_marker",
"&&",
"html",
".",
"indexOf",
"(",
"options",
".",
"js_insert_marker",
")",
"!==",
"-",
"1",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"options",
".",
"js_insert_marker",
",",
"script_tag",
")",
";",
"}",
"else",
"{",
"var",
"shims",
"=",
"[",
"\"</body>\"",
",",
"\"</html>\"",
",",
"\"</head>\"",
"]",
";",
"inject",
"(",
"script_tag",
",",
"shims",
")",
";",
"}",
"}",
"}"
]
| Inject a script tag pointed at the minified JS. Attempt to insert the shim before the closing body tag. | [
"Inject",
"a",
"script",
"tag",
"pointed",
"at",
"the",
"minified",
"JS",
".",
"Attempt",
"to",
"insert",
"the",
"shim",
"before",
"the",
"closing",
"body",
"tag",
"."
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L196-L207 |
46,465 | julescarbon/grunt-dentist | tasks/dentist.js | inject_stylesheet_shim | function inject_stylesheet_shim () {
if (options.include_css) {
var style_tag = '<link rel="stylesheet" type="text/css" href="' + options.include_css + '">';
if (options.css_insert_marker && html.indexOf(options.css_insert_marker) !== -1) {
html = html.replace(options.css_insert_marker, style_tag);
}
else {
var shims = ["</head>", "<body>", "</html>"];
inject(style_tag, shims);
}
}
} | javascript | function inject_stylesheet_shim () {
if (options.include_css) {
var style_tag = '<link rel="stylesheet" type="text/css" href="' + options.include_css + '">';
if (options.css_insert_marker && html.indexOf(options.css_insert_marker) !== -1) {
html = html.replace(options.css_insert_marker, style_tag);
}
else {
var shims = ["</head>", "<body>", "</html>"];
inject(style_tag, shims);
}
}
} | [
"function",
"inject_stylesheet_shim",
"(",
")",
"{",
"if",
"(",
"options",
".",
"include_css",
")",
"{",
"var",
"style_tag",
"=",
"'<link rel=\"stylesheet\" type=\"text/css\" href=\"'",
"+",
"options",
".",
"include_css",
"+",
"'\">'",
";",
"if",
"(",
"options",
".",
"css_insert_marker",
"&&",
"html",
".",
"indexOf",
"(",
"options",
".",
"css_insert_marker",
")",
"!==",
"-",
"1",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"options",
".",
"css_insert_marker",
",",
"style_tag",
")",
";",
"}",
"else",
"{",
"var",
"shims",
"=",
"[",
"\"</head>\"",
",",
"\"<body>\"",
",",
"\"</html>\"",
"]",
";",
"inject",
"(",
"style_tag",
",",
"shims",
")",
";",
"}",
"}",
"}"
]
| Inject a style tag pointed at the minified CSS. Attempt to insert the shim before the closing head tag. | [
"Inject",
"a",
"style",
"tag",
"pointed",
"at",
"the",
"minified",
"CSS",
".",
"Attempt",
"to",
"insert",
"the",
"shim",
"before",
"the",
"closing",
"head",
"tag",
"."
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L211-L222 |
46,466 | julescarbon/grunt-dentist | tasks/dentist.js | write_css | function write_css () {
if (dest.dest_css) {
grunt.file.write(dest.dest_css, strip_whitespace(styles.join("\n")));
grunt.log.writeln('Stylesheet ' + dest.dest_css + '" extracted.');
}
} | javascript | function write_css () {
if (dest.dest_css) {
grunt.file.write(dest.dest_css, strip_whitespace(styles.join("\n")));
grunt.log.writeln('Stylesheet ' + dest.dest_css + '" extracted.');
}
} | [
"function",
"write_css",
"(",
")",
"{",
"if",
"(",
"dest",
".",
"dest_css",
")",
"{",
"grunt",
".",
"file",
".",
"write",
"(",
"dest",
".",
"dest_css",
",",
"strip_whitespace",
"(",
"styles",
".",
"join",
"(",
"\"\\n\"",
")",
")",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Stylesheet '",
"+",
"dest",
".",
"dest_css",
"+",
"'\" extracted.'",
")",
";",
"}",
"}"
]
| Write the CSS | [
"Write",
"the",
"CSS"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L233-L238 |
46,467 | julescarbon/grunt-dentist | tasks/dentist.js | write_js | function write_js () {
if (dest.dest_js) {
grunt.file.write(dest.dest_js, strip_whitespace(scripts.join(";\n")));
grunt.log.writeln('Script "' + dest.dest_js + '" extracted.');
}
} | javascript | function write_js () {
if (dest.dest_js) {
grunt.file.write(dest.dest_js, strip_whitespace(scripts.join(";\n")));
grunt.log.writeln('Script "' + dest.dest_js + '" extracted.');
}
} | [
"function",
"write_js",
"(",
")",
"{",
"if",
"(",
"dest",
".",
"dest_js",
")",
"{",
"grunt",
".",
"file",
".",
"write",
"(",
"dest",
".",
"dest_js",
",",
"strip_whitespace",
"(",
"scripts",
".",
"join",
"(",
"\";\\n\"",
")",
")",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Script \"'",
"+",
"dest",
".",
"dest_js",
"+",
"'\" extracted.'",
")",
";",
"}",
"}"
]
| Write the JS | [
"Write",
"the",
"JS"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L241-L246 |
46,468 | julescarbon/grunt-dentist | tasks/dentist.js | write_html | function write_html () {
if (dest.dest_html) {
grunt.file.write(dest.dest_html, strip_whitespace(html));
grunt.log.writeln('Document "' + dest.dest_html + '" extracted.');
}
} | javascript | function write_html () {
if (dest.dest_html) {
grunt.file.write(dest.dest_html, strip_whitespace(html));
grunt.log.writeln('Document "' + dest.dest_html + '" extracted.');
}
} | [
"function",
"write_html",
"(",
")",
"{",
"if",
"(",
"dest",
".",
"dest_html",
")",
"{",
"grunt",
".",
"file",
".",
"write",
"(",
"dest",
".",
"dest_html",
",",
"strip_whitespace",
"(",
"html",
")",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Document \"'",
"+",
"dest",
".",
"dest_html",
"+",
"'\" extracted.'",
")",
";",
"}",
"}"
]
| Write the HTML | [
"Write",
"the",
"HTML"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L249-L254 |
46,469 | julescarbon/grunt-dentist | tasks/dentist.js | run_dentist | function run_dentist() {
if (load_files() && parse_html()) {
if (dest.dest_html) {
if (dest.dest_js) {
remove_inline_scripts();
remove_script_tags();
inject_script_shim();
}
if (dest.dest_css) {
remove_inline_stylesheets();
remove_stylesheet_tags();
inject_stylesheet_shim();
}
}
remove_comments();
write_js();
write_css();
write_html();
return true;
}
else {
return false;
}
} | javascript | function run_dentist() {
if (load_files() && parse_html()) {
if (dest.dest_html) {
if (dest.dest_js) {
remove_inline_scripts();
remove_script_tags();
inject_script_shim();
}
if (dest.dest_css) {
remove_inline_stylesheets();
remove_stylesheet_tags();
inject_stylesheet_shim();
}
}
remove_comments();
write_js();
write_css();
write_html();
return true;
}
else {
return false;
}
} | [
"function",
"run_dentist",
"(",
")",
"{",
"if",
"(",
"load_files",
"(",
")",
"&&",
"parse_html",
"(",
")",
")",
"{",
"if",
"(",
"dest",
".",
"dest_html",
")",
"{",
"if",
"(",
"dest",
".",
"dest_js",
")",
"{",
"remove_inline_scripts",
"(",
")",
";",
"remove_script_tags",
"(",
")",
";",
"inject_script_shim",
"(",
")",
";",
"}",
"if",
"(",
"dest",
".",
"dest_css",
")",
"{",
"remove_inline_stylesheets",
"(",
")",
";",
"remove_stylesheet_tags",
"(",
")",
";",
"inject_stylesheet_shim",
"(",
")",
";",
"}",
"}",
"remove_comments",
"(",
")",
";",
"write_js",
"(",
")",
";",
"write_css",
"(",
")",
";",
"write_html",
"(",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
]
| Main Dentist task | [
"Main",
"Dentist",
"task"
]
| d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb | https://github.com/julescarbon/grunt-dentist/blob/d6dc4921f67bf521fb044fdb89bffe9cbdeacbbb/tasks/dentist.js#L257-L281 |
46,470 | TMiguelT/pokemontcgscraper | index.js | scrapeEnergies | function scrapeEnergies(el, $, func) {
const $el = $(el);
$el.find("li").each(function (i, val) {
const $val = $(val);
const type = $val.attr("title");
func(type, $val);
});
} | javascript | function scrapeEnergies(el, $, func) {
const $el = $(el);
$el.find("li").each(function (i, val) {
const $val = $(val);
const type = $val.attr("title");
func(type, $val);
});
} | [
"function",
"scrapeEnergies",
"(",
"el",
",",
"$",
",",
"func",
")",
"{",
"const",
"$el",
"=",
"$",
"(",
"el",
")",
";",
"$el",
".",
"find",
"(",
"\"li\"",
")",
".",
"each",
"(",
"function",
"(",
"i",
",",
"val",
")",
"{",
"const",
"$val",
"=",
"$",
"(",
"val",
")",
";",
"const",
"type",
"=",
"$val",
".",
"attr",
"(",
"\"title\"",
")",
";",
"func",
"(",
"type",
",",
"$val",
")",
";",
"}",
")",
";",
"}"
]
| Calls the callback function on each energy
@param el the DOM element to start scraping from
@param $ the query object el exists within
@param func called with (energy, $), where energy is the energy type (Fire etc.) and $ is a jQuery element for this energy | [
"Calls",
"the",
"callback",
"function",
"on",
"each",
"energy"
]
| b8fb289cf582b5d158f94f3903b17409dfc3f168 | https://github.com/TMiguelT/pokemontcgscraper/blob/b8fb289cf582b5d158f94f3903b17409dfc3f168/index.js#L68-L76 |
46,471 | TMiguelT/pokemontcgscraper | index.js | scrapeAll | function scrapeAll(query, scrapeDetails) {
return co(function *() {
//By default, scrape the card details
scrapeDetails = scrapeDetails === undefined ? true : scrapeDetails;
//Load the HTML page
const scrapeURL = makeUrl(SCRAPE_URL, query);
const search = yield scrapeSearchPage(scrapeURL);
//Recurring variables
var cards = search.cards;
var i;
//Scrape all of the pages sequentially;
for (i = 2; i <= search.numPages; i++) {
const scrapeURL = makeUrl(Url.resolve(SCRAPE_URL, i.toString()), query);
const results = yield scrapeSearchPage(scrapeURL);
cards = cards.concat(results.cards);
}
//Scrape all of the cards sequentially if requested
if (scrapeDetails) {
for (i = 0; i < cards.length; i++) {
const card = cards[i];
_.assign(card, yield scrapeCard(card.url));
}
}
return cards;
})();
} | javascript | function scrapeAll(query, scrapeDetails) {
return co(function *() {
//By default, scrape the card details
scrapeDetails = scrapeDetails === undefined ? true : scrapeDetails;
//Load the HTML page
const scrapeURL = makeUrl(SCRAPE_URL, query);
const search = yield scrapeSearchPage(scrapeURL);
//Recurring variables
var cards = search.cards;
var i;
//Scrape all of the pages sequentially;
for (i = 2; i <= search.numPages; i++) {
const scrapeURL = makeUrl(Url.resolve(SCRAPE_URL, i.toString()), query);
const results = yield scrapeSearchPage(scrapeURL);
cards = cards.concat(results.cards);
}
//Scrape all of the cards sequentially if requested
if (scrapeDetails) {
for (i = 0; i < cards.length; i++) {
const card = cards[i];
_.assign(card, yield scrapeCard(card.url));
}
}
return cards;
})();
} | [
"function",
"scrapeAll",
"(",
"query",
",",
"scrapeDetails",
")",
"{",
"return",
"co",
"(",
"function",
"*",
"(",
")",
"{",
"//By default, scrape the card details",
"scrapeDetails",
"=",
"scrapeDetails",
"===",
"undefined",
"?",
"true",
":",
"scrapeDetails",
";",
"//Load the HTML page",
"const",
"scrapeURL",
"=",
"makeUrl",
"(",
"SCRAPE_URL",
",",
"query",
")",
";",
"const",
"search",
"=",
"yield",
"scrapeSearchPage",
"(",
"scrapeURL",
")",
";",
"//Recurring variables",
"var",
"cards",
"=",
"search",
".",
"cards",
";",
"var",
"i",
";",
"//Scrape all of the pages sequentially;",
"for",
"(",
"i",
"=",
"2",
";",
"i",
"<=",
"search",
".",
"numPages",
";",
"i",
"++",
")",
"{",
"const",
"scrapeURL",
"=",
"makeUrl",
"(",
"Url",
".",
"resolve",
"(",
"SCRAPE_URL",
",",
"i",
".",
"toString",
"(",
")",
")",
",",
"query",
")",
";",
"const",
"results",
"=",
"yield",
"scrapeSearchPage",
"(",
"scrapeURL",
")",
";",
"cards",
"=",
"cards",
".",
"concat",
"(",
"results",
".",
"cards",
")",
";",
"}",
"//Scrape all of the cards sequentially if requested",
"if",
"(",
"scrapeDetails",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"cards",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"card",
"=",
"cards",
"[",
"i",
"]",
";",
"_",
".",
"assign",
"(",
"card",
",",
"yield",
"scrapeCard",
"(",
"card",
".",
"url",
")",
")",
";",
"}",
"}",
"return",
"cards",
";",
"}",
")",
"(",
")",
";",
"}"
]
| Scrapes the Pokemon TCG database
@param query The query string to use for the search.
@param scrapeDetails True if you want to return the card data, false if you just want the URLs
@returns {*} | [
"Scrapes",
"the",
"Pokemon",
"TCG",
"database"
]
| b8fb289cf582b5d158f94f3903b17409dfc3f168 | https://github.com/TMiguelT/pokemontcgscraper/blob/b8fb289cf582b5d158f94f3903b17409dfc3f168/index.js#L242-L273 |
46,472 | benlue/newsql | lib/newsql.js | matchSQLFilter | function matchSQLFilter(tableSchema, whereCol) {
for (var i in whereCol) {
var col = whereCol[i],
schema = tableSchema[col.tbName];
if (!schema)
throw new Error('A filter column refers to an unknown table [' + col.tbName + ']');
if (schema.columns.indexOf(col.col) < 0)
return false;
}
return true;
} | javascript | function matchSQLFilter(tableSchema, whereCol) {
for (var i in whereCol) {
var col = whereCol[i],
schema = tableSchema[col.tbName];
if (!schema)
throw new Error('A filter column refers to an unknown table [' + col.tbName + ']');
if (schema.columns.indexOf(col.col) < 0)
return false;
}
return true;
} | [
"function",
"matchSQLFilter",
"(",
"tableSchema",
",",
"whereCol",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"whereCol",
")",
"{",
"var",
"col",
"=",
"whereCol",
"[",
"i",
"]",
",",
"schema",
"=",
"tableSchema",
"[",
"col",
".",
"tbName",
"]",
";",
"if",
"(",
"!",
"schema",
")",
"throw",
"new",
"Error",
"(",
"'A filter column refers to an unknown table ['",
"+",
"col",
".",
"tbName",
"+",
"']'",
")",
";",
"if",
"(",
"schema",
".",
"columns",
".",
"indexOf",
"(",
"col",
".",
"col",
")",
"<",
"0",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| check if whereCol contains any non-sql columns. | [
"check",
"if",
"whereCol",
"contains",
"any",
"non",
"-",
"sql",
"columns",
"."
]
| 0c7fe03b134459ec952871fd9aa67c5dff18c612 | https://github.com/benlue/newsql/blob/0c7fe03b134459ec952871fd9aa67c5dff18c612/lib/newsql.js#L1070-L1082 |
46,473 | benlue/newsql | lib/newsql.js | collectFilterColumns | function collectFilterColumns(dftTable, filter, col) {
var isLogical = false;
if (filter.op === 'AND' || filter.op === 'and' || filter.op === 'OR' || filter.op === 'or') {
filter.op = filter.op.toLowerCase();
isLogical = true;
}
if (isLogical) {
filter.filters.forEach(function(f) {
collectFilterColumns(dftTable, f, col);
});
}
else {
var colName = filter.field || filter.name,
fc = {tbName: dftTable, col: colName, orig: colName},
idx = colName.indexOf('.');
if (idx > 0) {
fc.tbName = colName.substring(0, idx);
fc.col = colName.substring(idx+1);
}
if (_.findIndex(col, fc) < 0)
col.push(fc);
}
} | javascript | function collectFilterColumns(dftTable, filter, col) {
var isLogical = false;
if (filter.op === 'AND' || filter.op === 'and' || filter.op === 'OR' || filter.op === 'or') {
filter.op = filter.op.toLowerCase();
isLogical = true;
}
if (isLogical) {
filter.filters.forEach(function(f) {
collectFilterColumns(dftTable, f, col);
});
}
else {
var colName = filter.field || filter.name,
fc = {tbName: dftTable, col: colName, orig: colName},
idx = colName.indexOf('.');
if (idx > 0) {
fc.tbName = colName.substring(0, idx);
fc.col = colName.substring(idx+1);
}
if (_.findIndex(col, fc) < 0)
col.push(fc);
}
} | [
"function",
"collectFilterColumns",
"(",
"dftTable",
",",
"filter",
",",
"col",
")",
"{",
"var",
"isLogical",
"=",
"false",
";",
"if",
"(",
"filter",
".",
"op",
"===",
"'AND'",
"||",
"filter",
".",
"op",
"===",
"'and'",
"||",
"filter",
".",
"op",
"===",
"'OR'",
"||",
"filter",
".",
"op",
"===",
"'or'",
")",
"{",
"filter",
".",
"op",
"=",
"filter",
".",
"op",
".",
"toLowerCase",
"(",
")",
";",
"isLogical",
"=",
"true",
";",
"}",
"if",
"(",
"isLogical",
")",
"{",
"filter",
".",
"filters",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"collectFilterColumns",
"(",
"dftTable",
",",
"f",
",",
"col",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"var",
"colName",
"=",
"filter",
".",
"field",
"||",
"filter",
".",
"name",
",",
"fc",
"=",
"{",
"tbName",
":",
"dftTable",
",",
"col",
":",
"colName",
",",
"orig",
":",
"colName",
"}",
",",
"idx",
"=",
"colName",
".",
"indexOf",
"(",
"'.'",
")",
";",
"if",
"(",
"idx",
">",
"0",
")",
"{",
"fc",
".",
"tbName",
"=",
"colName",
".",
"substring",
"(",
"0",
",",
"idx",
")",
";",
"fc",
".",
"col",
"=",
"colName",
".",
"substring",
"(",
"idx",
"+",
"1",
")",
";",
"}",
"if",
"(",
"_",
".",
"findIndex",
"(",
"col",
",",
"fc",
")",
"<",
"0",
")",
"col",
".",
"push",
"(",
"fc",
")",
";",
"}",
"}"
]
| Check if a filter contains json-columns | [
"Check",
"if",
"a",
"filter",
"contains",
"json",
"-",
"columns"
]
| 0c7fe03b134459ec952871fd9aa67c5dff18c612 | https://github.com/benlue/newsql/blob/0c7fe03b134459ec952871fd9aa67c5dff18c612/lib/newsql.js#L1242-L1267 |
46,474 | benlue/newsql | lib/newsql.js | buildSqlFilter | function buildSqlFilter(filter, columns) {
if (filter.op === 'and') {
var clones = [];
filter.filters.forEach(function(f) {
var cf = buildSqlFilter(f, columns);
if (cf)
clones.push( cf );
});
var len = clones.length;
if (len < 1)
return null;
else
return len > 1 ? {op: 'and', filters: clones} : clones[0];
}
else if (filter.op === 'or') {
var clones = [];
filter.filters.forEach(function(f) {
var cf = buildSqlFilter(f, columns);
if (cf)
clones.push( cf );
});
return clones.length === filter.filters.length ? {op: 'or', filters: clones} : null;
}
var cf = null,
colName = filter.name;
if (columns.indexOf(colName) >= 0)
cf = filter; //cloneObj( filter );
return cf;
} | javascript | function buildSqlFilter(filter, columns) {
if (filter.op === 'and') {
var clones = [];
filter.filters.forEach(function(f) {
var cf = buildSqlFilter(f, columns);
if (cf)
clones.push( cf );
});
var len = clones.length;
if (len < 1)
return null;
else
return len > 1 ? {op: 'and', filters: clones} : clones[0];
}
else if (filter.op === 'or') {
var clones = [];
filter.filters.forEach(function(f) {
var cf = buildSqlFilter(f, columns);
if (cf)
clones.push( cf );
});
return clones.length === filter.filters.length ? {op: 'or', filters: clones} : null;
}
var cf = null,
colName = filter.name;
if (columns.indexOf(colName) >= 0)
cf = filter; //cloneObj( filter );
return cf;
} | [
"function",
"buildSqlFilter",
"(",
"filter",
",",
"columns",
")",
"{",
"if",
"(",
"filter",
".",
"op",
"===",
"'and'",
")",
"{",
"var",
"clones",
"=",
"[",
"]",
";",
"filter",
".",
"filters",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"var",
"cf",
"=",
"buildSqlFilter",
"(",
"f",
",",
"columns",
")",
";",
"if",
"(",
"cf",
")",
"clones",
".",
"push",
"(",
"cf",
")",
";",
"}",
")",
";",
"var",
"len",
"=",
"clones",
".",
"length",
";",
"if",
"(",
"len",
"<",
"1",
")",
"return",
"null",
";",
"else",
"return",
"len",
">",
"1",
"?",
"{",
"op",
":",
"'and'",
",",
"filters",
":",
"clones",
"}",
":",
"clones",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"filter",
".",
"op",
"===",
"'or'",
")",
"{",
"var",
"clones",
"=",
"[",
"]",
";",
"filter",
".",
"filters",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"var",
"cf",
"=",
"buildSqlFilter",
"(",
"f",
",",
"columns",
")",
";",
"if",
"(",
"cf",
")",
"clones",
".",
"push",
"(",
"cf",
")",
";",
"}",
")",
";",
"return",
"clones",
".",
"length",
"===",
"filter",
".",
"filters",
".",
"length",
"?",
"{",
"op",
":",
"'or'",
",",
"filters",
":",
"clones",
"}",
":",
"null",
";",
"}",
"var",
"cf",
"=",
"null",
",",
"colName",
"=",
"filter",
".",
"name",
";",
"if",
"(",
"columns",
".",
"indexOf",
"(",
"colName",
")",
">=",
"0",
")",
"cf",
"=",
"filter",
";",
"//cloneObj( filter );",
"return",
"cf",
";",
"}"
]
| Build a new SQL filter with 'inertia' columns | [
"Build",
"a",
"new",
"SQL",
"filter",
"with",
"inertia",
"columns"
]
| 0c7fe03b134459ec952871fd9aa67c5dff18c612 | https://github.com/benlue/newsql/blob/0c7fe03b134459ec952871fd9aa67c5dff18c612/lib/newsql.js#L1273-L1306 |
46,475 | tollwerk/fractal-typo3 | index.js | writeFile | function writeFile(file, content) {
fs.writeFileSync(file, content);
files.push(path.relative(app.components.get('path'), file));
} | javascript | function writeFile(file, content) {
fs.writeFileSync(file, content);
files.push(path.relative(app.components.get('path'), file));
} | [
"function",
"writeFile",
"(",
"file",
",",
"content",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"file",
",",
"content",
")",
";",
"files",
".",
"push",
"(",
"path",
".",
"relative",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"file",
")",
")",
";",
"}"
]
| Write a file to disc
@param {String} path File path
@param {String} content File content | [
"Write",
"a",
"file",
"to",
"disc"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L25-L28 |
46,476 | tollwerk/fractal-typo3 | index.js | configureComponent | function configureComponent(configPath, component, componentPath) {
let config;
try {
config = require(configPath);
// If this is the default variant
if (!component.variant) {
config.title = component.name;
config.status = component.status;
config.context = config.context || {};
config.context.type = component.type;
}
config.variants = config.variants || [];
} catch (e) {
config = {
title: component.name,
status: component.status,
context: {
type: component.type,
},
variants: [],
};
}
// Register the preview component
if (component.preview) {
config.preview = `@${[...componentPath, dashify(component.name), 'preview'].join('-')}`;
}
// Remove the variant if already present
const variant = component.variant || 'default';
config.variants = config.variants.filter(vt => vt.name !== variant);
// Register the variant
config.variants.push({
name: variant,
label: component.label || ((variant === 'default') ? component.name : variant),
context: {
config: component.config,
parameters: component.parameters || {},
request: component.request,
component: component.class,
},
});
config.variants = config.variants.sort((a, b) => {
const aName = a.label.toLowerCase();
const bName = b.label.toLowerCase();
if (aName > bName) {
return 1;
}
return (aName < bName) ? -1 : 0;
});
config.variants.forEach((v, i) => {
config.variants[i].order = i;
});
// Write the configuration file
writeFile(configPath, JSON.stringify(config, null, 4));
// If there's a component note
if ((variant === 'default') && component.notice) {
const readme = path.join(path.dirname(configPath), 'README.md');
writeFile(readme, component.notice);
}
} | javascript | function configureComponent(configPath, component, componentPath) {
let config;
try {
config = require(configPath);
// If this is the default variant
if (!component.variant) {
config.title = component.name;
config.status = component.status;
config.context = config.context || {};
config.context.type = component.type;
}
config.variants = config.variants || [];
} catch (e) {
config = {
title: component.name,
status: component.status,
context: {
type: component.type,
},
variants: [],
};
}
// Register the preview component
if (component.preview) {
config.preview = `@${[...componentPath, dashify(component.name), 'preview'].join('-')}`;
}
// Remove the variant if already present
const variant = component.variant || 'default';
config.variants = config.variants.filter(vt => vt.name !== variant);
// Register the variant
config.variants.push({
name: variant,
label: component.label || ((variant === 'default') ? component.name : variant),
context: {
config: component.config,
parameters: component.parameters || {},
request: component.request,
component: component.class,
},
});
config.variants = config.variants.sort((a, b) => {
const aName = a.label.toLowerCase();
const bName = b.label.toLowerCase();
if (aName > bName) {
return 1;
}
return (aName < bName) ? -1 : 0;
});
config.variants.forEach((v, i) => {
config.variants[i].order = i;
});
// Write the configuration file
writeFile(configPath, JSON.stringify(config, null, 4));
// If there's a component note
if ((variant === 'default') && component.notice) {
const readme = path.join(path.dirname(configPath), 'README.md');
writeFile(readme, component.notice);
}
} | [
"function",
"configureComponent",
"(",
"configPath",
",",
"component",
",",
"componentPath",
")",
"{",
"let",
"config",
";",
"try",
"{",
"config",
"=",
"require",
"(",
"configPath",
")",
";",
"// If this is the default variant",
"if",
"(",
"!",
"component",
".",
"variant",
")",
"{",
"config",
".",
"title",
"=",
"component",
".",
"name",
";",
"config",
".",
"status",
"=",
"component",
".",
"status",
";",
"config",
".",
"context",
"=",
"config",
".",
"context",
"||",
"{",
"}",
";",
"config",
".",
"context",
".",
"type",
"=",
"component",
".",
"type",
";",
"}",
"config",
".",
"variants",
"=",
"config",
".",
"variants",
"||",
"[",
"]",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"config",
"=",
"{",
"title",
":",
"component",
".",
"name",
",",
"status",
":",
"component",
".",
"status",
",",
"context",
":",
"{",
"type",
":",
"component",
".",
"type",
",",
"}",
",",
"variants",
":",
"[",
"]",
",",
"}",
";",
"}",
"// Register the preview component",
"if",
"(",
"component",
".",
"preview",
")",
"{",
"config",
".",
"preview",
"=",
"`",
"${",
"[",
"...",
"componentPath",
",",
"dashify",
"(",
"component",
".",
"name",
")",
",",
"'preview'",
"]",
".",
"join",
"(",
"'-'",
")",
"}",
"`",
";",
"}",
"// Remove the variant if already present",
"const",
"variant",
"=",
"component",
".",
"variant",
"||",
"'default'",
";",
"config",
".",
"variants",
"=",
"config",
".",
"variants",
".",
"filter",
"(",
"vt",
"=>",
"vt",
".",
"name",
"!==",
"variant",
")",
";",
"// Register the variant",
"config",
".",
"variants",
".",
"push",
"(",
"{",
"name",
":",
"variant",
",",
"label",
":",
"component",
".",
"label",
"||",
"(",
"(",
"variant",
"===",
"'default'",
")",
"?",
"component",
".",
"name",
":",
"variant",
")",
",",
"context",
":",
"{",
"config",
":",
"component",
".",
"config",
",",
"parameters",
":",
"component",
".",
"parameters",
"||",
"{",
"}",
",",
"request",
":",
"component",
".",
"request",
",",
"component",
":",
"component",
".",
"class",
",",
"}",
",",
"}",
")",
";",
"config",
".",
"variants",
"=",
"config",
".",
"variants",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"const",
"aName",
"=",
"a",
".",
"label",
".",
"toLowerCase",
"(",
")",
";",
"const",
"bName",
"=",
"b",
".",
"label",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"aName",
">",
"bName",
")",
"{",
"return",
"1",
";",
"}",
"return",
"(",
"aName",
"<",
"bName",
")",
"?",
"-",
"1",
":",
"0",
";",
"}",
")",
";",
"config",
".",
"variants",
".",
"forEach",
"(",
"(",
"v",
",",
"i",
")",
"=>",
"{",
"config",
".",
"variants",
"[",
"i",
"]",
".",
"order",
"=",
"i",
";",
"}",
")",
";",
"// Write the configuration file",
"writeFile",
"(",
"configPath",
",",
"JSON",
".",
"stringify",
"(",
"config",
",",
"null",
",",
"4",
")",
")",
";",
"// If there's a component note",
"if",
"(",
"(",
"variant",
"===",
"'default'",
")",
"&&",
"component",
".",
"notice",
")",
"{",
"const",
"readme",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"configPath",
")",
",",
"'README.md'",
")",
";",
"writeFile",
"(",
"readme",
",",
"component",
".",
"notice",
")",
";",
"}",
"}"
]
| Configure a component
@param {String} configPath Component configuration path
@param {Object} component Component properties
@param {String} componentPath Component path | [
"Configure",
"a",
"component"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L37-L103 |
46,477 | tollwerk/fractal-typo3 | index.js | createCollection | function createCollection(dirPrefix, dirPath, dirConfigs) {
const dir = dirPath.shift();
const dirConfig = dirConfigs.shift() || {};
const absDir = path.join(dirPrefix, dir);
// Create the collection directory
try {
if (!fs.statSync(absDir).isDirectory()) {
throw new Error('1');
}
} catch (e) {
try {
if (!mkdirp(absDir)) {
throw new Error('2');
}
} catch (f) {
return false;
}
}
// Configure the collection prefix
const configPath = path.join(absDir, `${dir.replace(/^\d{2}-/, '')}.config.json`);
const prefix = path.relative(app.components.get('path'), absDir).split(path.sep).map(p => p.replace(/^\d{2}-/, '')).join('-');
let config;
try {
config = require(configPath);
config.prefix = prefix;
} catch (e) {
config = { prefix };
}
['label'].forEach(c => {
if (c in dirConfig) {
config[c] = dirConfig[c];
}
})
writeFile(configPath, JSON.stringify(config, null, 4));
// Recurse
return dirPath.length ? createCollection(absDir, dirPath, dirConfigs) : true;
} | javascript | function createCollection(dirPrefix, dirPath, dirConfigs) {
const dir = dirPath.shift();
const dirConfig = dirConfigs.shift() || {};
const absDir = path.join(dirPrefix, dir);
// Create the collection directory
try {
if (!fs.statSync(absDir).isDirectory()) {
throw new Error('1');
}
} catch (e) {
try {
if (!mkdirp(absDir)) {
throw new Error('2');
}
} catch (f) {
return false;
}
}
// Configure the collection prefix
const configPath = path.join(absDir, `${dir.replace(/^\d{2}-/, '')}.config.json`);
const prefix = path.relative(app.components.get('path'), absDir).split(path.sep).map(p => p.replace(/^\d{2}-/, '')).join('-');
let config;
try {
config = require(configPath);
config.prefix = prefix;
} catch (e) {
config = { prefix };
}
['label'].forEach(c => {
if (c in dirConfig) {
config[c] = dirConfig[c];
}
})
writeFile(configPath, JSON.stringify(config, null, 4));
// Recurse
return dirPath.length ? createCollection(absDir, dirPath, dirConfigs) : true;
} | [
"function",
"createCollection",
"(",
"dirPrefix",
",",
"dirPath",
",",
"dirConfigs",
")",
"{",
"const",
"dir",
"=",
"dirPath",
".",
"shift",
"(",
")",
";",
"const",
"dirConfig",
"=",
"dirConfigs",
".",
"shift",
"(",
")",
"||",
"{",
"}",
";",
"const",
"absDir",
"=",
"path",
".",
"join",
"(",
"dirPrefix",
",",
"dir",
")",
";",
"// Create the collection directory",
"try",
"{",
"if",
"(",
"!",
"fs",
".",
"statSync",
"(",
"absDir",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'1'",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"mkdirp",
"(",
"absDir",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'2'",
")",
";",
"}",
"}",
"catch",
"(",
"f",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// Configure the collection prefix",
"const",
"configPath",
"=",
"path",
".",
"join",
"(",
"absDir",
",",
"`",
"${",
"dir",
".",
"replace",
"(",
"/",
"^\\d{2}-",
"/",
",",
"''",
")",
"}",
"`",
")",
";",
"const",
"prefix",
"=",
"path",
".",
"relative",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"absDir",
")",
".",
"split",
"(",
"path",
".",
"sep",
")",
".",
"map",
"(",
"p",
"=>",
"p",
".",
"replace",
"(",
"/",
"^\\d{2}-",
"/",
",",
"''",
")",
")",
".",
"join",
"(",
"'-'",
")",
";",
"let",
"config",
";",
"try",
"{",
"config",
"=",
"require",
"(",
"configPath",
")",
";",
"config",
".",
"prefix",
"=",
"prefix",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"config",
"=",
"{",
"prefix",
"}",
";",
"}",
"[",
"'label'",
"]",
".",
"forEach",
"(",
"c",
"=>",
"{",
"if",
"(",
"c",
"in",
"dirConfig",
")",
"{",
"config",
"[",
"c",
"]",
"=",
"dirConfig",
"[",
"c",
"]",
";",
"}",
"}",
")",
"writeFile",
"(",
"configPath",
",",
"JSON",
".",
"stringify",
"(",
"config",
",",
"null",
",",
"4",
")",
")",
";",
"// Recurse",
"return",
"dirPath",
".",
"length",
"?",
"createCollection",
"(",
"absDir",
",",
"dirPath",
",",
"dirConfigs",
")",
":",
"true",
";",
"}"
]
| Create and pre-configure a directory
@param {String} dirPrefix Path prefix
@param {Array} dirPath Directory path
@param {Array} dirConfigs Local directory configurations
@return {boolean} Directory been created and pre-configured | [
"Create",
"and",
"pre",
"-",
"configure",
"a",
"directory"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L113-L153 |
46,478 | tollwerk/fractal-typo3 | index.js | registerComponent | function registerComponent(component) {
const componentName = dashify(component.name);
const componentLocalConfig = (component.local instanceof Array) ? component.local : [];
while (componentLocalConfig.length < component.path.length) {
componentLocalConfig.push([]);
}
const componentPath = component.path.slice(0).map(p => dashify(p));
const componentRealPath = componentPath.map((p, i) => {
return componentLocalConfig[i].dirsort ?
`${(new String(componentLocalConfig[i].dirsort)).padStart(2, '0')}-${p}` : p;
});
const componentParent = path.join(app.components.get('path'), ...componentRealPath);
const componentDirectory = path.join(componentParent, componentName);
// Create the component directory
if (!createCollection(app.components.get('path'), [...componentRealPath, componentName], componentLocalConfig)) {
throw new Error(`Could not create component directory ${componentDirectory}`);
}
// Write out the template file
const componentVariantName = componentName + (component.variant ? `--${dashify(component.variant)}` : '');
const componentTemplate = path.join(componentDirectory, `${componentVariantName}.${component.extension}`);
writeFile(componentTemplate, component.template);
// Write out the preview template
if (component.preview) {
writeFile(path.join(componentParent, `_${componentName}-preview.t3s`), component.preview);
}
// Configure the component
configureComponent(path.join(componentDirectory, `${componentName}.config.json`), component, componentPath);
} | javascript | function registerComponent(component) {
const componentName = dashify(component.name);
const componentLocalConfig = (component.local instanceof Array) ? component.local : [];
while (componentLocalConfig.length < component.path.length) {
componentLocalConfig.push([]);
}
const componentPath = component.path.slice(0).map(p => dashify(p));
const componentRealPath = componentPath.map((p, i) => {
return componentLocalConfig[i].dirsort ?
`${(new String(componentLocalConfig[i].dirsort)).padStart(2, '0')}-${p}` : p;
});
const componentParent = path.join(app.components.get('path'), ...componentRealPath);
const componentDirectory = path.join(componentParent, componentName);
// Create the component directory
if (!createCollection(app.components.get('path'), [...componentRealPath, componentName], componentLocalConfig)) {
throw new Error(`Could not create component directory ${componentDirectory}`);
}
// Write out the template file
const componentVariantName = componentName + (component.variant ? `--${dashify(component.variant)}` : '');
const componentTemplate = path.join(componentDirectory, `${componentVariantName}.${component.extension}`);
writeFile(componentTemplate, component.template);
// Write out the preview template
if (component.preview) {
writeFile(path.join(componentParent, `_${componentName}-preview.t3s`), component.preview);
}
// Configure the component
configureComponent(path.join(componentDirectory, `${componentName}.config.json`), component, componentPath);
} | [
"function",
"registerComponent",
"(",
"component",
")",
"{",
"const",
"componentName",
"=",
"dashify",
"(",
"component",
".",
"name",
")",
";",
"const",
"componentLocalConfig",
"=",
"(",
"component",
".",
"local",
"instanceof",
"Array",
")",
"?",
"component",
".",
"local",
":",
"[",
"]",
";",
"while",
"(",
"componentLocalConfig",
".",
"length",
"<",
"component",
".",
"path",
".",
"length",
")",
"{",
"componentLocalConfig",
".",
"push",
"(",
"[",
"]",
")",
";",
"}",
"const",
"componentPath",
"=",
"component",
".",
"path",
".",
"slice",
"(",
"0",
")",
".",
"map",
"(",
"p",
"=>",
"dashify",
"(",
"p",
")",
")",
";",
"const",
"componentRealPath",
"=",
"componentPath",
".",
"map",
"(",
"(",
"p",
",",
"i",
")",
"=>",
"{",
"return",
"componentLocalConfig",
"[",
"i",
"]",
".",
"dirsort",
"?",
"`",
"${",
"(",
"new",
"String",
"(",
"componentLocalConfig",
"[",
"i",
"]",
".",
"dirsort",
")",
")",
".",
"padStart",
"(",
"2",
",",
"'0'",
")",
"}",
"${",
"p",
"}",
"`",
":",
"p",
";",
"}",
")",
";",
"const",
"componentParent",
"=",
"path",
".",
"join",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"...",
"componentRealPath",
")",
";",
"const",
"componentDirectory",
"=",
"path",
".",
"join",
"(",
"componentParent",
",",
"componentName",
")",
";",
"// Create the component directory",
"if",
"(",
"!",
"createCollection",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"[",
"...",
"componentRealPath",
",",
"componentName",
"]",
",",
"componentLocalConfig",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"componentDirectory",
"}",
"`",
")",
";",
"}",
"// Write out the template file",
"const",
"componentVariantName",
"=",
"componentName",
"+",
"(",
"component",
".",
"variant",
"?",
"`",
"${",
"dashify",
"(",
"component",
".",
"variant",
")",
"}",
"`",
":",
"''",
")",
";",
"const",
"componentTemplate",
"=",
"path",
".",
"join",
"(",
"componentDirectory",
",",
"`",
"${",
"componentVariantName",
"}",
"${",
"component",
".",
"extension",
"}",
"`",
")",
";",
"writeFile",
"(",
"componentTemplate",
",",
"component",
".",
"template",
")",
";",
"// Write out the preview template",
"if",
"(",
"component",
".",
"preview",
")",
"{",
"writeFile",
"(",
"path",
".",
"join",
"(",
"componentParent",
",",
"`",
"${",
"componentName",
"}",
"`",
")",
",",
"component",
".",
"preview",
")",
";",
"}",
"// Configure the component",
"configureComponent",
"(",
"path",
".",
"join",
"(",
"componentDirectory",
",",
"`",
"${",
"componentName",
"}",
"`",
")",
",",
"component",
",",
"componentPath",
")",
";",
"}"
]
| Register a component
@param {Object} component Component | [
"Register",
"a",
"component"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L160-L191 |
46,479 | tollwerk/fractal-typo3 | index.js | update | function update(args, done) {
app = this.fractal;
let typo3cli = path.join(typo3path, '../vendor/bin/typo3');
let typo3args = ['extbase', 'component:discover'];
try {
if (fs.statSync(typo3cli).isFile()) {
typo3args.shift();
}
} catch (e) {
typo3cli = path.join(typo3path, 'typo3/cli_dispatch.phpsh');
}
try {
if (fs.statSync(typo3cli).isFile()) {
typo3args.unshift(typo3cli);
const componentsJSON = execFileSync('php', typo3args).toString();
const components = JSON.parse(componentsJSON);
for (const component of components) {
processComponent(component);
}
// Write the general shared context
const context = { context: { typo3: typo3url } };
writeFile(path.resolve(app.components.get('path'), 'components.config.json'), JSON.stringify(context, null, 4));
// See if there's a component file manifest
const manifest = path.resolve(app.components.get('path'), 'components.files.json');
try {
if (fs.statSync(manifest).isFile()) {
const currentFiles = new Set(files);
const prevFiles = new Set(JSON.parse(fs.readFileSync(manifest)));
// Delete all redundant files
[...prevFiles].filter(f => !currentFiles.has(f)).forEach(f => fs.unlinkSync(path.resolve(app.components.get('path'), f)));
}
} catch (e) {
// Ignore errors
} finally {
writeFile(manifest, JSON.stringify(files));
deleteEmpty.sync(app.components.get('path'));
}
}
done();
} catch (e) {
console.log(e);
process.exit(1);
}
} | javascript | function update(args, done) {
app = this.fractal;
let typo3cli = path.join(typo3path, '../vendor/bin/typo3');
let typo3args = ['extbase', 'component:discover'];
try {
if (fs.statSync(typo3cli).isFile()) {
typo3args.shift();
}
} catch (e) {
typo3cli = path.join(typo3path, 'typo3/cli_dispatch.phpsh');
}
try {
if (fs.statSync(typo3cli).isFile()) {
typo3args.unshift(typo3cli);
const componentsJSON = execFileSync('php', typo3args).toString();
const components = JSON.parse(componentsJSON);
for (const component of components) {
processComponent(component);
}
// Write the general shared context
const context = { context: { typo3: typo3url } };
writeFile(path.resolve(app.components.get('path'), 'components.config.json'), JSON.stringify(context, null, 4));
// See if there's a component file manifest
const manifest = path.resolve(app.components.get('path'), 'components.files.json');
try {
if (fs.statSync(manifest).isFile()) {
const currentFiles = new Set(files);
const prevFiles = new Set(JSON.parse(fs.readFileSync(manifest)));
// Delete all redundant files
[...prevFiles].filter(f => !currentFiles.has(f)).forEach(f => fs.unlinkSync(path.resolve(app.components.get('path'), f)));
}
} catch (e) {
// Ignore errors
} finally {
writeFile(manifest, JSON.stringify(files));
deleteEmpty.sync(app.components.get('path'));
}
}
done();
} catch (e) {
console.log(e);
process.exit(1);
}
} | [
"function",
"update",
"(",
"args",
",",
"done",
")",
"{",
"app",
"=",
"this",
".",
"fractal",
";",
"let",
"typo3cli",
"=",
"path",
".",
"join",
"(",
"typo3path",
",",
"'../vendor/bin/typo3'",
")",
";",
"let",
"typo3args",
"=",
"[",
"'extbase'",
",",
"'component:discover'",
"]",
";",
"try",
"{",
"if",
"(",
"fs",
".",
"statSync",
"(",
"typo3cli",
")",
".",
"isFile",
"(",
")",
")",
"{",
"typo3args",
".",
"shift",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"typo3cli",
"=",
"path",
".",
"join",
"(",
"typo3path",
",",
"'typo3/cli_dispatch.phpsh'",
")",
";",
"}",
"try",
"{",
"if",
"(",
"fs",
".",
"statSync",
"(",
"typo3cli",
")",
".",
"isFile",
"(",
")",
")",
"{",
"typo3args",
".",
"unshift",
"(",
"typo3cli",
")",
";",
"const",
"componentsJSON",
"=",
"execFileSync",
"(",
"'php'",
",",
"typo3args",
")",
".",
"toString",
"(",
")",
";",
"const",
"components",
"=",
"JSON",
".",
"parse",
"(",
"componentsJSON",
")",
";",
"for",
"(",
"const",
"component",
"of",
"components",
")",
"{",
"processComponent",
"(",
"component",
")",
";",
"}",
"// Write the general shared context",
"const",
"context",
"=",
"{",
"context",
":",
"{",
"typo3",
":",
"typo3url",
"}",
"}",
";",
"writeFile",
"(",
"path",
".",
"resolve",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"'components.config.json'",
")",
",",
"JSON",
".",
"stringify",
"(",
"context",
",",
"null",
",",
"4",
")",
")",
";",
"// See if there's a component file manifest",
"const",
"manifest",
"=",
"path",
".",
"resolve",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"'components.files.json'",
")",
";",
"try",
"{",
"if",
"(",
"fs",
".",
"statSync",
"(",
"manifest",
")",
".",
"isFile",
"(",
")",
")",
"{",
"const",
"currentFiles",
"=",
"new",
"Set",
"(",
"files",
")",
";",
"const",
"prevFiles",
"=",
"new",
"Set",
"(",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"manifest",
")",
")",
")",
";",
"// Delete all redundant files",
"[",
"...",
"prevFiles",
"]",
".",
"filter",
"(",
"f",
"=>",
"!",
"currentFiles",
".",
"has",
"(",
"f",
")",
")",
".",
"forEach",
"(",
"f",
"=>",
"fs",
".",
"unlinkSync",
"(",
"path",
".",
"resolve",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
",",
"f",
")",
")",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"// Ignore errors",
"}",
"finally",
"{",
"writeFile",
"(",
"manifest",
",",
"JSON",
".",
"stringify",
"(",
"files",
")",
")",
";",
"deleteEmpty",
".",
"sync",
"(",
"app",
".",
"components",
".",
"get",
"(",
"'path'",
")",
")",
";",
"}",
"}",
"done",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"e",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
]
| Update the components by extracting them from a TYPO3 instance
@param {Array} args Arguments
@param {Function} done Callback | [
"Update",
"the",
"components",
"by",
"extracting",
"them",
"from",
"a",
"TYPO3",
"instance"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L222-L270 |
46,480 | tollwerk/fractal-typo3 | index.js | encodeURIParams | function encodeURIParams(params, prefix) {
let parts = [];
for (const name in params) {
if (Object.prototype.hasOwnProperty.call(params, name)) {
const paramName = prefix ? (`${prefix}[${encodeURIComponent(name)}]`) : encodeURIComponent(name);
if (typeof params[name] === 'object') {
parts = Array.prototype.concat.apply(parts,
encodeURIParams(params[name], paramName));
} else {
parts.push(`${paramName}=${encodeURIComponent(params[name])}`);
}
}
}
return parts;
} | javascript | function encodeURIParams(params, prefix) {
let parts = [];
for (const name in params) {
if (Object.prototype.hasOwnProperty.call(params, name)) {
const paramName = prefix ? (`${prefix}[${encodeURIComponent(name)}]`) : encodeURIComponent(name);
if (typeof params[name] === 'object') {
parts = Array.prototype.concat.apply(parts,
encodeURIParams(params[name], paramName));
} else {
parts.push(`${paramName}=${encodeURIComponent(params[name])}`);
}
}
}
return parts;
} | [
"function",
"encodeURIParams",
"(",
"params",
",",
"prefix",
")",
"{",
"let",
"parts",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"name",
"in",
"params",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"params",
",",
"name",
")",
")",
"{",
"const",
"paramName",
"=",
"prefix",
"?",
"(",
"`",
"${",
"prefix",
"}",
"${",
"encodeURIComponent",
"(",
"name",
")",
"}",
"`",
")",
":",
"encodeURIComponent",
"(",
"name",
")",
";",
"if",
"(",
"typeof",
"params",
"[",
"name",
"]",
"===",
"'object'",
")",
"{",
"parts",
"=",
"Array",
".",
"prototype",
".",
"concat",
".",
"apply",
"(",
"parts",
",",
"encodeURIParams",
"(",
"params",
"[",
"name",
"]",
",",
"paramName",
")",
")",
";",
"}",
"else",
"{",
"parts",
".",
"push",
"(",
"`",
"${",
"paramName",
"}",
"${",
"encodeURIComponent",
"(",
"params",
"[",
"name",
"]",
")",
"}",
"`",
")",
";",
"}",
"}",
"}",
"return",
"parts",
";",
"}"
]
| Encode an object as URI parameters
@param {Object} params Parameter object
@param {String} prefix Parameter prefix
@return {Array} Encoded URI parameters | [
"Encode",
"an",
"object",
"as",
"URI",
"parameters"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L279-L293 |
46,481 | tollwerk/fractal-typo3 | index.js | componentGraphUrl | function componentGraphUrl(component) {
const context = ('variants' in component) ? component.variants().default().context : component.context;
const graphUrl = url.parse(context.typo3);
graphUrl.search = `?${encodeURIParams(Object.assign(context.request.arguments, {
tx_twcomponentlibrary_component: { component: context.component },
type: 2401,
})).join('&')}`;
return url.format(graphUrl);
} | javascript | function componentGraphUrl(component) {
const context = ('variants' in component) ? component.variants().default().context : component.context;
const graphUrl = url.parse(context.typo3);
graphUrl.search = `?${encodeURIParams(Object.assign(context.request.arguments, {
tx_twcomponentlibrary_component: { component: context.component },
type: 2401,
})).join('&')}`;
return url.format(graphUrl);
} | [
"function",
"componentGraphUrl",
"(",
"component",
")",
"{",
"const",
"context",
"=",
"(",
"'variants'",
"in",
"component",
")",
"?",
"component",
".",
"variants",
"(",
")",
".",
"default",
"(",
")",
".",
"context",
":",
"component",
".",
"context",
";",
"const",
"graphUrl",
"=",
"url",
".",
"parse",
"(",
"context",
".",
"typo3",
")",
";",
"graphUrl",
".",
"search",
"=",
"`",
"${",
"encodeURIParams",
"(",
"Object",
".",
"assign",
"(",
"context",
".",
"request",
".",
"arguments",
",",
"{",
"tx_twcomponentlibrary_component",
":",
"{",
"component",
":",
"context",
".",
"component",
"}",
",",
"type",
":",
"2401",
",",
"}",
")",
")",
".",
"join",
"(",
"'&'",
")",
"}",
"`",
";",
"return",
"url",
".",
"format",
"(",
"graphUrl",
")",
";",
"}"
]
| Create and return the graph URL for a particular component
@param {Component} component Component | [
"Create",
"and",
"return",
"the",
"graph",
"URL",
"for",
"a",
"particular",
"component"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L300-L308 |
46,482 | tollwerk/fractal-typo3 | index.js | configure | function configure(t3path, t3url, t3theme) {
typo3path = t3path;
typo3url = t3url;
// If a Fractal theme is given
if ((typeof t3theme === 'object') && (typeof t3theme.options === 'function')) {
t3theme.addLoadPath(path.resolve(__dirname, 'lib', 'views'));
// Add the graph panel
const options = t3theme.options();
if (options.panels.indexOf('graph') < 0) {
options.panels.push('graph');
}
t3theme.options(options);
t3theme.addListener('init', (engine) => {
engine._engine.addFilter('componentGraphUrl', componentGraphUrl);
});
}
} | javascript | function configure(t3path, t3url, t3theme) {
typo3path = t3path;
typo3url = t3url;
// If a Fractal theme is given
if ((typeof t3theme === 'object') && (typeof t3theme.options === 'function')) {
t3theme.addLoadPath(path.resolve(__dirname, 'lib', 'views'));
// Add the graph panel
const options = t3theme.options();
if (options.panels.indexOf('graph') < 0) {
options.panels.push('graph');
}
t3theme.options(options);
t3theme.addListener('init', (engine) => {
engine._engine.addFilter('componentGraphUrl', componentGraphUrl);
});
}
} | [
"function",
"configure",
"(",
"t3path",
",",
"t3url",
",",
"t3theme",
")",
"{",
"typo3path",
"=",
"t3path",
";",
"typo3url",
"=",
"t3url",
";",
"// If a Fractal theme is given",
"if",
"(",
"(",
"typeof",
"t3theme",
"===",
"'object'",
")",
"&&",
"(",
"typeof",
"t3theme",
".",
"options",
"===",
"'function'",
")",
")",
"{",
"t3theme",
".",
"addLoadPath",
"(",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'lib'",
",",
"'views'",
")",
")",
";",
"// Add the graph panel",
"const",
"options",
"=",
"t3theme",
".",
"options",
"(",
")",
";",
"if",
"(",
"options",
".",
"panels",
".",
"indexOf",
"(",
"'graph'",
")",
"<",
"0",
")",
"{",
"options",
".",
"panels",
".",
"push",
"(",
"'graph'",
")",
";",
"}",
"t3theme",
".",
"options",
"(",
"options",
")",
";",
"t3theme",
".",
"addListener",
"(",
"'init'",
",",
"(",
"engine",
")",
"=>",
"{",
"engine",
".",
"_engine",
".",
"addFilter",
"(",
"'componentGraphUrl'",
",",
"componentGraphUrl",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Configure the TYPO3 connection
@param {String} t3path TYPO3 default path
@param {String} t3url TYPO3 base URL
@param {Theme} t3theme TYPO3 theme | [
"Configure",
"the",
"TYPO3",
"connection"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L317-L335 |
46,483 | tollwerk/fractal-typo3 | index.js | engine | function engine() {
return {
register(source, gapp) {
const typo3Engine = require('./lib/typo3.js');
const handlebars = require('@frctl/handlebars');
typo3Engine.handlebars = handlebars({}).register(source, gapp);
typo3Engine.handlebars.load();
return new TYPO3Adapter(typo3Engine, source); // , gapp
},
};
} | javascript | function engine() {
return {
register(source, gapp) {
const typo3Engine = require('./lib/typo3.js');
const handlebars = require('@frctl/handlebars');
typo3Engine.handlebars = handlebars({}).register(source, gapp);
typo3Engine.handlebars.load();
return new TYPO3Adapter(typo3Engine, source); // , gapp
},
};
} | [
"function",
"engine",
"(",
")",
"{",
"return",
"{",
"register",
"(",
"source",
",",
"gapp",
")",
"{",
"const",
"typo3Engine",
"=",
"require",
"(",
"'./lib/typo3.js'",
")",
";",
"const",
"handlebars",
"=",
"require",
"(",
"'@frctl/handlebars'",
")",
";",
"typo3Engine",
".",
"handlebars",
"=",
"handlebars",
"(",
"{",
"}",
")",
".",
"register",
"(",
"source",
",",
"gapp",
")",
";",
"typo3Engine",
".",
"handlebars",
".",
"load",
"(",
")",
";",
"return",
"new",
"TYPO3Adapter",
"(",
"typo3Engine",
",",
"source",
")",
";",
"// , gapp",
"}",
",",
"}",
";",
"}"
]
| TYPO3 template engine | [
"TYPO3",
"template",
"engine"
]
| 7a331642e34f8a898895c32c03f81b8aef41ef2b | https://github.com/tollwerk/fractal-typo3/blob/7a331642e34f8a898895c32c03f81b8aef41ef2b/index.js#L363-L373 |
46,484 | chrahunt/tagpro-navmesh | tools/geom/diagonals.js | drawUpperTriangle | function drawUpperTriangle(d, loc) {
if (d == "r") {
var first = {x: 50, y: 0};
var second = {x: 50, y: 50};
} else {
var first = {x: 50, y: 0};
var second = {x: 0, y: 50};
}
context.beginPath();
context.moveTo(loc.x, loc.y);
context.lineTo(loc.x + first.x, loc.y + first.y);
context.lineTo(loc.x + second.x, loc.y + second.y);
context.lineTo(loc.x, loc.y);
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();
context.fillStyle = fill;
context.fill();
context.closePath();
} | javascript | function drawUpperTriangle(d, loc) {
if (d == "r") {
var first = {x: 50, y: 0};
var second = {x: 50, y: 50};
} else {
var first = {x: 50, y: 0};
var second = {x: 0, y: 50};
}
context.beginPath();
context.moveTo(loc.x, loc.y);
context.lineTo(loc.x + first.x, loc.y + first.y);
context.lineTo(loc.x + second.x, loc.y + second.y);
context.lineTo(loc.x, loc.y);
context.lineWidth = 1;
context.strokeStyle = 'black';
context.stroke();
context.fillStyle = fill;
context.fill();
context.closePath();
} | [
"function",
"drawUpperTriangle",
"(",
"d",
",",
"loc",
")",
"{",
"if",
"(",
"d",
"==",
"\"r\"",
")",
"{",
"var",
"first",
"=",
"{",
"x",
":",
"50",
",",
"y",
":",
"0",
"}",
";",
"var",
"second",
"=",
"{",
"x",
":",
"50",
",",
"y",
":",
"50",
"}",
";",
"}",
"else",
"{",
"var",
"first",
"=",
"{",
"x",
":",
"50",
",",
"y",
":",
"0",
"}",
";",
"var",
"second",
"=",
"{",
"x",
":",
"0",
",",
"y",
":",
"50",
"}",
";",
"}",
"context",
".",
"beginPath",
"(",
")",
";",
"context",
".",
"moveTo",
"(",
"loc",
".",
"x",
",",
"loc",
".",
"y",
")",
";",
"context",
".",
"lineTo",
"(",
"loc",
".",
"x",
"+",
"first",
".",
"x",
",",
"loc",
".",
"y",
"+",
"first",
".",
"y",
")",
";",
"context",
".",
"lineTo",
"(",
"loc",
".",
"x",
"+",
"second",
".",
"x",
",",
"loc",
".",
"y",
"+",
"second",
".",
"y",
")",
";",
"context",
".",
"lineTo",
"(",
"loc",
".",
"x",
",",
"loc",
".",
"y",
")",
";",
"context",
".",
"lineWidth",
"=",
"1",
";",
"context",
".",
"strokeStyle",
"=",
"'black'",
";",
"context",
".",
"stroke",
"(",
")",
";",
"context",
".",
"fillStyle",
"=",
"fill",
";",
"context",
".",
"fill",
"(",
")",
";",
"context",
".",
"closePath",
"(",
")",
";",
"}"
]
| draw upper triangle going certain direction at location | [
"draw",
"upper",
"triangle",
"going",
"certain",
"direction",
"at",
"location"
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/tools/geom/diagonals.js#L210-L229 |
46,485 | chrahunt/tagpro-navmesh | tools/geom/diagonals.js | drawBadCells | function drawBadCells(cells) {
var context = c.getContext('2d');
var canvas = c; // from global.
// Drawing bad cells
var draw_loc = {x: 0, y: 0};
for (var i = 0; i < cells.length; i++) {
var cell_info = cells[i];
var cell = cell_info[0];
var matched_entrances = cell_info[1];
var matched_exits = cell_info[2]
// Write information.
context.fillStyle = 'black';
context.fillText(cell.toString(), draw_loc.x + 5, draw_loc.y + 10)
context.fillText("ents:" + matched_entrances.length, draw_loc.x + 5, draw_loc.y + 20)
context.fillText("exts:" + matched_exits.length, draw_loc.x + 5, draw_loc.y + 35)
drawCell(cell, canvas, {x: draw_loc.x + text_width, y: draw_loc.y});
// Increment drawing location.
if ((i % 5) == 4) {
draw_loc = {x: 0, y: draw_loc.y + total_width};
} else {
draw_loc = {x: draw_loc.x + total_width, y: draw_loc.y};
}
}
} | javascript | function drawBadCells(cells) {
var context = c.getContext('2d');
var canvas = c; // from global.
// Drawing bad cells
var draw_loc = {x: 0, y: 0};
for (var i = 0; i < cells.length; i++) {
var cell_info = cells[i];
var cell = cell_info[0];
var matched_entrances = cell_info[1];
var matched_exits = cell_info[2]
// Write information.
context.fillStyle = 'black';
context.fillText(cell.toString(), draw_loc.x + 5, draw_loc.y + 10)
context.fillText("ents:" + matched_entrances.length, draw_loc.x + 5, draw_loc.y + 20)
context.fillText("exts:" + matched_exits.length, draw_loc.x + 5, draw_loc.y + 35)
drawCell(cell, canvas, {x: draw_loc.x + text_width, y: draw_loc.y});
// Increment drawing location.
if ((i % 5) == 4) {
draw_loc = {x: 0, y: draw_loc.y + total_width};
} else {
draw_loc = {x: draw_loc.x + total_width, y: draw_loc.y};
}
}
} | [
"function",
"drawBadCells",
"(",
"cells",
")",
"{",
"var",
"context",
"=",
"c",
".",
"getContext",
"(",
"'2d'",
")",
";",
"var",
"canvas",
"=",
"c",
";",
"// from global.",
"// Drawing bad cells",
"var",
"draw_loc",
"=",
"{",
"x",
":",
"0",
",",
"y",
":",
"0",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cells",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"cell_info",
"=",
"cells",
"[",
"i",
"]",
";",
"var",
"cell",
"=",
"cell_info",
"[",
"0",
"]",
";",
"var",
"matched_entrances",
"=",
"cell_info",
"[",
"1",
"]",
";",
"var",
"matched_exits",
"=",
"cell_info",
"[",
"2",
"]",
"// Write information.",
"context",
".",
"fillStyle",
"=",
"'black'",
";",
"context",
".",
"fillText",
"(",
"cell",
".",
"toString",
"(",
")",
",",
"draw_loc",
".",
"x",
"+",
"5",
",",
"draw_loc",
".",
"y",
"+",
"10",
")",
"context",
".",
"fillText",
"(",
"\"ents:\"",
"+",
"matched_entrances",
".",
"length",
",",
"draw_loc",
".",
"x",
"+",
"5",
",",
"draw_loc",
".",
"y",
"+",
"20",
")",
"context",
".",
"fillText",
"(",
"\"exts:\"",
"+",
"matched_exits",
".",
"length",
",",
"draw_loc",
".",
"x",
"+",
"5",
",",
"draw_loc",
".",
"y",
"+",
"35",
")",
"drawCell",
"(",
"cell",
",",
"canvas",
",",
"{",
"x",
":",
"draw_loc",
".",
"x",
"+",
"text_width",
",",
"y",
":",
"draw_loc",
".",
"y",
"}",
")",
";",
"// Increment drawing location.",
"if",
"(",
"(",
"i",
"%",
"5",
")",
"==",
"4",
")",
"{",
"draw_loc",
"=",
"{",
"x",
":",
"0",
",",
"y",
":",
"draw_loc",
".",
"y",
"+",
"total_width",
"}",
";",
"}",
"else",
"{",
"draw_loc",
"=",
"{",
"x",
":",
"draw_loc",
".",
"x",
"+",
"total_width",
",",
"y",
":",
"draw_loc",
".",
"y",
"}",
";",
"}",
"}",
"}"
]
| Function for drawing the cells that were unmatched. | [
"Function",
"for",
"drawing",
"the",
"cells",
"that",
"were",
"unmatched",
"."
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/tools/geom/diagonals.js#L437-L462 |
46,486 | chrahunt/tagpro-navmesh | tools/geom/diagonals.js | getIndexForLoc | function getIndexForLoc(loc) {
var col = Math.floor(loc.x / total_width);
var row = Math.floor(loc.y / total_width);
var index = col + (row * 5);
return index;
} | javascript | function getIndexForLoc(loc) {
var col = Math.floor(loc.x / total_width);
var row = Math.floor(loc.y / total_width);
var index = col + (row * 5);
return index;
} | [
"function",
"getIndexForLoc",
"(",
"loc",
")",
"{",
"var",
"col",
"=",
"Math",
".",
"floor",
"(",
"loc",
".",
"x",
"/",
"total_width",
")",
";",
"var",
"row",
"=",
"Math",
".",
"floor",
"(",
"loc",
".",
"y",
"/",
"total_width",
")",
";",
"var",
"index",
"=",
"col",
"+",
"(",
"row",
"*",
"5",
")",
";",
"return",
"index",
";",
"}"
]
| Given a location, return the index of the element that is present at that location. If it doesn't correspond to a good index, then it is -1. | [
"Given",
"a",
"location",
"return",
"the",
"index",
"of",
"the",
"element",
"that",
"is",
"present",
"at",
"that",
"location",
".",
"If",
"it",
"doesn",
"t",
"correspond",
"to",
"a",
"good",
"index",
"then",
"it",
"is",
"-",
"1",
"."
]
| b50fbdad1061fb4760ac22ee756f34ab3e177539 | https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/tools/geom/diagonals.js#L485-L490 |
46,487 | pbeardshear/Tycho | lib/tycho.js | handleIncomingMessage | function handleIncomingMessage(event, message, source) {
var blocks = event.split(':'),
id = blocks[2] || blocks[1];
if (id in self.transactions && source in self.transactions[id]) {
self.transactions[id][source].resolve([message, source]);
}
} | javascript | function handleIncomingMessage(event, message, source) {
var blocks = event.split(':'),
id = blocks[2] || blocks[1];
if (id in self.transactions && source in self.transactions[id]) {
self.transactions[id][source].resolve([message, source]);
}
} | [
"function",
"handleIncomingMessage",
"(",
"event",
",",
"message",
",",
"source",
")",
"{",
"var",
"blocks",
"=",
"event",
".",
"split",
"(",
"':'",
")",
",",
"id",
"=",
"blocks",
"[",
"2",
"]",
"||",
"blocks",
"[",
"1",
"]",
";",
"if",
"(",
"id",
"in",
"self",
".",
"transactions",
"&&",
"source",
"in",
"self",
".",
"transactions",
"[",
"id",
"]",
")",
"{",
"self",
".",
"transactions",
"[",
"id",
"]",
"[",
"source",
"]",
".",
"resolve",
"(",
"[",
"message",
",",
"source",
"]",
")",
";",
"}",
"}"
]
| Handler for messages from the store | [
"Handler",
"for",
"messages",
"from",
"the",
"store"
]
| 11ff1b9bda5044edb575d58c3b5533335c7b5d88 | https://github.com/pbeardshear/Tycho/blob/11ff1b9bda5044edb575d58c3b5533335c7b5d88/lib/tycho.js#L53-L59 |
46,488 | pbeardshear/Tycho | lib/tycho.js | handleControlConnection | function handleControlConnection(connection) {
connection.on('data', function (data) {
console.log('Got command:', data.toString().trim());
var request = data.toString().trim().split(' '),
cmd = request[0],
target = request[1],
newline = '\r\n',
response;
console.log('Command is:', cmd);
switch (cmd) {
case 'start':
console.log('got here');
self.store.broadcast('worker:start', target);
response = lib.format('Starting {0} servers.', (target || 'all'));
break;
case 'pause':
self.store.broadcast('worker:pause', target);
response = lib.format('Pausing {0} servers.', (target || 'all'));
break;
case 'stop':
self.store.broadcast('worker:stop', target);
response = lib.format('Stopping {0} servers.', (target || 'all'));
break;
case 'resume':
self.store.broadcast('worker:resume', target);
response = lib.format('Resuming {0} servers.', (target || 'all'));
break;
case 'heartbeat':
var id = lib.guid();
self.store.broadcast('worker:heartbeat', id);
wait(id, function () {
var args = Array.prototype.slice.call(arguments),
response = {};
lib.each(args, function (data) {
var message = data[0],
worker = data[1];
response[worker] = message;
});
connection.write(JSON.stringify(response));
connection.end(newline);
});
break;
case 'stats':
var id = lib.guid();
self.store.broadcast('worker:stats', id);
wait(id, function () {
var args = Array.prototype.slice.call(arguments),
response = {};
lib.each(args, function (data) {
var message = data[0],
worker = data[1];
response[worker] = message;
});
connection.write(JSON.stringify(response));
connection.end(newline);
});
break;
default:
response = lib.format('Unknown command: {0}.', cmd);
break;
}
if (response) {
connection.write(response);
connection.end(newline);
}
});
} | javascript | function handleControlConnection(connection) {
connection.on('data', function (data) {
console.log('Got command:', data.toString().trim());
var request = data.toString().trim().split(' '),
cmd = request[0],
target = request[1],
newline = '\r\n',
response;
console.log('Command is:', cmd);
switch (cmd) {
case 'start':
console.log('got here');
self.store.broadcast('worker:start', target);
response = lib.format('Starting {0} servers.', (target || 'all'));
break;
case 'pause':
self.store.broadcast('worker:pause', target);
response = lib.format('Pausing {0} servers.', (target || 'all'));
break;
case 'stop':
self.store.broadcast('worker:stop', target);
response = lib.format('Stopping {0} servers.', (target || 'all'));
break;
case 'resume':
self.store.broadcast('worker:resume', target);
response = lib.format('Resuming {0} servers.', (target || 'all'));
break;
case 'heartbeat':
var id = lib.guid();
self.store.broadcast('worker:heartbeat', id);
wait(id, function () {
var args = Array.prototype.slice.call(arguments),
response = {};
lib.each(args, function (data) {
var message = data[0],
worker = data[1];
response[worker] = message;
});
connection.write(JSON.stringify(response));
connection.end(newline);
});
break;
case 'stats':
var id = lib.guid();
self.store.broadcast('worker:stats', id);
wait(id, function () {
var args = Array.prototype.slice.call(arguments),
response = {};
lib.each(args, function (data) {
var message = data[0],
worker = data[1];
response[worker] = message;
});
connection.write(JSON.stringify(response));
connection.end(newline);
});
break;
default:
response = lib.format('Unknown command: {0}.', cmd);
break;
}
if (response) {
connection.write(response);
connection.end(newline);
}
});
} | [
"function",
"handleControlConnection",
"(",
"connection",
")",
"{",
"connection",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"console",
".",
"log",
"(",
"'Got command:'",
",",
"data",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
")",
";",
"var",
"request",
"=",
"data",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
".",
"split",
"(",
"' '",
")",
",",
"cmd",
"=",
"request",
"[",
"0",
"]",
",",
"target",
"=",
"request",
"[",
"1",
"]",
",",
"newline",
"=",
"'\\r\\n'",
",",
"response",
";",
"console",
".",
"log",
"(",
"'Command is:'",
",",
"cmd",
")",
";",
"switch",
"(",
"cmd",
")",
"{",
"case",
"'start'",
":",
"console",
".",
"log",
"(",
"'got here'",
")",
";",
"self",
".",
"store",
".",
"broadcast",
"(",
"'worker:start'",
",",
"target",
")",
";",
"response",
"=",
"lib",
".",
"format",
"(",
"'Starting {0} servers.'",
",",
"(",
"target",
"||",
"'all'",
")",
")",
";",
"break",
";",
"case",
"'pause'",
":",
"self",
".",
"store",
".",
"broadcast",
"(",
"'worker:pause'",
",",
"target",
")",
";",
"response",
"=",
"lib",
".",
"format",
"(",
"'Pausing {0} servers.'",
",",
"(",
"target",
"||",
"'all'",
")",
")",
";",
"break",
";",
"case",
"'stop'",
":",
"self",
".",
"store",
".",
"broadcast",
"(",
"'worker:stop'",
",",
"target",
")",
";",
"response",
"=",
"lib",
".",
"format",
"(",
"'Stopping {0} servers.'",
",",
"(",
"target",
"||",
"'all'",
")",
")",
";",
"break",
";",
"case",
"'resume'",
":",
"self",
".",
"store",
".",
"broadcast",
"(",
"'worker:resume'",
",",
"target",
")",
";",
"response",
"=",
"lib",
".",
"format",
"(",
"'Resuming {0} servers.'",
",",
"(",
"target",
"||",
"'all'",
")",
")",
";",
"break",
";",
"case",
"'heartbeat'",
":",
"var",
"id",
"=",
"lib",
".",
"guid",
"(",
")",
";",
"self",
".",
"store",
".",
"broadcast",
"(",
"'worker:heartbeat'",
",",
"id",
")",
";",
"wait",
"(",
"id",
",",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"response",
"=",
"{",
"}",
";",
"lib",
".",
"each",
"(",
"args",
",",
"function",
"(",
"data",
")",
"{",
"var",
"message",
"=",
"data",
"[",
"0",
"]",
",",
"worker",
"=",
"data",
"[",
"1",
"]",
";",
"response",
"[",
"worker",
"]",
"=",
"message",
";",
"}",
")",
";",
"connection",
".",
"write",
"(",
"JSON",
".",
"stringify",
"(",
"response",
")",
")",
";",
"connection",
".",
"end",
"(",
"newline",
")",
";",
"}",
")",
";",
"break",
";",
"case",
"'stats'",
":",
"var",
"id",
"=",
"lib",
".",
"guid",
"(",
")",
";",
"self",
".",
"store",
".",
"broadcast",
"(",
"'worker:stats'",
",",
"id",
")",
";",
"wait",
"(",
"id",
",",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"response",
"=",
"{",
"}",
";",
"lib",
".",
"each",
"(",
"args",
",",
"function",
"(",
"data",
")",
"{",
"var",
"message",
"=",
"data",
"[",
"0",
"]",
",",
"worker",
"=",
"data",
"[",
"1",
"]",
";",
"response",
"[",
"worker",
"]",
"=",
"message",
";",
"}",
")",
";",
"connection",
".",
"write",
"(",
"JSON",
".",
"stringify",
"(",
"response",
")",
")",
";",
"connection",
".",
"end",
"(",
"newline",
")",
";",
"}",
")",
";",
"break",
";",
"default",
":",
"response",
"=",
"lib",
".",
"format",
"(",
"'Unknown command: {0}.'",
",",
"cmd",
")",
";",
"break",
";",
"}",
"if",
"(",
"response",
")",
"{",
"connection",
".",
"write",
"(",
"response",
")",
";",
"connection",
".",
"end",
"(",
"newline",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Handler for new connections to the control server
Also defines the valid commands that can be issued to workers | [
"Handler",
"for",
"new",
"connections",
"to",
"the",
"control",
"server",
"Also",
"defines",
"the",
"valid",
"commands",
"that",
"can",
"be",
"issued",
"to",
"workers"
]
| 11ff1b9bda5044edb575d58c3b5533335c7b5d88 | https://github.com/pbeardshear/Tycho/blob/11ff1b9bda5044edb575d58c3b5533335c7b5d88/lib/tycho.js#L65-L131 |
46,489 | pbeardshear/Tycho | lib/tycho.js | handleWorkerRestart | function handleWorkerRestart(worker, code, signal) {
delete self.workers[worker.id];
if (self.reviveWorkers) {
var zombie = cluster.fork({
config: JSON.stringify(self.config)
});
self.workers[zombie.id] = zombie;
}
} | javascript | function handleWorkerRestart(worker, code, signal) {
delete self.workers[worker.id];
if (self.reviveWorkers) {
var zombie = cluster.fork({
config: JSON.stringify(self.config)
});
self.workers[zombie.id] = zombie;
}
} | [
"function",
"handleWorkerRestart",
"(",
"worker",
",",
"code",
",",
"signal",
")",
"{",
"delete",
"self",
".",
"workers",
"[",
"worker",
".",
"id",
"]",
";",
"if",
"(",
"self",
".",
"reviveWorkers",
")",
"{",
"var",
"zombie",
"=",
"cluster",
".",
"fork",
"(",
"{",
"config",
":",
"JSON",
".",
"stringify",
"(",
"self",
".",
"config",
")",
"}",
")",
";",
"self",
".",
"workers",
"[",
"zombie",
".",
"id",
"]",
"=",
"zombie",
";",
"}",
"}"
]
| Restart a worker when one goes offline | [
"Restart",
"a",
"worker",
"when",
"one",
"goes",
"offline"
]
| 11ff1b9bda5044edb575d58c3b5533335c7b5d88 | https://github.com/pbeardshear/Tycho/blob/11ff1b9bda5044edb575d58c3b5533335c7b5d88/lib/tycho.js#L136-L144 |
46,490 | pbeardshear/Tycho | lib/tycho.js | wait | function wait(id, callback) {
var promises = [];
self.transactions[id] = {};
lib.each(self.workers, function (worker) {
var deferred = Q.defer();
self.transactions[id][worker.id] = deferred;
promises.push(deferred.promise);
});
Q.spread(promises, callback);
} | javascript | function wait(id, callback) {
var promises = [];
self.transactions[id] = {};
lib.each(self.workers, function (worker) {
var deferred = Q.defer();
self.transactions[id][worker.id] = deferred;
promises.push(deferred.promise);
});
Q.spread(promises, callback);
} | [
"function",
"wait",
"(",
"id",
",",
"callback",
")",
"{",
"var",
"promises",
"=",
"[",
"]",
";",
"self",
".",
"transactions",
"[",
"id",
"]",
"=",
"{",
"}",
";",
"lib",
".",
"each",
"(",
"self",
".",
"workers",
",",
"function",
"(",
"worker",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"self",
".",
"transactions",
"[",
"id",
"]",
"[",
"worker",
".",
"id",
"]",
"=",
"deferred",
";",
"promises",
".",
"push",
"(",
"deferred",
".",
"promise",
")",
";",
"}",
")",
";",
"Q",
".",
"spread",
"(",
"promises",
",",
"callback",
")",
";",
"}"
]
| Create a transaction which resolves when a response
is heard from each active worker | [
"Create",
"a",
"transaction",
"which",
"resolves",
"when",
"a",
"response",
"is",
"heard",
"from",
"each",
"active",
"worker"
]
| 11ff1b9bda5044edb575d58c3b5533335c7b5d88 | https://github.com/pbeardshear/Tycho/blob/11ff1b9bda5044edb575d58c3b5533335c7b5d88/lib/tycho.js#L150-L161 |
46,491 | reklatsmasters/ip2buf | index.js | pton | function pton(af, addr, dest, index) {
switch (af) {
case IPV4_OCTETS:
return pton4(addr, dest, index)
case IPV6_OCTETS:
return pton6(addr, dest, index)
default:
throw new Error('Unsupported ip address.')
}
} | javascript | function pton(af, addr, dest, index) {
switch (af) {
case IPV4_OCTETS:
return pton4(addr, dest, index)
case IPV6_OCTETS:
return pton6(addr, dest, index)
default:
throw new Error('Unsupported ip address.')
}
} | [
"function",
"pton",
"(",
"af",
",",
"addr",
",",
"dest",
",",
"index",
")",
"{",
"switch",
"(",
"af",
")",
"{",
"case",
"IPV4_OCTETS",
":",
"return",
"pton4",
"(",
"addr",
",",
"dest",
",",
"index",
")",
"case",
"IPV6_OCTETS",
":",
"return",
"pton6",
"(",
"addr",
",",
"dest",
",",
"index",
")",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Unsupported ip address.'",
")",
"}",
"}"
]
| Convert ip address to the Buffer.
@param {number} af - type of an address.
@param {string} addr - source address.
@param {Buffer} [dest] - target buffer.
@param {number} [index] - start position in the target buffer. | [
"Convert",
"ip",
"address",
"to",
"the",
"Buffer",
"."
]
| 439c55cc7605423929808d42a29b9cd284914cd6 | https://github.com/reklatsmasters/ip2buf/blob/439c55cc7605423929808d42a29b9cd284914cd6/index.js#L27-L36 |
46,492 | sbarwe/node-red-contrib-contextbrowser | contextbrowser.js | copycontext | function copycontext(context) {
var t = {};
var keys = context.keys();
var i = keys.length;
var k, v, j;
while (i--) {
k = keys[i];
if (k[0] == '_')
continue;
v = context.get(k);
if (v && {}.toString.call(v) === '[object Function]')
continue;
try {
j = JSON.stringify(v);
t[k] = JSON.parse(j);
} catch(err) {
t[k] = "Exception: " + err;
}
}
return t;
} | javascript | function copycontext(context) {
var t = {};
var keys = context.keys();
var i = keys.length;
var k, v, j;
while (i--) {
k = keys[i];
if (k[0] == '_')
continue;
v = context.get(k);
if (v && {}.toString.call(v) === '[object Function]')
continue;
try {
j = JSON.stringify(v);
t[k] = JSON.parse(j);
} catch(err) {
t[k] = "Exception: " + err;
}
}
return t;
} | [
"function",
"copycontext",
"(",
"context",
")",
"{",
"var",
"t",
"=",
"{",
"}",
";",
"var",
"keys",
"=",
"context",
".",
"keys",
"(",
")",
";",
"var",
"i",
"=",
"keys",
".",
"length",
";",
"var",
"k",
",",
"v",
",",
"j",
";",
"while",
"(",
"i",
"--",
")",
"{",
"k",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"k",
"[",
"0",
"]",
"==",
"'_'",
")",
"continue",
";",
"v",
"=",
"context",
".",
"get",
"(",
"k",
")",
";",
"if",
"(",
"v",
"&&",
"{",
"}",
".",
"toString",
".",
"call",
"(",
"v",
")",
"===",
"'[object Function]'",
")",
"continue",
";",
"try",
"{",
"j",
"=",
"JSON",
".",
"stringify",
"(",
"v",
")",
";",
"t",
"[",
"k",
"]",
"=",
"JSON",
".",
"parse",
"(",
"j",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"t",
"[",
"k",
"]",
"=",
"\"Exception: \"",
"+",
"err",
";",
"}",
"}",
"return",
"t",
";",
"}"
]
| prepare context object for serialization | [
"prepare",
"context",
"object",
"for",
"serialization"
]
| 38db41ad015334eb662dd95413236dd546c753e5 | https://github.com/sbarwe/node-red-contrib-contextbrowser/blob/38db41ad015334eb662dd95413236dd546c753e5/contextbrowser.js#L32-L54 |
46,493 | thlorenz/ps-aux | index.js | parseLine | function parseLine(line) {
// except for the command, no field has a space, so we split by that and piece the command back together
var parts = line.split(/ +/);
return {
user : parts[0]
, pid : parseInt(parts[1])
, '%cpu' : parseFloat(parts[2])
, '%mem' : parseFloat(parts[3])
, vsz : parseInt(parts[4])
, rss : parseInt(parts[5])
, tty : parts[6]
, state : parts[7]
, started : parts[8]
, time : parts[9]
, command : parts.slice(10).join(' ')
}
} | javascript | function parseLine(line) {
// except for the command, no field has a space, so we split by that and piece the command back together
var parts = line.split(/ +/);
return {
user : parts[0]
, pid : parseInt(parts[1])
, '%cpu' : parseFloat(parts[2])
, '%mem' : parseFloat(parts[3])
, vsz : parseInt(parts[4])
, rss : parseInt(parts[5])
, tty : parts[6]
, state : parts[7]
, started : parts[8]
, time : parts[9]
, command : parts.slice(10).join(' ')
}
} | [
"function",
"parseLine",
"(",
"line",
")",
"{",
"// except for the command, no field has a space, so we split by that and piece the command back together",
"var",
"parts",
"=",
"line",
".",
"split",
"(",
"/",
" +",
"/",
")",
";",
"return",
"{",
"user",
":",
"parts",
"[",
"0",
"]",
",",
"pid",
":",
"parseInt",
"(",
"parts",
"[",
"1",
"]",
")",
",",
"'%cpu'",
":",
"parseFloat",
"(",
"parts",
"[",
"2",
"]",
")",
",",
"'%mem'",
":",
"parseFloat",
"(",
"parts",
"[",
"3",
"]",
")",
",",
"vsz",
":",
"parseInt",
"(",
"parts",
"[",
"4",
"]",
")",
",",
"rss",
":",
"parseInt",
"(",
"parts",
"[",
"5",
"]",
")",
",",
"tty",
":",
"parts",
"[",
"6",
"]",
",",
"state",
":",
"parts",
"[",
"7",
"]",
",",
"started",
":",
"parts",
"[",
"8",
"]",
",",
"time",
":",
"parts",
"[",
"9",
"]",
",",
"command",
":",
"parts",
".",
"slice",
"(",
"10",
")",
".",
"join",
"(",
"' '",
")",
"}",
"}"
]
| Parses out process info from a given `ps aux` line.
@name parseLine
@private
@function
@param {string} line the raw info for the given process
@return {Object} with parsed out process info | [
"Parses",
"out",
"process",
"info",
"from",
"a",
"given",
"ps",
"aux",
"line",
"."
]
| 482b1fea2a8924313196113c488f334c5a2bfed9 | https://github.com/thlorenz/ps-aux/blob/482b1fea2a8924313196113c488f334c5a2bfed9/index.js#L16-L32 |
46,494 | d-oliveros/isomorphine | src/client/createProxiedMethod.js | proxiedMethod | function proxiedMethod(params, path) {
// Get the arguments that should be passed to the server
var payload = Array.prototype.slice.call(arguments).slice(2);
// Save the callback function for later use
var callback = util.firstFunction(payload);
// Transform the callback function in the arguments into a special key
// that will be used in the server to signal the client-side callback call
payload = util.serializeCallback(payload);
var endpoint = buildEndpoint(params, path);
if (callback) {
return doRequest(endpoint, payload, params, callback);
} else {
return util.promisify(doRequest)(endpoint, payload, params);
}
} | javascript | function proxiedMethod(params, path) {
// Get the arguments that should be passed to the server
var payload = Array.prototype.slice.call(arguments).slice(2);
// Save the callback function for later use
var callback = util.firstFunction(payload);
// Transform the callback function in the arguments into a special key
// that will be used in the server to signal the client-side callback call
payload = util.serializeCallback(payload);
var endpoint = buildEndpoint(params, path);
if (callback) {
return doRequest(endpoint, payload, params, callback);
} else {
return util.promisify(doRequest)(endpoint, payload, params);
}
} | [
"function",
"proxiedMethod",
"(",
"params",
",",
"path",
")",
"{",
"// Get the arguments that should be passed to the server",
"var",
"payload",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"slice",
"(",
"2",
")",
";",
"// Save the callback function for later use",
"var",
"callback",
"=",
"util",
".",
"firstFunction",
"(",
"payload",
")",
";",
"// Transform the callback function in the arguments into a special key",
"// that will be used in the server to signal the client-side callback call",
"payload",
"=",
"util",
".",
"serializeCallback",
"(",
"payload",
")",
";",
"var",
"endpoint",
"=",
"buildEndpoint",
"(",
"params",
",",
"path",
")",
";",
"if",
"(",
"callback",
")",
"{",
"return",
"doRequest",
"(",
"endpoint",
",",
"payload",
",",
"params",
",",
"callback",
")",
";",
"}",
"else",
"{",
"return",
"util",
".",
"promisify",
"(",
"doRequest",
")",
"(",
"endpoint",
",",
"payload",
",",
"params",
")",
";",
"}",
"}"
]
| Serializes the parameters sent in the function's call,
and sends a POST request to isomorphine's endpoint in the server.
@param {Object} params The server's configuration and error handlers.
@param {Object} path The path to the serverside method to be called. | [
"Serializes",
"the",
"parameters",
"sent",
"in",
"the",
"function",
"s",
"call",
"and",
"sends",
"a",
"POST",
"request",
"to",
"isomorphine",
"s",
"endpoint",
"in",
"the",
"server",
"."
]
| cb123d16b4be3bb7ec57758bd0b2e43767e91864 | https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/client/createProxiedMethod.js#L32-L51 |
46,495 | d-oliveros/isomorphine | src/client/createProxiedMethod.js | doRequest | function doRequest(endpoint, payload, params, callback) {
debug('Calling API endpoint: ' + endpoint + '.');
request
.post(endpoint)
.send({ payload: payload })
.set('Accept', 'application/json')
.end(function(err, res) {
if ((!res || !res.body) && !err) {
err = new Error('No response from server. ' +
'(Hint: Have you mounted isomorphine.router() in your app?)');
}
if (err) {
return handleError(err, params, callback);
}
var values = res.body.values;
if (!values || values.constructor !== Array) {
err = new Error('Fetched payload is not an array.');
return handleError(err, params, callback);
}
debug('Resolving callback with ' + JSON.stringify(values, null, 3));
// Sets the error argument to null
values.unshift(null);
callback.apply(this, values);
});
} | javascript | function doRequest(endpoint, payload, params, callback) {
debug('Calling API endpoint: ' + endpoint + '.');
request
.post(endpoint)
.send({ payload: payload })
.set('Accept', 'application/json')
.end(function(err, res) {
if ((!res || !res.body) && !err) {
err = new Error('No response from server. ' +
'(Hint: Have you mounted isomorphine.router() in your app?)');
}
if (err) {
return handleError(err, params, callback);
}
var values = res.body.values;
if (!values || values.constructor !== Array) {
err = new Error('Fetched payload is not an array.');
return handleError(err, params, callback);
}
debug('Resolving callback with ' + JSON.stringify(values, null, 3));
// Sets the error argument to null
values.unshift(null);
callback.apply(this, values);
});
} | [
"function",
"doRequest",
"(",
"endpoint",
",",
"payload",
",",
"params",
",",
"callback",
")",
"{",
"debug",
"(",
"'Calling API endpoint: '",
"+",
"endpoint",
"+",
"'.'",
")",
";",
"request",
".",
"post",
"(",
"endpoint",
")",
".",
"send",
"(",
"{",
"payload",
":",
"payload",
"}",
")",
".",
"set",
"(",
"'Accept'",
",",
"'application/json'",
")",
".",
"end",
"(",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"(",
"!",
"res",
"||",
"!",
"res",
".",
"body",
")",
"&&",
"!",
"err",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"'No response from server. '",
"+",
"'(Hint: Have you mounted isomorphine.router() in your app?)'",
")",
";",
"}",
"if",
"(",
"err",
")",
"{",
"return",
"handleError",
"(",
"err",
",",
"params",
",",
"callback",
")",
";",
"}",
"var",
"values",
"=",
"res",
".",
"body",
".",
"values",
";",
"if",
"(",
"!",
"values",
"||",
"values",
".",
"constructor",
"!==",
"Array",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"'Fetched payload is not an array.'",
")",
";",
"return",
"handleError",
"(",
"err",
",",
"params",
",",
"callback",
")",
";",
"}",
"debug",
"(",
"'Resolving callback with '",
"+",
"JSON",
".",
"stringify",
"(",
"values",
",",
"null",
",",
"3",
")",
")",
";",
"// Sets the error argument to null",
"values",
".",
"unshift",
"(",
"null",
")",
";",
"callback",
".",
"apply",
"(",
"this",
",",
"values",
")",
";",
"}",
")",
";",
"}"
]
| Runs a request to an isomorphine's endpoint with the provided payload.
@param {String} endpoint The endpoint to request.
@param {Array} payload The arguments to send.
@param {Object} params The server's configuration and error handlers.
@param {Function} callback The callback function to call afterwards. | [
"Runs",
"a",
"request",
"to",
"an",
"isomorphine",
"s",
"endpoint",
"with",
"the",
"provided",
"payload",
"."
]
| cb123d16b4be3bb7ec57758bd0b2e43767e91864 | https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/client/createProxiedMethod.js#L61-L92 |
46,496 | d-oliveros/isomorphine | src/client/createProxiedMethod.js | buildEndpoint | function buildEndpoint(config, path) {
var host = config.host;
var port = config.port;
if (!host) throw new Error('No host is specified in proxied method config');
var base = host + (port ? ':' + port : '');
var fullpath = '/isomorphine/' + path;
var endpoint = base + fullpath;
debug('Built endpoint: ' + endpoint);
return endpoint;
} | javascript | function buildEndpoint(config, path) {
var host = config.host;
var port = config.port;
if (!host) throw new Error('No host is specified in proxied method config');
var base = host + (port ? ':' + port : '');
var fullpath = '/isomorphine/' + path;
var endpoint = base + fullpath;
debug('Built endpoint: ' + endpoint);
return endpoint;
} | [
"function",
"buildEndpoint",
"(",
"config",
",",
"path",
")",
"{",
"var",
"host",
"=",
"config",
".",
"host",
";",
"var",
"port",
"=",
"config",
".",
"port",
";",
"if",
"(",
"!",
"host",
")",
"throw",
"new",
"Error",
"(",
"'No host is specified in proxied method config'",
")",
";",
"var",
"base",
"=",
"host",
"+",
"(",
"port",
"?",
"':'",
"+",
"port",
":",
"''",
")",
";",
"var",
"fullpath",
"=",
"'/isomorphine/'",
"+",
"path",
";",
"var",
"endpoint",
"=",
"base",
"+",
"fullpath",
";",
"debug",
"(",
"'Built endpoint: '",
"+",
"endpoint",
")",
";",
"return",
"endpoint",
";",
"}"
]
| Builds a method's API endpoint.
@param {Object} config The host and port parameters to use.
@param {String} path The path to the serverside method.
@return {String} The endpoint to request. | [
"Builds",
"a",
"method",
"s",
"API",
"endpoint",
"."
]
| cb123d16b4be3bb7ec57758bd0b2e43767e91864 | https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/client/createProxiedMethod.js#L116-L129 |
46,497 | othiym23/async-some | some.js | some | function some (list, test, cb) {
assert("length" in list, "array must be arraylike")
assert.equal(typeof test, "function", "predicate must be callable")
assert.equal(typeof cb, "function", "callback must be callable")
var array = slice(list)
, index = 0
, length = array.length
, hecomes = dezalgoify(cb)
map()
function map () {
if (index >= length) return hecomes(null, false)
test(array[index], reduce)
}
function reduce (er, result) {
if (er) return hecomes(er, false)
if (result) return hecomes(null, result)
index++
map()
}
} | javascript | function some (list, test, cb) {
assert("length" in list, "array must be arraylike")
assert.equal(typeof test, "function", "predicate must be callable")
assert.equal(typeof cb, "function", "callback must be callable")
var array = slice(list)
, index = 0
, length = array.length
, hecomes = dezalgoify(cb)
map()
function map () {
if (index >= length) return hecomes(null, false)
test(array[index], reduce)
}
function reduce (er, result) {
if (er) return hecomes(er, false)
if (result) return hecomes(null, result)
index++
map()
}
} | [
"function",
"some",
"(",
"list",
",",
"test",
",",
"cb",
")",
"{",
"assert",
"(",
"\"length\"",
"in",
"list",
",",
"\"array must be arraylike\"",
")",
"assert",
".",
"equal",
"(",
"typeof",
"test",
",",
"\"function\"",
",",
"\"predicate must be callable\"",
")",
"assert",
".",
"equal",
"(",
"typeof",
"cb",
",",
"\"function\"",
",",
"\"callback must be callable\"",
")",
"var",
"array",
"=",
"slice",
"(",
"list",
")",
",",
"index",
"=",
"0",
",",
"length",
"=",
"array",
".",
"length",
",",
"hecomes",
"=",
"dezalgoify",
"(",
"cb",
")",
"map",
"(",
")",
"function",
"map",
"(",
")",
"{",
"if",
"(",
"index",
">=",
"length",
")",
"return",
"hecomes",
"(",
"null",
",",
"false",
")",
"test",
"(",
"array",
"[",
"index",
"]",
",",
"reduce",
")",
"}",
"function",
"reduce",
"(",
"er",
",",
"result",
")",
"{",
"if",
"(",
"er",
")",
"return",
"hecomes",
"(",
"er",
",",
"false",
")",
"if",
"(",
"result",
")",
"return",
"hecomes",
"(",
"null",
",",
"result",
")",
"index",
"++",
"map",
"(",
")",
"}",
"}"
]
| short-circuited async Array.prototype.some implementation
Serially evaluates a list of values from a JS array or arraylike
against an asynchronous predicate, terminating on the first truthy
value. If the predicate encounters an error, pass it to the completion
callback. Otherwise, pass the truthy value passed by the predicate, or
`false` if no truthy value was passed. | [
"short",
"-",
"circuited",
"async",
"Array",
".",
"prototype",
".",
"some",
"implementation"
]
| 3a5086ad54739c48b2bbf073f23bcc95658199e3 | https://github.com/othiym23/async-some/blob/3a5086ad54739c48b2bbf073f23bcc95658199e3/some.js#L15-L40 |
46,498 | othiym23/async-some | some.js | slice | function slice(args) {
var l = args.length, a = [], i
for (i = 0; i < l; i++) a[i] = args[i]
return a
} | javascript | function slice(args) {
var l = args.length, a = [], i
for (i = 0; i < l; i++) a[i] = args[i]
return a
} | [
"function",
"slice",
"(",
"args",
")",
"{",
"var",
"l",
"=",
"args",
".",
"length",
",",
"a",
"=",
"[",
"]",
",",
"i",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"a",
"[",
"i",
"]",
"=",
"args",
"[",
"i",
"]",
"return",
"a",
"}"
]
| Array.prototype.slice on arguments arraylike is expensive | [
"Array",
".",
"prototype",
".",
"slice",
"on",
"arguments",
"arraylike",
"is",
"expensive"
]
| 3a5086ad54739c48b2bbf073f23bcc95658199e3 | https://github.com/othiym23/async-some/blob/3a5086ad54739c48b2bbf073f23bcc95658199e3/some.js#L43-L47 |
46,499 | dominictarr/dat-table | index.js | Column | function Column (table, header, i) {
this._table = table, this._header = header, this._i = i
} | javascript | function Column (table, header, i) {
this._table = table, this._header = header, this._i = i
} | [
"function",
"Column",
"(",
"table",
",",
"header",
",",
"i",
")",
"{",
"this",
".",
"_table",
"=",
"table",
",",
"this",
".",
"_header",
"=",
"header",
",",
"this",
".",
"_i",
"=",
"i",
"}"
]
| this does nothing currently... but maybe it would be good to have something like this? so that you can pass columns to functions? | [
"this",
"does",
"nothing",
"currently",
"...",
"but",
"maybe",
"it",
"would",
"be",
"good",
"to",
"have",
"something",
"like",
"this?",
"so",
"that",
"you",
"can",
"pass",
"columns",
"to",
"functions?"
]
| d4c41e346ff4d721284a04841d1e7e0ed57a434d | https://github.com/dominictarr/dat-table/blob/d4c41e346ff4d721284a04841d1e7e0ed57a434d/index.js#L352-L354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.