repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
cb1kenobi/cli-kit | src/parser/option.js | processAliases | function processAliases(aliases) {
const result = {
long: {},
short: {}
};
if (!aliases) {
return result;
}
if (!Array.isArray(aliases)) {
if (typeof aliases === 'object') {
if (aliases.long && typeof aliases.long === 'object') {
Object.assign(result.long, aliases.long);
}
if (aliases.short && typeof aliases.short === 'object') {
Object.assign(result.short, aliases.short);
}
return result;
}
aliases = [ aliases ];
}
for (const alias of aliases) {
if (!alias || typeof alias !== 'string') {
throw E.INVALID_ALIAS('Expected aliases to be a string or an array of strings',
{ name: 'aliases', scope: 'Option.constructor', value: alias });
}
for (const a of alias.split(/[ ,|]+/)) {
const m = a.match(aliasRegExp);
if (!m) {
throw E.INVALID_ALIAS(`Invalid alias format "${alias}"`, { name: 'aliases', scope: 'Option.constructor', value: alias });
}
if (m[2]) {
result.short[m[2]] = !m[1];
} else if (m[3]) {
result.long[m[3]] = !m[1];
}
}
}
return result;
} | javascript | function processAliases(aliases) {
const result = {
long: {},
short: {}
};
if (!aliases) {
return result;
}
if (!Array.isArray(aliases)) {
if (typeof aliases === 'object') {
if (aliases.long && typeof aliases.long === 'object') {
Object.assign(result.long, aliases.long);
}
if (aliases.short && typeof aliases.short === 'object') {
Object.assign(result.short, aliases.short);
}
return result;
}
aliases = [ aliases ];
}
for (const alias of aliases) {
if (!alias || typeof alias !== 'string') {
throw E.INVALID_ALIAS('Expected aliases to be a string or an array of strings',
{ name: 'aliases', scope: 'Option.constructor', value: alias });
}
for (const a of alias.split(/[ ,|]+/)) {
const m = a.match(aliasRegExp);
if (!m) {
throw E.INVALID_ALIAS(`Invalid alias format "${alias}"`, { name: 'aliases', scope: 'Option.constructor', value: alias });
}
if (m[2]) {
result.short[m[2]] = !m[1];
} else if (m[3]) {
result.long[m[3]] = !m[1];
}
}
}
return result;
} | [
"function",
"processAliases",
"(",
"aliases",
")",
"{",
"const",
"result",
"=",
"{",
"long",
":",
"{",
"}",
",",
"short",
":",
"{",
"}",
"}",
";",
"if",
"(",
"!",
"aliases",
")",
"{",
"return",
"result",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"aliases",
")",
")",
"{",
"if",
"(",
"typeof",
"aliases",
"===",
"'object'",
")",
"{",
"if",
"(",
"aliases",
".",
"long",
"&&",
"typeof",
"aliases",
".",
"long",
"===",
"'object'",
")",
"{",
"Object",
".",
"assign",
"(",
"result",
".",
"long",
",",
"aliases",
".",
"long",
")",
";",
"}",
"if",
"(",
"aliases",
".",
"short",
"&&",
"typeof",
"aliases",
".",
"short",
"===",
"'object'",
")",
"{",
"Object",
".",
"assign",
"(",
"result",
".",
"short",
",",
"aliases",
".",
"short",
")",
";",
"}",
"return",
"result",
";",
"}",
"aliases",
"=",
"[",
"aliases",
"]",
";",
"}",
"for",
"(",
"const",
"alias",
"of",
"aliases",
")",
"{",
"if",
"(",
"!",
"alias",
"||",
"typeof",
"alias",
"!==",
"'string'",
")",
"{",
"throw",
"E",
".",
"INVALID_ALIAS",
"(",
"'Expected aliases to be a string or an array of strings'",
",",
"{",
"name",
":",
"'aliases'",
",",
"scope",
":",
"'Option.constructor'",
",",
"value",
":",
"alias",
"}",
")",
";",
"}",
"for",
"(",
"const",
"a",
"of",
"alias",
".",
"split",
"(",
"/",
"[ ,|]+",
"/",
")",
")",
"{",
"const",
"m",
"=",
"a",
".",
"match",
"(",
"aliasRegExp",
")",
";",
"if",
"(",
"!",
"m",
")",
"{",
"throw",
"E",
".",
"INVALID_ALIAS",
"(",
"`",
"${",
"alias",
"}",
"`",
",",
"{",
"name",
":",
"'aliases'",
",",
"scope",
":",
"'Option.constructor'",
",",
"value",
":",
"alias",
"}",
")",
";",
"}",
"if",
"(",
"m",
"[",
"2",
"]",
")",
"{",
"result",
".",
"short",
"[",
"m",
"[",
"2",
"]",
"]",
"=",
"!",
"m",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"m",
"[",
"3",
"]",
")",
"{",
"result",
".",
"long",
"[",
"m",
"[",
"3",
"]",
"]",
"=",
"!",
"m",
"[",
"1",
"]",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Processes aliases into sorted buckets for faster lookup.
@param {Array.<String>|String} aliases - An array, object, or string containing aliases.
@returns {Object} | [
"Processes",
"aliases",
"into",
"sorted",
"buckets",
"for",
"faster",
"lookup",
"."
] | 6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734 | https://github.com/cb1kenobi/cli-kit/blob/6d0d5ebb17cfbd11a8ec25ce8e4251f72cdc7734/src/parser/option.js#L221-L266 | train |
ryejs/rye | lib/query.js | getClosestNode | function getClosestNode (element, method, selector) {
do {
element = element[method]
} while (element && ((selector && !matches(element, selector)) || !util.isElement(element)))
return element
} | javascript | function getClosestNode (element, method, selector) {
do {
element = element[method]
} while (element && ((selector && !matches(element, selector)) || !util.isElement(element)))
return element
} | [
"function",
"getClosestNode",
"(",
"element",
",",
"method",
",",
"selector",
")",
"{",
"do",
"{",
"element",
"=",
"element",
"[",
"method",
"]",
"}",
"while",
"(",
"element",
"&&",
"(",
"(",
"selector",
"&&",
"!",
"matches",
"(",
"element",
",",
"selector",
")",
")",
"||",
"!",
"util",
".",
"isElement",
"(",
"element",
")",
")",
")",
"return",
"element",
"}"
] | Walks the DOM tree using `method`, returns when an element node is found | [
"Walks",
"the",
"DOM",
"tree",
"using",
"method",
"returns",
"when",
"an",
"element",
"node",
"is",
"found"
] | 24fd6728d055a1d2285b789c697a4578051f542d | https://github.com/ryejs/rye/blob/24fd6728d055a1d2285b789c697a4578051f542d/lib/query.js#L79-L84 | train |
ryejs/rye | lib/query.js | _create | function _create (elements, selector) {
return selector == null ? new Rye(elements) : new Rye(elements).filter(selector)
} | javascript | function _create (elements, selector) {
return selector == null ? new Rye(elements) : new Rye(elements).filter(selector)
} | [
"function",
"_create",
"(",
"elements",
",",
"selector",
")",
"{",
"return",
"selector",
"==",
"null",
"?",
"new",
"Rye",
"(",
"elements",
")",
":",
"new",
"Rye",
"(",
"elements",
")",
".",
"filter",
"(",
"selector",
")",
"}"
] | Creates a new Rye instance applying a filter if necessary | [
"Creates",
"a",
"new",
"Rye",
"instance",
"applying",
"a",
"filter",
"if",
"necessary"
] | 24fd6728d055a1d2285b789c697a4578051f542d | https://github.com/ryejs/rye/blob/24fd6728d055a1d2285b789c697a4578051f542d/lib/query.js#L87-L89 | train |
keymetrics/trassingue | src/plugins/plugin-redis.js | createCreateStreamWrap | function createCreateStreamWrap(api) {
return function createStreamWrap(create_stream) {
return function create_stream_trace() {
if (!this.stream) {
Object.defineProperty(this, 'stream', {
get: function () { return this._google_trace_stream; },
set: function (val) {
api.wrapEmitter(val);
this._google_trace_stream = val;
}
});
}
return create_stream.apply(this, arguments);
};
};
} | javascript | function createCreateStreamWrap(api) {
return function createStreamWrap(create_stream) {
return function create_stream_trace() {
if (!this.stream) {
Object.defineProperty(this, 'stream', {
get: function () { return this._google_trace_stream; },
set: function (val) {
api.wrapEmitter(val);
this._google_trace_stream = val;
}
});
}
return create_stream.apply(this, arguments);
};
};
} | [
"function",
"createCreateStreamWrap",
"(",
"api",
")",
"{",
"return",
"function",
"createStreamWrap",
"(",
"create_stream",
")",
"{",
"return",
"function",
"create_stream_trace",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"stream",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'stream'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"_google_trace_stream",
";",
"}",
",",
"set",
":",
"function",
"(",
"val",
")",
"{",
"api",
".",
"wrapEmitter",
"(",
"val",
")",
";",
"this",
".",
"_google_trace_stream",
"=",
"val",
";",
"}",
"}",
")",
";",
"}",
"return",
"create_stream",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}",
";",
"}"
] | Used for redis version > 2.3 | [
"Used",
"for",
"redis",
"version",
">",
"2",
".",
"3"
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/plugins/plugin-redis.js#L32-L47 | train |
keymetrics/trassingue | src/plugins/plugin-redis.js | createStreamListenersWrap | function createStreamListenersWrap(api) {
return function streamListenersWrap(install_stream_listeners) {
return function install_stream_listeners_trace() {
api.wrapEmitter(this.stream);
return install_stream_listeners.apply(this, arguments);
};
};
} | javascript | function createStreamListenersWrap(api) {
return function streamListenersWrap(install_stream_listeners) {
return function install_stream_listeners_trace() {
api.wrapEmitter(this.stream);
return install_stream_listeners.apply(this, arguments);
};
};
} | [
"function",
"createStreamListenersWrap",
"(",
"api",
")",
"{",
"return",
"function",
"streamListenersWrap",
"(",
"install_stream_listeners",
")",
"{",
"return",
"function",
"install_stream_listeners_trace",
"(",
")",
"{",
"api",
".",
"wrapEmitter",
"(",
"this",
".",
"stream",
")",
";",
"return",
"install_stream_listeners",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}",
";",
"}"
] | Used for redis version <= 2.3 | [
"Used",
"for",
"redis",
"version",
"<",
"=",
"2",
".",
"3"
] | 1d283858b45e5fb42519dc1f39cffaaade601931 | https://github.com/keymetrics/trassingue/blob/1d283858b45e5fb42519dc1f39cffaaade601931/src/plugins/plugin-redis.js#L50-L57 | train |
Squarespace/pouchdb-lru-cache | index.js | getDocWithDefault | function getDocWithDefault(db, id, defaultDoc) {
return db.get(id).catch(function (err) {
/* istanbul ignore if */
if (err.status !== 404) {
throw err;
}
defaultDoc._id = id;
return db.put(defaultDoc).catch(function (err) {
/* istanbul ignore if */
if (err.status !== 409) { // conflict
throw err;
}
}).then(function () {
return db.get(id);
});
});
} | javascript | function getDocWithDefault(db, id, defaultDoc) {
return db.get(id).catch(function (err) {
/* istanbul ignore if */
if (err.status !== 404) {
throw err;
}
defaultDoc._id = id;
return db.put(defaultDoc).catch(function (err) {
/* istanbul ignore if */
if (err.status !== 409) { // conflict
throw err;
}
}).then(function () {
return db.get(id);
});
});
} | [
"function",
"getDocWithDefault",
"(",
"db",
",",
"id",
",",
"defaultDoc",
")",
"{",
"return",
"db",
".",
"get",
"(",
"id",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"status",
"!==",
"404",
")",
"{",
"throw",
"err",
";",
"}",
"defaultDoc",
".",
"_id",
"=",
"id",
";",
"return",
"db",
".",
"put",
"(",
"defaultDoc",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"status",
"!==",
"409",
")",
"{",
"throw",
"err",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"db",
".",
"get",
"(",
"id",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Create the doc if it doesn't exist | [
"Create",
"the",
"doc",
"if",
"it",
"doesn",
"t",
"exist"
] | dcb35db4771b469be9bfe08bec0cdff71ae0a925 | https://github.com/Squarespace/pouchdb-lru-cache/blob/dcb35db4771b469be9bfe08bec0cdff71ae0a925/index.js#L18-L34 | train |
Squarespace/pouchdb-lru-cache | index.js | getMainDoc | function getMainDoc(db) {
return getDocWithDefault(db, MAIN_DOC_ID, {}).then(function (doc) {
if (!doc._attachments) {
doc._attachments = {};
}
return doc;
});
} | javascript | function getMainDoc(db) {
return getDocWithDefault(db, MAIN_DOC_ID, {}).then(function (doc) {
if (!doc._attachments) {
doc._attachments = {};
}
return doc;
});
} | [
"function",
"getMainDoc",
"(",
"db",
")",
"{",
"return",
"getDocWithDefault",
"(",
"db",
",",
"MAIN_DOC_ID",
",",
"{",
"}",
")",
".",
"then",
"(",
"function",
"(",
"doc",
")",
"{",
"if",
"(",
"!",
"doc",
".",
"_attachments",
")",
"{",
"doc",
".",
"_attachments",
"=",
"{",
"}",
";",
"}",
"return",
"doc",
";",
"}",
")",
";",
"}"
] | Store all attachments in a single doc. Since attachments
are deduped, and unless the attachment metadata can't all fit
in memory at once, there's no reason not to do this. | [
"Store",
"all",
"attachments",
"in",
"a",
"single",
"doc",
".",
"Since",
"attachments",
"are",
"deduped",
"and",
"unless",
"the",
"attachment",
"metadata",
"can",
"t",
"all",
"fit",
"in",
"memory",
"at",
"once",
"there",
"s",
"no",
"reason",
"not",
"to",
"do",
"this",
"."
] | dcb35db4771b469be9bfe08bec0cdff71ae0a925 | https://github.com/Squarespace/pouchdb-lru-cache/blob/dcb35db4771b469be9bfe08bec0cdff71ae0a925/index.js#L41-L48 | train |
Squarespace/pouchdb-lru-cache | index.js | calculateTotalSize | function calculateTotalSize(mainDoc) {
var digestsToSizes = {};
// dedup by digest, since that's what Pouch does under the hood
Object.keys(mainDoc._attachments).forEach(function (attName) {
var att = mainDoc._attachments[attName];
digestsToSizes[att.digest] = att.length;
});
var total = 0;
Object.keys(digestsToSizes).forEach(function (digest) {
total += digestsToSizes[digest];
});
return total;
} | javascript | function calculateTotalSize(mainDoc) {
var digestsToSizes = {};
// dedup by digest, since that's what Pouch does under the hood
Object.keys(mainDoc._attachments).forEach(function (attName) {
var att = mainDoc._attachments[attName];
digestsToSizes[att.digest] = att.length;
});
var total = 0;
Object.keys(digestsToSizes).forEach(function (digest) {
total += digestsToSizes[digest];
});
return total;
} | [
"function",
"calculateTotalSize",
"(",
"mainDoc",
")",
"{",
"var",
"digestsToSizes",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"mainDoc",
".",
"_attachments",
")",
".",
"forEach",
"(",
"function",
"(",
"attName",
")",
"{",
"var",
"att",
"=",
"mainDoc",
".",
"_attachments",
"[",
"attName",
"]",
";",
"digestsToSizes",
"[",
"att",
".",
"digest",
"]",
"=",
"att",
".",
"length",
";",
"}",
")",
";",
"var",
"total",
"=",
"0",
";",
"Object",
".",
"keys",
"(",
"digestsToSizes",
")",
".",
"forEach",
"(",
"function",
"(",
"digest",
")",
"{",
"total",
"+=",
"digestsToSizes",
"[",
"digest",
"]",
";",
"}",
")",
";",
"return",
"total",
";",
"}"
] | Get the total size of the LRU cache, taking duplicate digests into account | [
"Get",
"the",
"total",
"size",
"of",
"the",
"LRU",
"cache",
"taking",
"duplicate",
"digests",
"into",
"account"
] | dcb35db4771b469be9bfe08bec0cdff71ae0a925 | https://github.com/Squarespace/pouchdb-lru-cache/blob/dcb35db4771b469be9bfe08bec0cdff71ae0a925/index.js#L81-L95 | train |
Squarespace/pouchdb-lru-cache | index.js | synchronous | function synchronous(promiseFactory) {
return function () {
var promise = queue.then(promiseFactory);
queue = promise.catch(noop); // squelch
return promise;
};
} | javascript | function synchronous(promiseFactory) {
return function () {
var promise = queue.then(promiseFactory);
queue = promise.catch(noop); // squelch
return promise;
};
} | [
"function",
"synchronous",
"(",
"promiseFactory",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"promise",
"=",
"queue",
".",
"then",
"(",
"promiseFactory",
")",
";",
"queue",
"=",
"promise",
".",
"catch",
"(",
"noop",
")",
";",
"return",
"promise",
";",
"}",
";",
"}"
] | To mitigate 409s, we synchronize certain things that need to be
done in a "transaction". So whatever promise is given to this
function will execute sequentially. | [
"To",
"mitigate",
"409s",
"we",
"synchronize",
"certain",
"things",
"that",
"need",
"to",
"be",
"done",
"in",
"a",
"transaction",
".",
"So",
"whatever",
"promise",
"is",
"given",
"to",
"this",
"function",
"will",
"execute",
"sequentially",
"."
] | dcb35db4771b469be9bfe08bec0cdff71ae0a925 | https://github.com/Squarespace/pouchdb-lru-cache/blob/dcb35db4771b469be9bfe08bec0cdff71ae0a925/index.js#L102-L108 | train |
Squarespace/pouchdb-lru-cache | index.js | getDigestsToLastUsed | function getDigestsToLastUsed(mainDoc, lastUsedDoc) {
var result = {};
// dedup by digest, use the most recent date
Object.keys(mainDoc._attachments).forEach(function (attName) {
var att = mainDoc._attachments[attName];
var existing = result[att.digest] || 0;
result[att.digest] = Math.max(existing, lastUsedDoc.lastUsed[att.digest]);
});
return result;
} | javascript | function getDigestsToLastUsed(mainDoc, lastUsedDoc) {
var result = {};
// dedup by digest, use the most recent date
Object.keys(mainDoc._attachments).forEach(function (attName) {
var att = mainDoc._attachments[attName];
var existing = result[att.digest] || 0;
result[att.digest] = Math.max(existing, lastUsedDoc.lastUsed[att.digest]);
});
return result;
} | [
"function",
"getDigestsToLastUsed",
"(",
"mainDoc",
",",
"lastUsedDoc",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"mainDoc",
".",
"_attachments",
")",
".",
"forEach",
"(",
"function",
"(",
"attName",
")",
"{",
"var",
"att",
"=",
"mainDoc",
".",
"_attachments",
"[",
"attName",
"]",
";",
"var",
"existing",
"=",
"result",
"[",
"att",
".",
"digest",
"]",
"||",
"0",
";",
"result",
"[",
"att",
".",
"digest",
"]",
"=",
"Math",
".",
"max",
"(",
"existing",
",",
"lastUsedDoc",
".",
"lastUsed",
"[",
"att",
".",
"digest",
"]",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Get a map of unique digests to when they were last used. | [
"Get",
"a",
"map",
"of",
"unique",
"digests",
"to",
"when",
"they",
"were",
"last",
"used",
"."
] | dcb35db4771b469be9bfe08bec0cdff71ae0a925 | https://github.com/Squarespace/pouchdb-lru-cache/blob/dcb35db4771b469be9bfe08bec0cdff71ae0a925/index.js#L113-L124 | train |
Squarespace/pouchdb-lru-cache | index.js | getLeastRecentlyUsed | function getLeastRecentlyUsed(mainDoc, lastUsedDoc) {
var digestsToLastUsed = getDigestsToLastUsed(mainDoc, lastUsedDoc);
var min;
var minDigest;
Object.keys(digestsToLastUsed).forEach(function (digest) {
var lastUsed = digestsToLastUsed[digest];
if (typeof min === 'undefined' || min > lastUsed) {
min = lastUsed;
minDigest = digest;
}
});
return minDigest;
} | javascript | function getLeastRecentlyUsed(mainDoc, lastUsedDoc) {
var digestsToLastUsed = getDigestsToLastUsed(mainDoc, lastUsedDoc);
var min;
var minDigest;
Object.keys(digestsToLastUsed).forEach(function (digest) {
var lastUsed = digestsToLastUsed[digest];
if (typeof min === 'undefined' || min > lastUsed) {
min = lastUsed;
minDigest = digest;
}
});
return minDigest;
} | [
"function",
"getLeastRecentlyUsed",
"(",
"mainDoc",
",",
"lastUsedDoc",
")",
"{",
"var",
"digestsToLastUsed",
"=",
"getDigestsToLastUsed",
"(",
"mainDoc",
",",
"lastUsedDoc",
")",
";",
"var",
"min",
";",
"var",
"minDigest",
";",
"Object",
".",
"keys",
"(",
"digestsToLastUsed",
")",
".",
"forEach",
"(",
"function",
"(",
"digest",
")",
"{",
"var",
"lastUsed",
"=",
"digestsToLastUsed",
"[",
"digest",
"]",
";",
"if",
"(",
"typeof",
"min",
"===",
"'undefined'",
"||",
"min",
">",
"lastUsed",
")",
"{",
"min",
"=",
"lastUsed",
";",
"minDigest",
"=",
"digest",
";",
"}",
"}",
")",
";",
"return",
"minDigest",
";",
"}"
] | Get the digest that's the least recently used. If a digest was used
by more than one attachment, then favor the more recent usage date. | [
"Get",
"the",
"digest",
"that",
"s",
"the",
"least",
"recently",
"used",
".",
"If",
"a",
"digest",
"was",
"used",
"by",
"more",
"than",
"one",
"attachment",
"then",
"favor",
"the",
"more",
"recent",
"usage",
"date",
"."
] | dcb35db4771b469be9bfe08bec0cdff71ae0a925 | https://github.com/Squarespace/pouchdb-lru-cache/blob/dcb35db4771b469be9bfe08bec0cdff71ae0a925/index.js#L130-L143 | train |
BBVAEngineering/ember-task-scheduler | addon/services/scheduler.js | scheduleFrame | function scheduleFrame(context, method) {
method = context[method];
return requestAnimationFrame(method.bind(context));
} | javascript | function scheduleFrame(context, method) {
method = context[method];
return requestAnimationFrame(method.bind(context));
} | [
"function",
"scheduleFrame",
"(",
"context",
",",
"method",
")",
"{",
"method",
"=",
"context",
"[",
"method",
"]",
";",
"return",
"requestAnimationFrame",
"(",
"method",
".",
"bind",
"(",
"context",
")",
")",
";",
"}"
] | Bind context to method and call requestAnimationFrame with generated function.
@method scheduleFrame
@param {Object} context
@param {String} method
@return Number
@private | [
"Bind",
"context",
"to",
"method",
"and",
"call",
"requestAnimationFrame",
"with",
"generated",
"function",
"."
] | a6c35916e7e5f9e57c8d646062b15f9ae8164147 | https://github.com/BBVAEngineering/ember-task-scheduler/blob/a6c35916e7e5f9e57c8d646062b15f9ae8164147/addon/services/scheduler.js#L26-L30 | train |
BBVAEngineering/ember-task-scheduler | addon/services/scheduler.js | exec | function exec(target, method, args, onError, stack) {
try {
method.apply(target, args);
} catch (e) {
if (onError) {
onError(e, stack);
}
}
} | javascript | function exec(target, method, args, onError, stack) {
try {
method.apply(target, args);
} catch (e) {
if (onError) {
onError(e, stack);
}
}
} | [
"function",
"exec",
"(",
"target",
",",
"method",
",",
"args",
",",
"onError",
",",
"stack",
")",
"{",
"try",
"{",
"method",
".",
"apply",
"(",
"target",
",",
"args",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"onError",
")",
"{",
"onError",
"(",
"e",
",",
"stack",
")",
";",
"}",
"}",
"}"
] | Try to exec a function with target and args.
When function throws an error it calls onError function with error and stack.
@method exec
@param {Object} target
@param {Function|String} method
@param {Array} args
@param {Function} onError
@param {Error} stack
@private | [
"Try",
"to",
"exec",
"a",
"function",
"with",
"target",
"and",
"args",
"."
] | a6c35916e7e5f9e57c8d646062b15f9ae8164147 | https://github.com/BBVAEngineering/ember-task-scheduler/blob/a6c35916e7e5f9e57c8d646062b15f9ae8164147/addon/services/scheduler.js#L45-L53 | train |
BBVAEngineering/ember-task-scheduler | addon/services/scheduler.js | _logWarn | function _logWarn(title, stack, test = false, options = {}) {
if (test) {
return;
}
const { groupCollapsed, log, trace, groupEnd } = console;
if (groupCollapsed && trace && groupEnd) {
groupCollapsed(title);
log(options.id);
trace(stack.stack);
groupEnd(title);
} else {
warn(`${title}\n${stack.stack}`, test, options);
}
} | javascript | function _logWarn(title, stack, test = false, options = {}) {
if (test) {
return;
}
const { groupCollapsed, log, trace, groupEnd } = console;
if (groupCollapsed && trace && groupEnd) {
groupCollapsed(title);
log(options.id);
trace(stack.stack);
groupEnd(title);
} else {
warn(`${title}\n${stack.stack}`, test, options);
}
} | [
"function",
"_logWarn",
"(",
"title",
",",
"stack",
",",
"test",
"=",
"false",
",",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"test",
")",
"{",
"return",
";",
"}",
"const",
"{",
"groupCollapsed",
",",
"log",
",",
"trace",
",",
"groupEnd",
"}",
"=",
"console",
";",
"if",
"(",
"groupCollapsed",
"&&",
"trace",
"&&",
"groupEnd",
")",
"{",
"groupCollapsed",
"(",
"title",
")",
";",
"log",
"(",
"options",
".",
"id",
")",
";",
"trace",
"(",
"stack",
".",
"stack",
")",
";",
"groupEnd",
"(",
"title",
")",
";",
"}",
"else",
"{",
"warn",
"(",
"`",
"${",
"title",
"}",
"\\n",
"${",
"stack",
".",
"stack",
"}",
"`",
",",
"test",
",",
"options",
")",
";",
"}",
"}"
] | Logs a grouped stack trace.
Fallback to warn() from @ember/debug
@param {String} title Group title
@param {Object} stack Stack trace
@param {Boolean} test An optional boolean. If falsy, the warning will be displayed.
@param {Object} options Can be used to pass a unique `id` for this warning.
/* istanbul ignore next | [
"Logs",
"a",
"grouped",
"stack",
"trace",
"."
] | a6c35916e7e5f9e57c8d646062b15f9ae8164147 | https://github.com/BBVAEngineering/ember-task-scheduler/blob/a6c35916e7e5f9e57c8d646062b15f9ae8164147/addon/services/scheduler.js#L66-L81 | train |
nomocas/min-history | lib/min-history.js | function(id, location) {
var search = "?"+ (location.search || "") + "&hid=" + id;
return (location.pathname || '/')
+ search
+ (location.hash ? ("#" + location.hash) : "");
} | javascript | function(id, location) {
var search = "?"+ (location.search || "") + "&hid=" + id;
return (location.pathname || '/')
+ search
+ (location.hash ? ("#" + location.hash) : "");
} | [
"function",
"(",
"id",
",",
"location",
")",
"{",
"var",
"search",
"=",
"\"?\"",
"+",
"(",
"location",
".",
"search",
"||",
"\"\"",
")",
"+",
"\"&hid=\"",
"+",
"id",
";",
"return",
"(",
"location",
".",
"pathname",
"||",
"'/'",
")",
"+",
"search",
"+",
"(",
"location",
".",
"hash",
"?",
"(",
"\"#\"",
"+",
"location",
".",
"hash",
")",
":",
"\"\"",
")",
";",
"}"
] | produce href with hid in search part | [
"produce",
"href",
"with",
"hid",
"in",
"search",
"part"
] | d4e3514bf08982eb43aa0e1512294c767b8dea03 | https://github.com/nomocas/min-history/blob/d4e3514bf08982eb43aa0e1512294c767b8dea03/lib/min-history.js#L120-L125 | train |
|
nomocas/min-history | lib/min-history.js | function(location) {
if (!location.search)
return;
location.search = location.search.replace(/&hid=([^&]+)/gi, function(c, v) {
location.hid = v;
return "";
});
location.path = location.pathname + (location.search ? ("?" + location.search) : "");
location.relative = location.path + (location.hash ? ("#" + location.hash) : "");
location.href = location.protocol + "://" + location.host + location.relative;
} | javascript | function(location) {
if (!location.search)
return;
location.search = location.search.replace(/&hid=([^&]+)/gi, function(c, v) {
location.hid = v;
return "";
});
location.path = location.pathname + (location.search ? ("?" + location.search) : "");
location.relative = location.path + (location.hash ? ("#" + location.hash) : "");
location.href = location.protocol + "://" + location.host + location.relative;
} | [
"function",
"(",
"location",
")",
"{",
"if",
"(",
"!",
"location",
".",
"search",
")",
"return",
";",
"location",
".",
"search",
"=",
"location",
".",
"search",
".",
"replace",
"(",
"/",
"&hid=([^&]+)",
"/",
"gi",
",",
"function",
"(",
"c",
",",
"v",
")",
"{",
"location",
".",
"hid",
"=",
"v",
";",
"return",
"\"\"",
";",
"}",
")",
";",
"location",
".",
"path",
"=",
"location",
".",
"pathname",
"+",
"(",
"location",
".",
"search",
"?",
"(",
"\"?\"",
"+",
"location",
".",
"search",
")",
":",
"\"\"",
")",
";",
"location",
".",
"relative",
"=",
"location",
".",
"path",
"+",
"(",
"location",
".",
"hash",
"?",
"(",
"\"#\"",
"+",
"location",
".",
"hash",
")",
":",
"\"\"",
")",
";",
"location",
".",
"href",
"=",
"location",
".",
"protocol",
"+",
"\"://\"",
"+",
"location",
".",
"host",
"+",
"location",
".",
"relative",
";",
"}"
] | remove hid from location parts. store hid in location. | [
"remove",
"hid",
"from",
"location",
"parts",
".",
"store",
"hid",
"in",
"location",
"."
] | d4e3514bf08982eb43aa0e1512294c767b8dea03 | https://github.com/nomocas/min-history/blob/d4e3514bf08982eb43aa0e1512294c767b8dea03/lib/min-history.js#L128-L138 | train |
|
caohanyang/json_diff_rfc6902 | lib/deepEquals.js | _equals | function _equals(a, b) {
switch (typeof a) {
case 'undefined':
case 'boolean':
case 'string':
case 'number':
return a === b;
case 'object':
if (a === null)
{return b === null;}
if (_isArray(a)) {
if (!_isArray(b) || a.length !== b.length)
{return false;}
for (var i = 0, l = a.length; i < l; i++) {
if (!_equals(a[i], b[i]))
{return false;}
}
return true;
}
var bKeys = _objectKeys(b);
var bLength = bKeys.length;
if (_objectKeys(a).length !== bLength)
{return false;}
for (var i = 0, k; i < bLength; i++) {
k = bKeys[i];
if (!(k in a && _equals(a[k], b[k])))
{return false;}
}
return true;
default:
return false;
}
} | javascript | function _equals(a, b) {
switch (typeof a) {
case 'undefined':
case 'boolean':
case 'string':
case 'number':
return a === b;
case 'object':
if (a === null)
{return b === null;}
if (_isArray(a)) {
if (!_isArray(b) || a.length !== b.length)
{return false;}
for (var i = 0, l = a.length; i < l; i++) {
if (!_equals(a[i], b[i]))
{return false;}
}
return true;
}
var bKeys = _objectKeys(b);
var bLength = bKeys.length;
if (_objectKeys(a).length !== bLength)
{return false;}
for (var i = 0, k; i < bLength; i++) {
k = bKeys[i];
if (!(k in a && _equals(a[k], b[k])))
{return false;}
}
return true;
default:
return false;
}
} | [
"function",
"_equals",
"(",
"a",
",",
"b",
")",
"{",
"switch",
"(",
"typeof",
"a",
")",
"{",
"case",
"'undefined'",
":",
"case",
"'boolean'",
":",
"case",
"'string'",
":",
"case",
"'number'",
":",
"return",
"a",
"===",
"b",
";",
"case",
"'object'",
":",
"if",
"(",
"a",
"===",
"null",
")",
"{",
"return",
"b",
"===",
"null",
";",
"}",
"if",
"(",
"_isArray",
"(",
"a",
")",
")",
"{",
"if",
"(",
"!",
"_isArray",
"(",
"b",
")",
"||",
"a",
".",
"length",
"!==",
"b",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"a",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"_equals",
"(",
"a",
"[",
"i",
"]",
",",
"b",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"var",
"bKeys",
"=",
"_objectKeys",
"(",
"b",
")",
";",
"var",
"bLength",
"=",
"bKeys",
".",
"length",
";",
"if",
"(",
"_objectKeys",
"(",
"a",
")",
".",
"length",
"!==",
"bLength",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"k",
";",
"i",
"<",
"bLength",
";",
"i",
"++",
")",
"{",
"k",
"=",
"bKeys",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"(",
"k",
"in",
"a",
"&&",
"_equals",
"(",
"a",
"[",
"k",
"]",
",",
"b",
"[",
"k",
"]",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | _equals - This can save a lot of time 5 ms
@param {type} a description
@param {type} b description
@return {type} description | [
"_equals",
"-",
"This",
"can",
"save",
"a",
"lot",
"of",
"time",
"5",
"ms"
] | cb23e4adafb86156409c72790c593881f7685dc1 | https://github.com/caohanyang/json_diff_rfc6902/blob/cb23e4adafb86156409c72790c593881f7685dc1/lib/deepEquals.js#L40-L78 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | function (prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor();
Ctor.prototype = null;
return result;
} | javascript | function (prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor();
Ctor.prototype = null;
return result;
} | [
"function",
"(",
"prototype",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"prototype",
")",
")",
"return",
"{",
"}",
";",
"if",
"(",
"nativeCreate",
")",
"return",
"nativeCreate",
"(",
"prototype",
")",
";",
"Ctor",
".",
"prototype",
"=",
"prototype",
";",
"var",
"result",
"=",
"new",
"Ctor",
"(",
")",
";",
"Ctor",
".",
"prototype",
"=",
"null",
";",
"return",
"result",
";",
"}"
] | An internal function for creating a new object that inherits from another. | [
"An",
"internal",
"function",
"for",
"creating",
"a",
"new",
"object",
"that",
"inherits",
"from",
"another",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L140-L147 | train |
|
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | omit | function omit(obj, blackList) {
var newObj = {};
Object.keys(obj || {}).forEach(function (key) {
if (blackList.indexOf(key) === -1) {
newObj[key] = obj[key];
}
});
return newObj;
} | javascript | function omit(obj, blackList) {
var newObj = {};
Object.keys(obj || {}).forEach(function (key) {
if (blackList.indexOf(key) === -1) {
newObj[key] = obj[key];
}
});
return newObj;
} | [
"function",
"omit",
"(",
"obj",
",",
"blackList",
")",
"{",
"var",
"newObj",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"obj",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"blackList",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
")",
"{",
"newObj",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"return",
"newObj",
";",
"}"
] | Return a copy of the object, filtered to omit the blacklisted array of keys. | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"filtered",
"to",
"omit",
"the",
"blacklisted",
"array",
"of",
"keys",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L5578-L5586 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | parseStartKey | function parseStartKey(key, restOfLine) {
// When a new key is encountered, the rest of the line is immediately added as
// its value, by calling `flushBuffer`.
flushBuffer();
incrementArrayElement(key);
if (stackScope && stackScope.flags.indexOf('+') > -1) key = 'value';
bufferKey = key;
bufferString = restOfLine;
flushBufferInto(key, { replace: true });
} | javascript | function parseStartKey(key, restOfLine) {
// When a new key is encountered, the rest of the line is immediately added as
// its value, by calling `flushBuffer`.
flushBuffer();
incrementArrayElement(key);
if (stackScope && stackScope.flags.indexOf('+') > -1) key = 'value';
bufferKey = key;
bufferString = restOfLine;
flushBufferInto(key, { replace: true });
} | [
"function",
"parseStartKey",
"(",
"key",
",",
"restOfLine",
")",
"{",
"flushBuffer",
"(",
")",
";",
"incrementArrayElement",
"(",
"key",
")",
";",
"if",
"(",
"stackScope",
"&&",
"stackScope",
".",
"flags",
".",
"indexOf",
"(",
"'+'",
")",
">",
"-",
"1",
")",
"key",
"=",
"'value'",
";",
"bufferKey",
"=",
"key",
";",
"bufferString",
"=",
"restOfLine",
";",
"flushBufferInto",
"(",
"key",
",",
"{",
"replace",
":",
"true",
"}",
")",
";",
"}"
] | The following parse functions add to the global `data` object and update scoping variables to keep track of what we're parsing. | [
"The",
"following",
"parse",
"functions",
"add",
"to",
"the",
"global",
"data",
"object",
"and",
"update",
"scoping",
"variables",
"to",
"keep",
"track",
"of",
"what",
"we",
"re",
"parsing",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L5667-L5680 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | getParser | function getParser(delimiterOrParser) {
var parser;
if (typeof delimiterOrParser === 'string') {
parser = discernParser(delimiterOrParser, { delimiter: true });
} else if (typeof delimiterOrParser === 'function' || (typeof delimiterOrParser === 'undefined' ? 'undefined' : _typeof(delimiterOrParser)) === 'object') {
parser = delimiterOrParser;
}
return parser;
} | javascript | function getParser(delimiterOrParser) {
var parser;
if (typeof delimiterOrParser === 'string') {
parser = discernParser(delimiterOrParser, { delimiter: true });
} else if (typeof delimiterOrParser === 'function' || (typeof delimiterOrParser === 'undefined' ? 'undefined' : _typeof(delimiterOrParser)) === 'object') {
parser = delimiterOrParser;
}
return parser;
} | [
"function",
"getParser",
"(",
"delimiterOrParser",
")",
"{",
"var",
"parser",
";",
"if",
"(",
"typeof",
"delimiterOrParser",
"===",
"'string'",
")",
"{",
"parser",
"=",
"discernParser",
"(",
"delimiterOrParser",
",",
"{",
"delimiter",
":",
"true",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"delimiterOrParser",
"===",
"'function'",
"||",
"(",
"typeof",
"delimiterOrParser",
"===",
"'undefined'",
"?",
"'undefined'",
":",
"_typeof",
"(",
"delimiterOrParser",
")",
")",
"===",
"'object'",
")",
"{",
"parser",
"=",
"delimiterOrParser",
";",
"}",
"return",
"parser",
";",
"}"
] | Our `readData` fns can take either a delimiter to parse a file, or a full blown parser Determine what they passed in with this handy function | [
"Our",
"readData",
"fns",
"can",
"take",
"either",
"a",
"delimiter",
"to",
"parse",
"a",
"file",
"or",
"a",
"full",
"blown",
"parser",
"Determine",
"what",
"they",
"passed",
"in",
"with",
"this",
"handy",
"function"
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L6098-L6106 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | formattingPreflight | function formattingPreflight(file, format) {
if (file === '') {
return [];
} else if (!Array.isArray(file)) {
notListError(format);
}
return file;
} | javascript | function formattingPreflight(file, format) {
if (file === '') {
return [];
} else if (!Array.isArray(file)) {
notListError(format);
}
return file;
} | [
"function",
"formattingPreflight",
"(",
"file",
",",
"format",
")",
"{",
"if",
"(",
"file",
"===",
"''",
")",
"{",
"return",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"file",
")",
")",
"{",
"notListError",
"(",
"format",
")",
";",
"}",
"return",
"file",
";",
"}"
] | Some shared data integrity checks for formatters | [
"Some",
"shared",
"data",
"integrity",
"checks",
"for",
"formatters"
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L6603-L6610 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readDbf | function readDbf(filePath, opts_, cb) {
var parserOptions = {
map: identity
};
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, parserOptions, cb);
} | javascript | function readDbf(filePath, opts_, cb) {
var parserOptions = {
map: identity
};
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, parserOptions, cb);
} | [
"function",
"readDbf",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
"=",
"{",
"map",
":",
"identity",
"}",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"parserOptions",
",",
"cb",
")",
";",
"}"
] | Asynchronously read a dbf file. Returns an empty array if file is empty.
@function readDbf
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Called once for each row with the signature `(row, i)` and must return the transformed row. See example below.
@param {Function} callback Has signature `(err, data)`
@example
io.readDbf('path/to/data.dbf', function (err, data) {
console.log(data) // Json data
})
// Transform values on load
io.readDbf('path/to/data.csv', function (row, i) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
}, function (err, data) {
console.log(data) // Converted json data
}) | [
"Asynchronously",
"read",
"a",
"dbf",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L7247-L7257 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readdirFilter | function readdirFilter(dirPath, opts_, cb) {
if (typeof cb === 'undefined') {
cb = opts_;
opts_ = undefined;
}
readdir({ async: true }, dirPath, opts_, cb);
} | javascript | function readdirFilter(dirPath, opts_, cb) {
if (typeof cb === 'undefined') {
cb = opts_;
opts_ = undefined;
}
readdir({ async: true }, dirPath, opts_, cb);
} | [
"function",
"readdirFilter",
"(",
"dirPath",
",",
"opts_",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"opts_",
"=",
"undefined",
";",
"}",
"readdir",
"(",
"{",
"async",
":",
"true",
"}",
",",
"dirPath",
",",
"opts_",
",",
"cb",
")",
";",
"}"
] | Asynchronously get a list of a directory's files and folders if certain critera are met.
@function readdirFilter
@param {String} dirPath The directory to read from
@param {Object} options Filter options, see below
@param {Boolean} [options.fullPath=false] If `true`, return the full path of the file, otherwise just return the file name.
@param {Boolean} [options.detailed=false] If `true`, return an object like `{basePath: 'path/to', fileName: 'file.csv'}`. Whether `basePath` has a trailing will follow what you give to `dirPath`, which can take either.
@param {Boolean} [options.skipFiles=false] If `true`, omit files from results.
@param {Boolean} [options.skipDirs=false] If `true`, omit directories from results.
@param {Boolean} [options.skipHidden=false] If `true`, omit files that start with a dot from results. Shorthand for `{exclude: /^\./}`.
@param {String|RegExp|Array<String|RegExp>} options.include If given a string, return files that have that string as their extension. If given a Regular Expression, return the files whose name matches the pattern. Can also take a list of either type. List matching behavior is described in `includeMatchAll`.
@param {String|RegExp|Array<String|RegExp>} options.exclude If given a string, return files that do not have that string as their extension. If given a Regular Expression, omit files whose name matches the pattern. Can also take a list of either type. List matching behavior is described in `excludeMatchAll`.
@param {Boolean} [options.includeMatchAll=false] If true, require all include conditions to be met for a file to be included.
@param {Boolean} [options.excludeMatchAll=false] If true, require all exclude conditions to be met for a file to be excluded.
@param {Function} callback Has signature `(err, data)` where `files` is a list of matching file names.
@example
// dir contains `data-0.tsv`, `data-0.json`, `data-0.csv`, `data-1.csv`, `.hidden-file`
io.readdirFilter('path/to/files', {include: 'csv'}, function(err, files){
console.log(files) // ['data-0.csv', 'data-1.csv']
})
io.readdirFilter('path/to/files', {include: [/^data/], exclude: ['csv', 'json']}, , function(err, files){
console.log(files) // ['path/to/files/data-0.csv', 'path/to/files/data-1.csv', 'path/to/files/data-0.tsv']
}) | [
"Asynchronously",
"get",
"a",
"list",
"of",
"a",
"directory",
"s",
"files",
"and",
"folders",
"if",
"certain",
"critera",
"are",
"met",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L7978-L7985 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readAml | function readAml(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserAml, parserOptions: parserOptions }, cb);
} | javascript | function readAml(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserAml, parserOptions: parserOptions }, cb);
} | [
"function",
"readAml",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserAml",
",",
"parserOptions",
":",
"parserOptions",
"}",
",",
"cb",
")",
";",
"}"
] | Asynchronously read an ArchieMl file. Returns an empty object if file is empty.
@function readAml
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Takes the parsed file (usually an object) and must return the modified file. See example below.
@param {Function} callback Has signature `(err, data)`
@example
io.readAml('path/to/data.aml', function (err, data) {
console.log(data) // json data
})
// With map
io.readAml('path/to/data.aml', function (amlFile) {
amlFile.height = amlFile.height * 2
return amlFile
}, function (err, data) {
console.log(data) // json data with height multiplied by 2
}) | [
"Asynchronously",
"read",
"an",
"ArchieMl",
"file",
".",
"Returns",
"an",
"empty",
"object",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8041-L8049 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readAmlSync | function readAmlSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserAml, parserOptions: parserOptions });
} | javascript | function readAmlSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserAml, parserOptions: parserOptions });
} | [
"function",
"readAmlSync",
"(",
"filePath",
",",
"opts_",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"opts_",
"!==",
"'undefined'",
")",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"return",
"readDataSync",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserAml",
",",
"parserOptions",
":",
"parserOptions",
"}",
")",
";",
"}"
] | Synchronously read an ArchieML file. Returns an empty object if file is empty.
@function readAmlSync
@param {String} filePath Input file path
@param {Function} [map] Optional map function. Takes the parsed file (usually an object) and must return the modified file. See example below.
@returns {Object} The parsed file
@example
var data = io.readAmlSync('path/to/data.aml')
console.log(data) // json data
var data = io.readAmlSync('path/to/data-with-comments.aml', function (amlFile) {
amlFile.height = amlFile.height * 2
return amlFile
})
console.log(data) // json data with height multiplied by 2 | [
"Synchronously",
"read",
"an",
"ArchieML",
"file",
".",
"Returns",
"an",
"empty",
"object",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8069-L8075 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readCsv | function readCsv(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserCsv, parserOptions: parserOptions }, cb);
} | javascript | function readCsv(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserCsv, parserOptions: parserOptions }, cb);
} | [
"function",
"readCsv",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserCsv",
",",
"parserOptions",
":",
"parserOptions",
"}",
",",
"cb",
")",
";",
"}"
] | Asynchronously read a comma-separated value file. Returns an empty array if file is empty.
@function readCsv
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Called once for each row with the signature `(row, i)` and must return the transformed row. See example below or d3-dsv documentation for details.
@param {Function} callback Has signature `(err, data)`
@example
io.readCsv('path/to/data.csv', function (err, data) {
console.log(data) // Json data
})
// Transform values on load
io.readCsv('path/to/data.csv', function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
}, function (err, data) {
console.log(data) // Converted json data
})
// Pass in an object with a `map` key
io.readCsv('path/to/data.csv', {map: function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
}}, function (err, data) {
console.log(data) // Converted json data
}) | [
"Asynchronously",
"read",
"a",
"comma",
"-",
"separated",
"value",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8108-L8116 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readCsvSync | function readCsvSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserCsv, parserOptions: parserOptions });
} | javascript | function readCsvSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserCsv, parserOptions: parserOptions });
} | [
"function",
"readCsvSync",
"(",
"filePath",
",",
"opts_",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"opts_",
"!==",
"'undefined'",
")",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"return",
"readDataSync",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserCsv",
",",
"parserOptions",
":",
"parserOptions",
"}",
")",
";",
"}"
] | Synchronously read a comma-separated value file. Returns an empty array if file is empty.
@function readCsvSync
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Called once for each row with the signature `(row, i)` and must return the transformed row. See example below or d3-dsv documentation for details.
@returns {Array} the contents of the file as JSON
@example
var data = io.readCsvSync('path/to/data.csv')
console.log(data) // Json data
// Transform values on load
var data = io.readCsvSync('path/to/data.csv', function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
})
console.log(data) // Json data with casted values
// Pass in an object with a `map` key
var data = io.readCsvSync('path/to/data.csv', {map: function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
}})
console.log(data) // Json data with casted values | [
"Synchronously",
"read",
"a",
"comma",
"-",
"separated",
"value",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8146-L8152 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readJson | function readJson(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserJson, parserOptions: parserOptions }, cb);
} | javascript | function readJson(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserJson, parserOptions: parserOptions }, cb);
} | [
"function",
"readJson",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserJson",
",",
"parserOptions",
":",
"parserOptions",
"}",
",",
"cb",
")",
";",
"}"
] | Asynchronously read a JSON file. Returns an empty array if file is empty.
@function readJson
@param {String} filePath Input file path
@param {Function|Object} [parserOptions] Optional map function or an object specifying the optional options below.
@param {Function} [parserOptions.map] Map function. Called once for each row if your file is an array (it tests if the first non-whitespace character is a `[`) with a callback signature `(row, i)` and delegates to `_.map`. Otherwise it's considered an object and the callback the signature is `(value, key)` and delegates to `_.mapObject`. See example below.
@param {String} [parserOptions.filename] File name displayed in the error message.
@param {Function} [parserOptions.reviver] A function that prescribes how the value originally produced by parsing is mapped before being returned. See JSON.parse docs for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter
@param {Function} callback Has signature `(err, data)`
@example
io.readJson('path/to/data.json', function (err, data) {
console.log(data) // Json data
})
// Specify a map
io.readJson('path/to/data.json', function (row, i) {
row.height = row.height * 2
return row
}, function (err, data) {
console.log(data) // Json data with height multiplied by two
})
// Specify a filename
io.readJson('path/to/data.json', 'awesome-data.json', function (err, data) {
console.log(data) // Json data, any errors are reported with `fileName`.
})
// Specify a map and a filename
io.readJson('path/to/data.json', {
map: function (row, i) {
row.height = row.height * 2
return row
},
filename: 'awesome-data.json'
}, function (err, data) {
console.log(data) // Json data with any number values multiplied by two and errors reported with `fileName`
})
// Specify a map and a filename on json object
io.readJson('path/to/json-object.json', {
map: function (value, key) {
if (typeof value === 'number') {
return value * 2
}
return value
},
filename: 'awesome-data.json'
}, function (err, data) {
console.log(data) // Json data with any number values multiplied by two and errors reported with `fileName`
})
// Specify a reviver function and a filename
io.readJson('path/to/data.json', {
reviver: function (k, v) {
if (typeof v === 'number') {
return v * 2
}
return v
},
filename: 'awesome-data.json'
}, function (err, data) {
console.log(data) // Json data with any number values multiplied by two and errors reported with `fileName`
}) | [
"Asynchronously",
"read",
"a",
"JSON",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8220-L8228 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readJsonSync | function readJsonSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserJson, parserOptions: parserOptions });
} | javascript | function readJsonSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserJson, parserOptions: parserOptions });
} | [
"function",
"readJsonSync",
"(",
"filePath",
",",
"opts_",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"opts_",
"!==",
"'undefined'",
")",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"return",
"readDataSync",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserJson",
",",
"parserOptions",
":",
"parserOptions",
"}",
")",
";",
"}"
] | Synchronously read a JSON file. Returns an empty array if file is empty.
@function readJsonSync
@param {String} filePath Input file path
@param {Function|Object} [parserOptions] Optional map function or an object specifying the optional options below.
@param {Function} [parserOptions.map] Map function. Called once for each row if your file is an array (it tests if the first non-whitespace character is a `[`) with a callback signature `(row, i)` and delegates to `_.map`. Otherwise it's considered an object and the callback the signature is `(value, key)` and delegates to `_.mapObject`. See example below.
@param {String} [parserOptions.filename] File name displayed in the error message.
@param {Function} [parserOptions.reviver] A function that prescribes how the value originally produced by parsing is mapped before being returned. See JSON.parse docs for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter
@returns {Array|Object} The contents of the file as JSON
@example
var data = io.readJsonSync('path/to/data.json')
console.log(data) // Json data
// Specify a map
var data = io.readJson('path/to/data.json', function (k, v) {
if (typeof v === 'number') {
return v * 2
}
return v
})
console.log(data) // Json data with any number values multiplied by two
// Specify a filename
var data = io.readJson('path/to/data.json', 'awesome-data.json')
console.log(data) // Json data, any errors are reported with `fileName`.
// Specify a map and a filename
var data = io.readJsonSync('path/to/data.json', {
map: function (k, v) {
if (typeof v === 'number') {
return v * 2
}
return v
},
filename: 'awesome-data.json'
})
console.log(data) // Json data with any number values multiplied by two and errors reported with `fileName` | [
"Synchronously",
"read",
"a",
"JSON",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8271-L8277 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readPsv | function readPsv(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserPsv, parserOptions: parserOptions }, cb);
} | javascript | function readPsv(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserPsv, parserOptions: parserOptions }, cb);
} | [
"function",
"readPsv",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserPsv",
",",
"parserOptions",
":",
"parserOptions",
"}",
",",
"cb",
")",
";",
"}"
] | Asynchronously read a pipe-separated value file. Returns an empty array if file is empty.
@function readPsv
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Called once for each row with the signature `(row, i)` and must return the transformed row. See example below or d3-dsv documentation for details.
@param {Function} callback Has signature `(err, data)`
@example
io.readPsv('path/to/data.psv', function (err, data) {
console.log(data) // Json data
})
// Transform values on load
io.readPsv('path/to/data.psv', function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
}, function (err, data) {
console.log(data) // Json data with casted values
}) | [
"Asynchronously",
"read",
"a",
"pipe",
"-",
"separated",
"value",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8301-L8309 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readPsvSync | function readPsvSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserPsv, parserOptions: parserOptions });
} | javascript | function readPsvSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserPsv, parserOptions: parserOptions });
} | [
"function",
"readPsvSync",
"(",
"filePath",
",",
"opts_",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"opts_",
"!==",
"'undefined'",
")",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"return",
"readDataSync",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserPsv",
",",
"parserOptions",
":",
"parserOptions",
"}",
")",
";",
"}"
] | Synchronously read a pipe-separated value file. Returns an empty array if file is empty.
@function readPsvSync
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Called once for each row with the signature `(row, i)` and must return the transformed row. See example below or d3-dsv documentation for details.
@returns {Array} The contents of the file as JSON
@example
var data = io.readPsvSync('path/to/data.psv')
console.log(data) // Json data
var data = io.readPsvSync('path/to/data.psv', function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
})
console.log(data) // Json data with casted values | [
"Synchronously",
"read",
"a",
"pipe",
"-",
"separated",
"value",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8330-L8336 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readTsv | function readTsv(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserTsv, parserOptions: parserOptions }, cb);
} | javascript | function readTsv(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserTsv, parserOptions: parserOptions }, cb);
} | [
"function",
"readTsv",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserTsv",
",",
"parserOptions",
":",
"parserOptions",
"}",
",",
"cb",
")",
";",
"}"
] | Asynchronously read a tab-separated value file. Returns an empty array if file is empty.
@function readTsv
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Called once for each row with the signature `(row, i)` and must return the transformed row. See example below or d3-dsv documentation for details.
@param {Function} callback Has signature `(err, data)`
@example
io.readTsv('path/to/data.tsv', function (err, data) {
console.log(data) // Json data
})
// Transform values on load
io.readTsv('path/to/data.tsv', function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
}, function (err, data) {
console.log(data) // Json data with casted values
}) | [
"Asynchronously",
"read",
"a",
"tab",
"-",
"separated",
"value",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8360-L8368 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readTsvSync | function readTsvSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserTsv, parserOptions: parserOptions });
} | javascript | function readTsvSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserTsv, parserOptions: parserOptions });
} | [
"function",
"readTsvSync",
"(",
"filePath",
",",
"opts_",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"opts_",
"!==",
"'undefined'",
")",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"return",
"readDataSync",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserTsv",
",",
"parserOptions",
":",
"parserOptions",
"}",
")",
";",
"}"
] | Synchronously read a tab-separated value file. Returns an empty array if file is empty.
@function readTsvSync
@param {String} filePath Input file path
@param {Function} [map] Optional map function, called once for each row (header row skipped). Has signature `(row, i, columns)` and must return the transformed row. See example below or d3-dsv documentation for details.
@returns {Array} the contents of the file as JSON
@example
var data = io.readTsvSync('path/to/data.tsv')
console.log(data) // Json data
// Transform values on load
var data = io.readTsvSync('path/to/data.tsv', function (row, i, columns) {
console.log(columns) // [ 'name', 'occupation', 'height' ]
row.height = +row.height // Convert this value to a number
return row
})
console.log(data) // Json data with casted values | [
"Synchronously",
"read",
"a",
"tab",
"-",
"separated",
"value",
"file",
".",
"Returns",
"an",
"empty",
"array",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8390-L8396 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readTxt | function readTxt(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserTxt, parserOptions: parserOptions }, cb);
} | javascript | function readTxt(filePath, opts_, cb) {
var parserOptions;
if (typeof cb === 'undefined') {
cb = opts_;
} else {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
readData(filePath, { parser: parserTxt, parserOptions: parserOptions }, cb);
} | [
"function",
"readTxt",
"(",
"filePath",
",",
"opts_",
",",
"cb",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"cb",
"===",
"'undefined'",
")",
"{",
"cb",
"=",
"opts_",
";",
"}",
"else",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"readData",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserTxt",
",",
"parserOptions",
":",
"parserOptions",
"}",
",",
"cb",
")",
";",
"}"
] | Asynchronously read a text file. Returns an empty string if file is empty.
@function readTxt
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Takes the file read in as text and return the modified file. See example below.
@param {Function} callback Has signature `(err, data)`
@example
io.readTxt('path/to/data.txt', function (err, data) {
console.log(data) // string data
})
io.readTxt('path/to/data.txt', function (str) {
return str.replace(/hello/g, 'goodbye') // Replace all instances of `"hello"` with `"goodbye"`
}, function (err, data) {
console.log(data) // string data with values replaced
}) | [
"Asynchronously",
"read",
"a",
"text",
"file",
".",
"Returns",
"an",
"empty",
"string",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8417-L8425 | train |
mhkeller/indian-ocean | dist/indian-ocean.cjs.js | readTxtSync | function readTxtSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserTxt, parserOptions: parserOptions });
} | javascript | function readTxtSync(filePath, opts_) {
var parserOptions;
if (typeof opts_ !== 'undefined') {
parserOptions = typeof opts_ === 'function' ? { map: opts_ } : opts_;
}
return readDataSync(filePath, { parser: parserTxt, parserOptions: parserOptions });
} | [
"function",
"readTxtSync",
"(",
"filePath",
",",
"opts_",
")",
"{",
"var",
"parserOptions",
";",
"if",
"(",
"typeof",
"opts_",
"!==",
"'undefined'",
")",
"{",
"parserOptions",
"=",
"typeof",
"opts_",
"===",
"'function'",
"?",
"{",
"map",
":",
"opts_",
"}",
":",
"opts_",
";",
"}",
"return",
"readDataSync",
"(",
"filePath",
",",
"{",
"parser",
":",
"parserTxt",
",",
"parserOptions",
":",
"parserOptions",
"}",
")",
";",
"}"
] | Synchronously read a text file. Returns an empty string if file is empty.
@function readTxtSync
@param {String} filePath Input file path
@param {Function|Object} [map] Optional map function or an object with `map` key that is a function. Takes the file read in as text and must return the modified file. See example below.
@returns {String} the contents of the file as a string
@example
var data = io.readTxtSync('path/to/data.txt')
console.log(data) // string data
var data = io.readTxtSync('path/to/data.txt', function (str) {
return str.replace(/hello/g, 'goodbye') // Replace all instances of `"hello"` with `"goodbye"`
})
console.log(data) // string data with values replaced | [
"Synchronously",
"read",
"a",
"text",
"file",
".",
"Returns",
"an",
"empty",
"string",
"if",
"file",
"is",
"empty",
"."
] | 32b5b5799341370452b17ec2ac18529c849f3916 | https://github.com/mhkeller/indian-ocean/blob/32b5b5799341370452b17ec2ac18529c849f3916/dist/indian-ocean.cjs.js#L8444-L8450 | train |
ascartabelli/lamb | src/privates/_getInsertionIndex.js | _getInsertionIndex | function _getInsertionIndex (array, element, comparer, start, end) {
if (array.length === 0) {
return 0;
}
var pivot = (start + end) >> 1;
var result = comparer(
{ value: element, index: pivot },
{ value: array[pivot], index: pivot }
);
if (end - start <= 1) {
return result < 0 ? pivot : pivot + 1;
} else if (result < 0) {
return _getInsertionIndex(array, element, comparer, start, pivot);
} else if (result === 0) {
return pivot + 1;
} else {
return _getInsertionIndex(array, element, comparer, pivot, end);
}
} | javascript | function _getInsertionIndex (array, element, comparer, start, end) {
if (array.length === 0) {
return 0;
}
var pivot = (start + end) >> 1;
var result = comparer(
{ value: element, index: pivot },
{ value: array[pivot], index: pivot }
);
if (end - start <= 1) {
return result < 0 ? pivot : pivot + 1;
} else if (result < 0) {
return _getInsertionIndex(array, element, comparer, start, pivot);
} else if (result === 0) {
return pivot + 1;
} else {
return _getInsertionIndex(array, element, comparer, pivot, end);
}
} | [
"function",
"_getInsertionIndex",
"(",
"array",
",",
"element",
",",
"comparer",
",",
"start",
",",
"end",
")",
"{",
"if",
"(",
"array",
".",
"length",
"===",
"0",
")",
"{",
"return",
"0",
";",
"}",
"var",
"pivot",
"=",
"(",
"start",
"+",
"end",
")",
">>",
"1",
";",
"var",
"result",
"=",
"comparer",
"(",
"{",
"value",
":",
"element",
",",
"index",
":",
"pivot",
"}",
",",
"{",
"value",
":",
"array",
"[",
"pivot",
"]",
",",
"index",
":",
"pivot",
"}",
")",
";",
"if",
"(",
"end",
"-",
"start",
"<=",
"1",
")",
"{",
"return",
"result",
"<",
"0",
"?",
"pivot",
":",
"pivot",
"+",
"1",
";",
"}",
"else",
"if",
"(",
"result",
"<",
"0",
")",
"{",
"return",
"_getInsertionIndex",
"(",
"array",
",",
"element",
",",
"comparer",
",",
"start",
",",
"pivot",
")",
";",
"}",
"else",
"if",
"(",
"result",
"===",
"0",
")",
"{",
"return",
"pivot",
"+",
"1",
";",
"}",
"else",
"{",
"return",
"_getInsertionIndex",
"(",
"array",
",",
"element",
",",
"comparer",
",",
"pivot",
",",
"end",
")",
";",
"}",
"}"
] | Establishes at which index an element should be inserted in a sorted array to respect
the array order. Needs the comparer used to sort the array.
@private
@param {Array} array
@param {*} element
@param {Function} comparer
@param {Number} start
@param {Number} end
@returns {Number} | [
"Establishes",
"at",
"which",
"index",
"an",
"element",
"should",
"be",
"inserted",
"in",
"a",
"sorted",
"array",
"to",
"respect",
"the",
"array",
"order",
".",
"Needs",
"the",
"comparer",
"used",
"to",
"sort",
"the",
"array",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_getInsertionIndex.js#L12-L32 | train |
ascartabelli/lamb | src/privates/_getNumConsecutiveHits.js | _getNumConsecutiveHits | function _getNumConsecutiveHits (arrayLike, predicate) {
var idx = 0;
var len = arrayLike.length;
while (idx < len && predicate(arrayLike[idx], idx, arrayLike)) {
idx++;
}
return idx;
} | javascript | function _getNumConsecutiveHits (arrayLike, predicate) {
var idx = 0;
var len = arrayLike.length;
while (idx < len && predicate(arrayLike[idx], idx, arrayLike)) {
idx++;
}
return idx;
} | [
"function",
"_getNumConsecutiveHits",
"(",
"arrayLike",
",",
"predicate",
")",
"{",
"var",
"idx",
"=",
"0",
";",
"var",
"len",
"=",
"arrayLike",
".",
"length",
";",
"while",
"(",
"idx",
"<",
"len",
"&&",
"predicate",
"(",
"arrayLike",
"[",
"idx",
"]",
",",
"idx",
",",
"arrayLike",
")",
")",
"{",
"idx",
"++",
";",
"}",
"return",
"idx",
";",
"}"
] | Gets the number of consecutive elements satisfying a predicate in an array-like object.
@private
@param {ArrayLike} arrayLike
@param {ListIteratorCallback} predicate
@returns {Number} | [
"Gets",
"the",
"number",
"of",
"consecutive",
"elements",
"satisfying",
"a",
"predicate",
"in",
"an",
"array",
"-",
"like",
"object",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_getNumConsecutiveHits.js#L8-L17 | train |
AvrahamO/he-date | HeDate.js | function(src, dest) {
var i = 0;
var len = Math.min(src.length, dest.length);
while(i < len) {
dest[i] = src[i];
i++;
}
return dest;
} | javascript | function(src, dest) {
var i = 0;
var len = Math.min(src.length, dest.length);
while(i < len) {
dest[i] = src[i];
i++;
}
return dest;
} | [
"function",
"(",
"src",
",",
"dest",
")",
"{",
"var",
"i",
"=",
"0",
";",
"var",
"len",
"=",
"Math",
".",
"min",
"(",
"src",
".",
"length",
",",
"dest",
".",
"length",
")",
";",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"dest",
"[",
"i",
"]",
"=",
"src",
"[",
"i",
"]",
";",
"i",
"++",
";",
"}",
"return",
"dest",
";",
"}"
] | src - Array || Argument object
dest - Array | [
"src",
"-",
"Array",
"||",
"Argument",
"object",
"dest",
"-",
"Array"
] | 942049a4f39e3f57e44ed6f2bef1caa274e21b80 | https://github.com/AvrahamO/he-date/blob/942049a4f39e3f57e44ed6f2bef1caa274e21b80/HeDate.js#L49-L57 | train |
|
AvrahamO/he-date | HeDate.js | function(month, year1, year2) {
var leap1 = isLeap(year1 - 1);
var leap2 = isLeap(year2 - 1);
if(month < 5 + leap1) return 0;
return leap2 - leap1;
} | javascript | function(month, year1, year2) {
var leap1 = isLeap(year1 - 1);
var leap2 = isLeap(year2 - 1);
if(month < 5 + leap1) return 0;
return leap2 - leap1;
} | [
"function",
"(",
"month",
",",
"year1",
",",
"year2",
")",
"{",
"var",
"leap1",
"=",
"isLeap",
"(",
"year1",
"-",
"1",
")",
";",
"var",
"leap2",
"=",
"isLeap",
"(",
"year2",
"-",
"1",
")",
";",
"if",
"(",
"month",
"<",
"5",
"+",
"leap1",
")",
"return",
"0",
";",
"return",
"leap2",
"-",
"leap1",
";",
"}"
] | returns 0, 1 or -1 | [
"returns",
"0",
"1",
"or",
"-",
"1"
] | 942049a4f39e3f57e44ed6f2bef1caa274e21b80 | https://github.com/AvrahamO/he-date/blob/942049a4f39e3f57e44ed6f2bef1caa274e21b80/HeDate.js#L218-L224 | train |
|
ILLGrenoble/guacamole-common-js | src/Keyboard.js | function() {
/**
* Reference to this key event.
*/
var key_event = this;
/**
* An arbitrary timestamp in milliseconds, indicating this event's
* position in time relative to other events.
*
* @type {Number}
*/
this.timestamp = new Date().getTime();
/**
* Whether the default action of this key event should be prevented.
*
* @type {Boolean}
*/
this.defaultPrevented = false;
/**
* The keysym of the key associated with this key event, as determined
* by a best-effort guess using available event properties and keyboard
* state.
*
* @type {Number}
*/
this.keysym = null;
/**
* Whether the keysym value of this key event is known to be reliable.
* If false, the keysym may still be valid, but it's only a best guess,
* and future key events may be a better source of information.
*
* @type {Boolean}
*/
this.reliable = false;
/**
* Returns the number of milliseconds elapsed since this event was
* received.
*
* @return {Number} The number of milliseconds elapsed since this
* event was received.
*/
this.getAge = function() {
return new Date().getTime() - key_event.timestamp;
};
} | javascript | function() {
/**
* Reference to this key event.
*/
var key_event = this;
/**
* An arbitrary timestamp in milliseconds, indicating this event's
* position in time relative to other events.
*
* @type {Number}
*/
this.timestamp = new Date().getTime();
/**
* Whether the default action of this key event should be prevented.
*
* @type {Boolean}
*/
this.defaultPrevented = false;
/**
* The keysym of the key associated with this key event, as determined
* by a best-effort guess using available event properties and keyboard
* state.
*
* @type {Number}
*/
this.keysym = null;
/**
* Whether the keysym value of this key event is known to be reliable.
* If false, the keysym may still be valid, but it's only a best guess,
* and future key events may be a better source of information.
*
* @type {Boolean}
*/
this.reliable = false;
/**
* Returns the number of milliseconds elapsed since this event was
* received.
*
* @return {Number} The number of milliseconds elapsed since this
* event was received.
*/
this.getAge = function() {
return new Date().getTime() - key_event.timestamp;
};
} | [
"function",
"(",
")",
"{",
"var",
"key_event",
"=",
"this",
";",
"this",
".",
"timestamp",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"this",
".",
"defaultPrevented",
"=",
"false",
";",
"this",
".",
"keysym",
"=",
"null",
";",
"this",
".",
"reliable",
"=",
"false",
";",
"this",
".",
"getAge",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"key_event",
".",
"timestamp",
";",
"}",
";",
"}"
] | A key event having a corresponding timestamp. This event is non-specific.
Its subclasses should be used instead when recording specific key
events.
@private
@constructor | [
"A",
"key",
"event",
"having",
"a",
"corresponding",
"timestamp",
".",
"This",
"event",
"is",
"non",
"-",
"specific",
".",
"Its",
"subclasses",
"should",
"be",
"used",
"instead",
"when",
"recording",
"specific",
"key",
"events",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Keyboard.js#L66-L117 | train |
|
ILLGrenoble/guacamole-common-js | src/Keyboard.js | function(charCode) {
// We extend KeyEvent
KeyEvent.apply(this);
/**
* The Unicode codepoint of the character that would be typed by the
* key pressed.
*
* @type {Number}
*/
this.charCode = charCode;
// Pull keysym from char code
this.keysym = keysym_from_charcode(charCode);
// Keypress is always reliable
this.reliable = true;
} | javascript | function(charCode) {
// We extend KeyEvent
KeyEvent.apply(this);
/**
* The Unicode codepoint of the character that would be typed by the
* key pressed.
*
* @type {Number}
*/
this.charCode = charCode;
// Pull keysym from char code
this.keysym = keysym_from_charcode(charCode);
// Keypress is always reliable
this.reliable = true;
} | [
"function",
"(",
"charCode",
")",
"{",
"KeyEvent",
".",
"apply",
"(",
"this",
")",
";",
"this",
".",
"charCode",
"=",
"charCode",
";",
"this",
".",
"keysym",
"=",
"keysym_from_charcode",
"(",
"charCode",
")",
";",
"this",
".",
"reliable",
"=",
"true",
";",
"}"
] | Information related to the pressing of a key, which MUST be
associated with a printable character. The presence or absence of any
information within this object is browser-dependent.
@private
@constructor
@augments Guacamole.Keyboard.KeyEvent
@param {Number} charCode The Unicode codepoint of the character that
would be typed by the key pressed. | [
"Information",
"related",
"to",
"the",
"pressing",
"of",
"a",
"key",
"which",
"MUST",
"be",
"associated",
"with",
"a",
"printable",
"character",
".",
"The",
"presence",
"or",
"absence",
"of",
"any",
"information",
"within",
"this",
"object",
"is",
"browser",
"-",
"dependent",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Keyboard.js#L220-L239 | train |
|
ILLGrenoble/guacamole-common-js | src/Keyboard.js | update_modifier_state | function update_modifier_state(e) {
// Get state
var state = Guacamole.Keyboard.ModifierState.fromKeyboardEvent(e);
// Release alt if implicitly released
if (guac_keyboard.modifiers.alt && state.alt === false) {
guac_keyboard.release(0xFFE9); // Left alt
guac_keyboard.release(0xFFEA); // Right alt
guac_keyboard.release(0xFE03); // AltGr
}
// Release shift if implicitly released
if (guac_keyboard.modifiers.shift && state.shift === false) {
guac_keyboard.release(0xFFE1); // Left shift
guac_keyboard.release(0xFFE2); // Right shift
}
// Release ctrl if implicitly released
if (guac_keyboard.modifiers.ctrl && state.ctrl === false) {
guac_keyboard.release(0xFFE3); // Left ctrl
guac_keyboard.release(0xFFE4); // Right ctrl
}
// Release meta if implicitly released
if (guac_keyboard.modifiers.meta && state.meta === false) {
guac_keyboard.release(0xFFE7); // Left meta
guac_keyboard.release(0xFFE8); // Right meta
}
// Release hyper if implicitly released
if (guac_keyboard.modifiers.hyper && state.hyper === false) {
guac_keyboard.release(0xFFEB); // Left hyper
guac_keyboard.release(0xFFEC); // Right hyper
}
// Update state
guac_keyboard.modifiers = state;
} | javascript | function update_modifier_state(e) {
// Get state
var state = Guacamole.Keyboard.ModifierState.fromKeyboardEvent(e);
// Release alt if implicitly released
if (guac_keyboard.modifiers.alt && state.alt === false) {
guac_keyboard.release(0xFFE9); // Left alt
guac_keyboard.release(0xFFEA); // Right alt
guac_keyboard.release(0xFE03); // AltGr
}
// Release shift if implicitly released
if (guac_keyboard.modifiers.shift && state.shift === false) {
guac_keyboard.release(0xFFE1); // Left shift
guac_keyboard.release(0xFFE2); // Right shift
}
// Release ctrl if implicitly released
if (guac_keyboard.modifiers.ctrl && state.ctrl === false) {
guac_keyboard.release(0xFFE3); // Left ctrl
guac_keyboard.release(0xFFE4); // Right ctrl
}
// Release meta if implicitly released
if (guac_keyboard.modifiers.meta && state.meta === false) {
guac_keyboard.release(0xFFE7); // Left meta
guac_keyboard.release(0xFFE8); // Right meta
}
// Release hyper if implicitly released
if (guac_keyboard.modifiers.hyper && state.hyper === false) {
guac_keyboard.release(0xFFEB); // Left hyper
guac_keyboard.release(0xFFEC); // Right hyper
}
// Update state
guac_keyboard.modifiers = state;
} | [
"function",
"update_modifier_state",
"(",
"e",
")",
"{",
"var",
"state",
"=",
"Guacamole",
".",
"Keyboard",
".",
"ModifierState",
".",
"fromKeyboardEvent",
"(",
"e",
")",
";",
"if",
"(",
"guac_keyboard",
".",
"modifiers",
".",
"alt",
"&&",
"state",
".",
"alt",
"===",
"false",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"0xFFE9",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFEA",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFE03",
")",
";",
"}",
"if",
"(",
"guac_keyboard",
".",
"modifiers",
".",
"shift",
"&&",
"state",
".",
"shift",
"===",
"false",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"0xFFE1",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFE2",
")",
";",
"}",
"if",
"(",
"guac_keyboard",
".",
"modifiers",
".",
"ctrl",
"&&",
"state",
".",
"ctrl",
"===",
"false",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"0xFFE3",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFE4",
")",
";",
"}",
"if",
"(",
"guac_keyboard",
".",
"modifiers",
".",
"meta",
"&&",
"state",
".",
"meta",
"===",
"false",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"0xFFE7",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFE8",
")",
";",
"}",
"if",
"(",
"guac_keyboard",
".",
"modifiers",
".",
"hyper",
"&&",
"state",
".",
"hyper",
"===",
"false",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"0xFFEB",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFEC",
")",
";",
"}",
"guac_keyboard",
".",
"modifiers",
"=",
"state",
";",
"}"
] | Given a keyboard event, updates the local modifier state and remote
key state based on the modifier flags within the event. This function
pays no attention to keycodes.
@private
@param {KeyboardEvent} e
The keyboard event containing the flags to update. | [
"Given",
"a",
"keyboard",
"event",
"updates",
"the",
"local",
"modifier",
"state",
"and",
"remote",
"key",
"state",
"based",
"on",
"the",
"modifier",
"flags",
"within",
"the",
"event",
".",
"This",
"function",
"pays",
"no",
"attention",
"to",
"keycodes",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Keyboard.js#L811-L850 | train |
ILLGrenoble/guacamole-common-js | src/Keyboard.js | release_simulated_altgr | function release_simulated_altgr(keysym) {
// Both Ctrl+Alt must be pressed if simulated AltGr is in use
if (!guac_keyboard.modifiers.ctrl || !guac_keyboard.modifiers.alt)
return;
// Assume [A-Z] never require AltGr
if (keysym >= 0x0041 && keysym <= 0x005A)
return;
// Assume [a-z] never require AltGr
if (keysym >= 0x0061 && keysym <= 0x007A)
return;
// Release Ctrl+Alt if the keysym is printable
if (keysym <= 0xFF || (keysym & 0xFF000000) === 0x01000000) {
guac_keyboard.release(0xFFE3); // Left ctrl
guac_keyboard.release(0xFFE4); // Right ctrl
guac_keyboard.release(0xFFE9); // Left alt
guac_keyboard.release(0xFFEA); // Right alt
}
} | javascript | function release_simulated_altgr(keysym) {
// Both Ctrl+Alt must be pressed if simulated AltGr is in use
if (!guac_keyboard.modifiers.ctrl || !guac_keyboard.modifiers.alt)
return;
// Assume [A-Z] never require AltGr
if (keysym >= 0x0041 && keysym <= 0x005A)
return;
// Assume [a-z] never require AltGr
if (keysym >= 0x0061 && keysym <= 0x007A)
return;
// Release Ctrl+Alt if the keysym is printable
if (keysym <= 0xFF || (keysym & 0xFF000000) === 0x01000000) {
guac_keyboard.release(0xFFE3); // Left ctrl
guac_keyboard.release(0xFFE4); // Right ctrl
guac_keyboard.release(0xFFE9); // Left alt
guac_keyboard.release(0xFFEA); // Right alt
}
} | [
"function",
"release_simulated_altgr",
"(",
"keysym",
")",
"{",
"if",
"(",
"!",
"guac_keyboard",
".",
"modifiers",
".",
"ctrl",
"||",
"!",
"guac_keyboard",
".",
"modifiers",
".",
"alt",
")",
"return",
";",
"if",
"(",
"keysym",
">=",
"0x0041",
"&&",
"keysym",
"<=",
"0x005A",
")",
"return",
";",
"if",
"(",
"keysym",
">=",
"0x0061",
"&&",
"keysym",
"<=",
"0x007A",
")",
"return",
";",
"if",
"(",
"keysym",
"<=",
"0xFF",
"||",
"(",
"keysym",
"&",
"0xFF000000",
")",
"===",
"0x01000000",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"0xFFE3",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFE4",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFE9",
")",
";",
"guac_keyboard",
".",
"release",
"(",
"0xFFEA",
")",
";",
"}",
"}"
] | Releases Ctrl+Alt, if both are currently pressed and the given keysym
looks like a key that may require AltGr.
@private
@param {Number} keysym The key that was just pressed. | [
"Releases",
"Ctrl",
"+",
"Alt",
"if",
"both",
"are",
"currently",
"pressed",
"and",
"the",
"given",
"keysym",
"looks",
"like",
"a",
"key",
"that",
"may",
"require",
"AltGr",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Keyboard.js#L886-L908 | train |
ILLGrenoble/guacamole-common-js | src/Keyboard.js | interpret_event | function interpret_event() {
// Peek at first event in log
var first = eventLog[0];
if (!first)
return null;
// Keydown event
if (first instanceof KeydownEvent) {
var keysym = null;
var accepted_events = [];
// If event itself is reliable, no need to wait for other events
if (first.reliable) {
keysym = first.keysym;
accepted_events = eventLog.splice(0, 1);
}
// If keydown is immediately followed by a keypress, use the indicated character
else if (eventLog[1] instanceof KeypressEvent) {
keysym = eventLog[1].keysym;
accepted_events = eventLog.splice(0, 2);
}
// If keydown is immediately followed by anything else, then no
// keypress can possibly occur to clarify this event, and we must
// handle it now
else if (eventLog[1]) {
keysym = first.keysym;
accepted_events = eventLog.splice(0, 1);
}
// Fire a key press if valid events were found
if (accepted_events.length > 0) {
if (keysym) {
// Fire event
release_simulated_altgr(keysym);
var defaultPrevented = !guac_keyboard.press(keysym);
recentKeysym[first.keyCode] = keysym;
// If a key is pressed while meta is held down, the keyup will
// never be sent in Chrome, so send it now. (bug #108404)
if (guac_keyboard.modifiers.meta && keysym !== 0xFFE7 && keysym !== 0xFFE8)
guac_keyboard.release(keysym);
// Record whether default was prevented
for (var i=0; i<accepted_events.length; i++)
accepted_events[i].defaultPrevented = defaultPrevented;
}
return first;
}
} // end if keydown
// Keyup event
else if (first instanceof KeyupEvent) {
// Release specific key if known
var keysym = first.keysym;
if (keysym) {
guac_keyboard.release(keysym);
first.defaultPrevented = true;
}
// Otherwise, fall back to releasing all keys
else {
guac_keyboard.reset();
return first;
}
return eventLog.shift();
} // end if keyup
// Ignore any other type of event (keypress by itself is invalid)
else
return eventLog.shift();
// No event interpreted
return null;
} | javascript | function interpret_event() {
// Peek at first event in log
var first = eventLog[0];
if (!first)
return null;
// Keydown event
if (first instanceof KeydownEvent) {
var keysym = null;
var accepted_events = [];
// If event itself is reliable, no need to wait for other events
if (first.reliable) {
keysym = first.keysym;
accepted_events = eventLog.splice(0, 1);
}
// If keydown is immediately followed by a keypress, use the indicated character
else if (eventLog[1] instanceof KeypressEvent) {
keysym = eventLog[1].keysym;
accepted_events = eventLog.splice(0, 2);
}
// If keydown is immediately followed by anything else, then no
// keypress can possibly occur to clarify this event, and we must
// handle it now
else if (eventLog[1]) {
keysym = first.keysym;
accepted_events = eventLog.splice(0, 1);
}
// Fire a key press if valid events were found
if (accepted_events.length > 0) {
if (keysym) {
// Fire event
release_simulated_altgr(keysym);
var defaultPrevented = !guac_keyboard.press(keysym);
recentKeysym[first.keyCode] = keysym;
// If a key is pressed while meta is held down, the keyup will
// never be sent in Chrome, so send it now. (bug #108404)
if (guac_keyboard.modifiers.meta && keysym !== 0xFFE7 && keysym !== 0xFFE8)
guac_keyboard.release(keysym);
// Record whether default was prevented
for (var i=0; i<accepted_events.length; i++)
accepted_events[i].defaultPrevented = defaultPrevented;
}
return first;
}
} // end if keydown
// Keyup event
else if (first instanceof KeyupEvent) {
// Release specific key if known
var keysym = first.keysym;
if (keysym) {
guac_keyboard.release(keysym);
first.defaultPrevented = true;
}
// Otherwise, fall back to releasing all keys
else {
guac_keyboard.reset();
return first;
}
return eventLog.shift();
} // end if keyup
// Ignore any other type of event (keypress by itself is invalid)
else
return eventLog.shift();
// No event interpreted
return null;
} | [
"function",
"interpret_event",
"(",
")",
"{",
"var",
"first",
"=",
"eventLog",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"first",
")",
"return",
"null",
";",
"if",
"(",
"first",
"instanceof",
"KeydownEvent",
")",
"{",
"var",
"keysym",
"=",
"null",
";",
"var",
"accepted_events",
"=",
"[",
"]",
";",
"if",
"(",
"first",
".",
"reliable",
")",
"{",
"keysym",
"=",
"first",
".",
"keysym",
";",
"accepted_events",
"=",
"eventLog",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"}",
"else",
"if",
"(",
"eventLog",
"[",
"1",
"]",
"instanceof",
"KeypressEvent",
")",
"{",
"keysym",
"=",
"eventLog",
"[",
"1",
"]",
".",
"keysym",
";",
"accepted_events",
"=",
"eventLog",
".",
"splice",
"(",
"0",
",",
"2",
")",
";",
"}",
"else",
"if",
"(",
"eventLog",
"[",
"1",
"]",
")",
"{",
"keysym",
"=",
"first",
".",
"keysym",
";",
"accepted_events",
"=",
"eventLog",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"}",
"if",
"(",
"accepted_events",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"keysym",
")",
"{",
"release_simulated_altgr",
"(",
"keysym",
")",
";",
"var",
"defaultPrevented",
"=",
"!",
"guac_keyboard",
".",
"press",
"(",
"keysym",
")",
";",
"recentKeysym",
"[",
"first",
".",
"keyCode",
"]",
"=",
"keysym",
";",
"if",
"(",
"guac_keyboard",
".",
"modifiers",
".",
"meta",
"&&",
"keysym",
"!==",
"0xFFE7",
"&&",
"keysym",
"!==",
"0xFFE8",
")",
"guac_keyboard",
".",
"release",
"(",
"keysym",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"accepted_events",
".",
"length",
";",
"i",
"++",
")",
"accepted_events",
"[",
"i",
"]",
".",
"defaultPrevented",
"=",
"defaultPrevented",
";",
"}",
"return",
"first",
";",
"}",
"}",
"else",
"if",
"(",
"first",
"instanceof",
"KeyupEvent",
")",
"{",
"var",
"keysym",
"=",
"first",
".",
"keysym",
";",
"if",
"(",
"keysym",
")",
"{",
"guac_keyboard",
".",
"release",
"(",
"keysym",
")",
";",
"first",
".",
"defaultPrevented",
"=",
"true",
";",
"}",
"else",
"{",
"guac_keyboard",
".",
"reset",
"(",
")",
";",
"return",
"first",
";",
"}",
"return",
"eventLog",
".",
"shift",
"(",
")",
";",
"}",
"else",
"return",
"eventLog",
".",
"shift",
"(",
")",
";",
"return",
"null",
";",
"}"
] | Reads through the event log, interpreting the first event, if possible,
and returning that event. If no events can be interpreted, due to a
total lack of events or the need for more events, null is returned. Any
interpreted events are automatically removed from the log.
@private
@return {KeyEvent}
The first key event in the log, if it can be interpreted, or null
otherwise. | [
"Reads",
"through",
"the",
"event",
"log",
"interpreting",
"the",
"first",
"event",
"if",
"possible",
"and",
"returning",
"that",
"event",
".",
"If",
"no",
"events",
"can",
"be",
"interpreted",
"due",
"to",
"a",
"total",
"lack",
"of",
"events",
"or",
"the",
"need",
"for",
"more",
"events",
"null",
"is",
"returned",
".",
"Any",
"interpreted",
"events",
"are",
"automatically",
"removed",
"from",
"the",
"log",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Keyboard.js#L921-L1008 | train |
the-simian/gulp-concat-filenames | index.js | function(str) {
var output;
try {
output = opts.template(str);
} catch (e) {
e.message = error.badTemplate + ': ' + e.message;
return this.emit('error', new PluginError('gulp-concat-filenames', e));
}
if (typeof output !== 'string') {
return this.emit('error', new PluginError('gulp-concat-filenames', error.badTemplate));
}
return output;
} | javascript | function(str) {
var output;
try {
output = opts.template(str);
} catch (e) {
e.message = error.badTemplate + ': ' + e.message;
return this.emit('error', new PluginError('gulp-concat-filenames', e));
}
if (typeof output !== 'string') {
return this.emit('error', new PluginError('gulp-concat-filenames', error.badTemplate));
}
return output;
} | [
"function",
"(",
"str",
")",
"{",
"var",
"output",
";",
"try",
"{",
"output",
"=",
"opts",
".",
"template",
"(",
"str",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"e",
".",
"message",
"=",
"error",
".",
"badTemplate",
"+",
"': '",
"+",
"e",
".",
"message",
";",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"PluginError",
"(",
"'gulp-concat-filenames'",
",",
"e",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"output",
"!==",
"'string'",
")",
"{",
"return",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"PluginError",
"(",
"'gulp-concat-filenames'",
",",
"error",
".",
"badTemplate",
")",
")",
";",
"}",
"return",
"output",
";",
"}"
] | Make sure template errors reach the output | [
"Make",
"sure",
"template",
"errors",
"reach",
"the",
"output"
] | 5b521d82b7867623e43e41647ad7cac6ca2f11b8 | https://github.com/the-simian/gulp-concat-filenames/blob/5b521d82b7867623e43e41647ad7cac6ca2f11b8/index.js#L39-L52 | train |
|
kibertoad/objection-swagger | lib/transformers/query-param.schema.transformer.js | transformIntoQueryParamSchema | function transformIntoQueryParamSchema(processedSchema) {
return _.transform(
processedSchema.items.properties,
(result, value, key) => {
const parameter = Object.assign(
{
name: key
},
value,
{
type: Array.isArray(value.type) ? value.type[0] : value.type,
required: !_.includes(value.type, "null")
}
);
result.push(parameter);
},
[]
);
} | javascript | function transformIntoQueryParamSchema(processedSchema) {
return _.transform(
processedSchema.items.properties,
(result, value, key) => {
const parameter = Object.assign(
{
name: key
},
value,
{
type: Array.isArray(value.type) ? value.type[0] : value.type,
required: !_.includes(value.type, "null")
}
);
result.push(parameter);
},
[]
);
} | [
"function",
"transformIntoQueryParamSchema",
"(",
"processedSchema",
")",
"{",
"return",
"_",
".",
"transform",
"(",
"processedSchema",
".",
"items",
".",
"properties",
",",
"(",
"result",
",",
"value",
",",
"key",
")",
"=>",
"{",
"const",
"parameter",
"=",
"Object",
".",
"assign",
"(",
"{",
"name",
":",
"key",
"}",
",",
"value",
",",
"{",
"type",
":",
"Array",
".",
"isArray",
"(",
"value",
".",
"type",
")",
"?",
"value",
".",
"type",
"[",
"0",
"]",
":",
"value",
".",
"type",
",",
"required",
":",
"!",
"_",
".",
"includes",
"(",
"value",
".",
"type",
",",
"\"null\"",
")",
"}",
")",
";",
"result",
".",
"push",
"(",
"parameter",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Transforms JSON-Schema to be usable as Swagger endpoint query param schema
@param {Object} processedSchema
@returns {*} | [
"Transforms",
"JSON",
"-",
"Schema",
"to",
"be",
"usable",
"as",
"Swagger",
"endpoint",
"query",
"param",
"schema"
] | 2109b58ce323e78252729a46bcc94e617035b541 | https://github.com/kibertoad/objection-swagger/blob/2109b58ce323e78252729a46bcc94e617035b541/lib/transformers/query-param.schema.transformer.js#L8-L26 | train |
jorisvervuurt/JVSDisplayOTron | lib/dothat/dothat.js | DOTHAT | function DOTHAT() {
if (!(this instanceof DOTHAT)) {
return new DOTHAT();
}
this.displayOTron = new DisplayOTron('HAT');
this.lcd = new LCD(this.displayOTron);
this.backlight = new Backlight(this.displayOTron);
this.barGraph = new BarGraph(this.displayOTron);
this.touch = new Touch(this.displayOTron);
} | javascript | function DOTHAT() {
if (!(this instanceof DOTHAT)) {
return new DOTHAT();
}
this.displayOTron = new DisplayOTron('HAT');
this.lcd = new LCD(this.displayOTron);
this.backlight = new Backlight(this.displayOTron);
this.barGraph = new BarGraph(this.displayOTron);
this.touch = new Touch(this.displayOTron);
} | [
"function",
"DOTHAT",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"DOTHAT",
")",
")",
"{",
"return",
"new",
"DOTHAT",
"(",
")",
";",
"}",
"this",
".",
"displayOTron",
"=",
"new",
"DisplayOTron",
"(",
"'HAT'",
")",
";",
"this",
".",
"lcd",
"=",
"new",
"LCD",
"(",
"this",
".",
"displayOTron",
")",
";",
"this",
".",
"backlight",
"=",
"new",
"Backlight",
"(",
"this",
".",
"displayOTron",
")",
";",
"this",
".",
"barGraph",
"=",
"new",
"BarGraph",
"(",
"this",
".",
"displayOTron",
")",
";",
"this",
".",
"touch",
"=",
"new",
"Touch",
"(",
"this",
".",
"displayOTron",
")",
";",
"}"
] | Creates a new `DOTHAT` object.
@constructor | [
"Creates",
"a",
"new",
"DOTHAT",
"object",
"."
] | c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc | https://github.com/jorisvervuurt/JVSDisplayOTron/blob/c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc/lib/dothat/dothat.js#L44-L54 | train |
Accela-Inc/accela-rest-nodejs | lib/rest-client.js | setAuthType | function setAuthType(auth_type) {
var headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (auth_type == 'AccessToken') {
headers['Authorization'] = _config.access_token;
}
else if (auth_type == 'AppCredentials') {
headers['x-accela-appid'] = _config.app_id
headers['x-accela-appsecret'] = _config.app_secret;
}
else {
headers['x-accela-appid'] = _config.app_id
headers['x-accela-agency'] = _config.agency;
headers['x-accela-environment'] = _config.environment;
}
return headers;
} | javascript | function setAuthType(auth_type) {
var headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (auth_type == 'AccessToken') {
headers['Authorization'] = _config.access_token;
}
else if (auth_type == 'AppCredentials') {
headers['x-accela-appid'] = _config.app_id
headers['x-accela-appsecret'] = _config.app_secret;
}
else {
headers['x-accela-appid'] = _config.app_id
headers['x-accela-agency'] = _config.agency;
headers['x-accela-environment'] = _config.environment;
}
return headers;
} | [
"function",
"setAuthType",
"(",
"auth_type",
")",
"{",
"var",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Accept'",
":",
"'application/json'",
"}",
";",
"if",
"(",
"auth_type",
"==",
"'AccessToken'",
")",
"{",
"headers",
"[",
"'Authorization'",
"]",
"=",
"_config",
".",
"access_token",
";",
"}",
"else",
"if",
"(",
"auth_type",
"==",
"'AppCredentials'",
")",
"{",
"headers",
"[",
"'x-accela-appid'",
"]",
"=",
"_config",
".",
"app_id",
"headers",
"[",
"'x-accela-appsecret'",
"]",
"=",
"_config",
".",
"app_secret",
";",
"}",
"else",
"{",
"headers",
"[",
"'x-accela-appid'",
"]",
"=",
"_config",
".",
"app_id",
"headers",
"[",
"'x-accela-agency'",
"]",
"=",
"_config",
".",
"agency",
";",
"headers",
"[",
"'x-accela-environment'",
"]",
"=",
"_config",
".",
"environment",
";",
"}",
"return",
"headers",
";",
"}"
] | Method to set authorization type. | [
"Method",
"to",
"set",
"authorization",
"type",
"."
] | 8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e | https://github.com/Accela-Inc/accela-rest-nodejs/blob/8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e/lib/rest-client.js#L133-L152 | train |
Accela-Inc/accela-rest-nodejs | lib/rest-client.js | escapeCharacters | function escapeCharacters(params) {
return params;
var find = new Array('.','-','%','/','\\\\',':','*','\\','<','>','|','?',' ','&','#');
var replace = new Array('.0','.1','.2','.3','.4','.5','.6','.7','.8','.9','.a','.b','.c','.d','.e');
var escaped = {};
for (var param in params) {
if(typeof(params[param]) == 'string') {
escaped[param] = replaceCharacter(find, replace, params[param]);
}
else {
escaped[param] = params[param];
}
}
return escaped;
} | javascript | function escapeCharacters(params) {
return params;
var find = new Array('.','-','%','/','\\\\',':','*','\\','<','>','|','?',' ','&','#');
var replace = new Array('.0','.1','.2','.3','.4','.5','.6','.7','.8','.9','.a','.b','.c','.d','.e');
var escaped = {};
for (var param in params) {
if(typeof(params[param]) == 'string') {
escaped[param] = replaceCharacter(find, replace, params[param]);
}
else {
escaped[param] = params[param];
}
}
return escaped;
} | [
"function",
"escapeCharacters",
"(",
"params",
")",
"{",
"return",
"params",
";",
"var",
"find",
"=",
"new",
"Array",
"(",
"'.'",
",",
"'-'",
",",
"'%'",
",",
"'/'",
",",
"'\\\\\\\\'",
",",
"\\\\",
",",
"\\\\",
",",
"':'",
",",
"'*'",
",",
"'\\\\'",
",",
"\\\\",
",",
"'<'",
",",
"'>'",
",",
"'|'",
",",
"'?'",
")",
";",
"' '",
"'&'",
"'#'",
"var",
"replace",
"=",
"new",
"Array",
"(",
"'.0'",
",",
"'.1'",
",",
"'.2'",
",",
"'.3'",
",",
"'.4'",
",",
"'.5'",
",",
"'.6'",
",",
"'.7'",
",",
"'.8'",
",",
"'.9'",
",",
"'.a'",
",",
"'.b'",
",",
"'.c'",
",",
"'.d'",
",",
"'.e'",
")",
";",
"}"
] | Method to escape special characters. | [
"Method",
"to",
"escape",
"special",
"characters",
"."
] | 8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e | https://github.com/Accela-Inc/accela-rest-nodejs/blob/8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e/lib/rest-client.js#L155-L169 | train |
Accela-Inc/accela-rest-nodejs | lib/rest-client.js | replaceCharacter | function replaceCharacter(search, replace, subject, count) {
var i = 0, j = 0, temp = '', repl = '', sl = 0,
fl = 0, f = [].concat(search), r = [].concat(replace),
s = subject, ra = Object.prototype.toString.call(r) === '[object Array]',
sa = Object.prototype.toString.call(s) === '[object Array]', s = [].concat(s);
if(typeof(search) === 'object' && typeof(replace) === 'string' ) {
temp = replace;
replace = new Array();
for (i=0; i < search.length; i+=1) {
replace[i] = temp;
}
temp = '';
r = [].concat(replace);
ra = Object.prototype.toString.call(r) === '[object Array]';
}
if (count) {
this.window[count] = 0;
}
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue;
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + '';
repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
s[i] = (temp)
.split(f[j])
.join(repl);
if (count) {
this.window[count] += ((temp.split(f[j])).length - 1);
}
}
}
return sa ? s : s[0];
} | javascript | function replaceCharacter(search, replace, subject, count) {
var i = 0, j = 0, temp = '', repl = '', sl = 0,
fl = 0, f = [].concat(search), r = [].concat(replace),
s = subject, ra = Object.prototype.toString.call(r) === '[object Array]',
sa = Object.prototype.toString.call(s) === '[object Array]', s = [].concat(s);
if(typeof(search) === 'object' && typeof(replace) === 'string' ) {
temp = replace;
replace = new Array();
for (i=0; i < search.length; i+=1) {
replace[i] = temp;
}
temp = '';
r = [].concat(replace);
ra = Object.prototype.toString.call(r) === '[object Array]';
}
if (count) {
this.window[count] = 0;
}
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue;
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + '';
repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
s[i] = (temp)
.split(f[j])
.join(repl);
if (count) {
this.window[count] += ((temp.split(f[j])).length - 1);
}
}
}
return sa ? s : s[0];
} | [
"function",
"replaceCharacter",
"(",
"search",
",",
"replace",
",",
"subject",
",",
"count",
")",
"{",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"0",
",",
"temp",
"=",
"''",
",",
"repl",
"=",
"''",
",",
"sl",
"=",
"0",
",",
"fl",
"=",
"0",
",",
"f",
"=",
"[",
"]",
".",
"concat",
"(",
"search",
")",
",",
"r",
"=",
"[",
"]",
".",
"concat",
"(",
"replace",
")",
",",
"s",
"=",
"subject",
",",
"ra",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"r",
")",
"===",
"'[object Array]'",
",",
"sa",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"s",
")",
"===",
"'[object Array]'",
",",
"s",
"=",
"[",
"]",
".",
"concat",
"(",
"s",
")",
";",
"if",
"(",
"typeof",
"(",
"search",
")",
"===",
"'object'",
"&&",
"typeof",
"(",
"replace",
")",
"===",
"'string'",
")",
"{",
"temp",
"=",
"replace",
";",
"replace",
"=",
"new",
"Array",
"(",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"search",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"replace",
"[",
"i",
"]",
"=",
"temp",
";",
"}",
"temp",
"=",
"''",
";",
"r",
"=",
"[",
"]",
".",
"concat",
"(",
"replace",
")",
";",
"ra",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"r",
")",
"===",
"'[object Array]'",
";",
"}",
"if",
"(",
"count",
")",
"{",
"this",
".",
"window",
"[",
"count",
"]",
"=",
"0",
";",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"sl",
"=",
"s",
".",
"length",
";",
"i",
"<",
"sl",
";",
"i",
"++",
")",
"{",
"if",
"(",
"s",
"[",
"i",
"]",
"===",
"''",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"j",
"=",
"0",
",",
"fl",
"=",
"f",
".",
"length",
";",
"j",
"<",
"fl",
";",
"j",
"++",
")",
"{",
"temp",
"=",
"s",
"[",
"i",
"]",
"+",
"''",
";",
"repl",
"=",
"ra",
"?",
"(",
"r",
"[",
"j",
"]",
"!==",
"undefined",
"?",
"r",
"[",
"j",
"]",
":",
"''",
")",
":",
"r",
"[",
"0",
"]",
";",
"s",
"[",
"i",
"]",
"=",
"(",
"temp",
")",
".",
"split",
"(",
"f",
"[",
"j",
"]",
")",
".",
"join",
"(",
"repl",
")",
";",
"if",
"(",
"count",
")",
"{",
"this",
".",
"window",
"[",
"count",
"]",
"+=",
"(",
"(",
"temp",
".",
"split",
"(",
"f",
"[",
"j",
"]",
")",
")",
".",
"length",
"-",
"1",
")",
";",
"}",
"}",
"}",
"return",
"sa",
"?",
"s",
":",
"s",
"[",
"0",
"]",
";",
"}"
] | Method for character replacement. | [
"Method",
"for",
"character",
"replacement",
"."
] | 8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e | https://github.com/Accela-Inc/accela-rest-nodejs/blob/8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e/lib/rest-client.js#L172-L209 | train |
Accela-Inc/accela-rest-nodejs | lib/rest-client.js | buildQueryString | function buildQueryString(params) {
var querystring = '';
for(param in params) {
querystring += '&' + param + '=' + params[param];
}
return querystring;
} | javascript | function buildQueryString(params) {
var querystring = '';
for(param in params) {
querystring += '&' + param + '=' + params[param];
}
return querystring;
} | [
"function",
"buildQueryString",
"(",
"params",
")",
"{",
"var",
"querystring",
"=",
"''",
";",
"for",
"(",
"param",
"in",
"params",
")",
"{",
"querystring",
"+=",
"'&'",
"+",
"param",
"+",
"'='",
"+",
"params",
"[",
"param",
"]",
";",
"}",
"return",
"querystring",
";",
"}"
] | Utility function to build querystring parameters for API call. | [
"Utility",
"function",
"to",
"build",
"querystring",
"parameters",
"for",
"API",
"call",
"."
] | 8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e | https://github.com/Accela-Inc/accela-rest-nodejs/blob/8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e/lib/rest-client.js#L220-L226 | train |
Accela-Inc/accela-rest-nodejs | lib/rest-client.js | makeRequest | function makeRequest(options, callback) {
request(options, function (error, response, body){
if (error) {
callback(error, null);
}
else if (response.statusCode == 200) {
callback( null, JSON.parse(body));
}
else {
callback(new Error('HTTP Response Code: ' + response.statusCode), null);
}
});
} | javascript | function makeRequest(options, callback) {
request(options, function (error, response, body){
if (error) {
callback(error, null);
}
else if (response.statusCode == 200) {
callback( null, JSON.parse(body));
}
else {
callback(new Error('HTTP Response Code: ' + response.statusCode), null);
}
});
} | [
"function",
"makeRequest",
"(",
"options",
",",
"callback",
")",
"{",
"request",
"(",
"options",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"null",
")",
";",
"}",
"else",
"if",
"(",
"response",
".",
"statusCode",
"==",
"200",
")",
"{",
"callback",
"(",
"null",
",",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'HTTP Response Code: '",
"+",
"response",
".",
"statusCode",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] | Private method to make API call. | [
"Private",
"method",
"to",
"make",
"API",
"call",
"."
] | 8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e | https://github.com/Accela-Inc/accela-rest-nodejs/blob/8f79d5f48d1244b3ab9afd958e7c9ae1f7ecbb0e/lib/rest-client.js#L229-L241 | train |
aMarCruz/jspreproc | lib/options.js | _setFilter | function _setFilter(filt) {
filt = filt.trim()
if (filt === 'all')
this.filter = filt
else if (filt in _filters) {
if (this.filter !== 'all' && this.filter.indexOf(filt) < 0)
this.filter.push(filt)
}
else this.invalid('filter', filt)
} | javascript | function _setFilter(filt) {
filt = filt.trim()
if (filt === 'all')
this.filter = filt
else if (filt in _filters) {
if (this.filter !== 'all' && this.filter.indexOf(filt) < 0)
this.filter.push(filt)
}
else this.invalid('filter', filt)
} | [
"function",
"_setFilter",
"(",
"filt",
")",
"{",
"filt",
"=",
"filt",
".",
"trim",
"(",
")",
"if",
"(",
"filt",
"===",
"'all'",
")",
"this",
".",
"filter",
"=",
"filt",
"else",
"if",
"(",
"filt",
"in",
"_filters",
")",
"{",
"if",
"(",
"this",
".",
"filter",
"!==",
"'all'",
"&&",
"this",
".",
"filter",
".",
"indexOf",
"(",
"filt",
")",
"<",
"0",
")",
"this",
".",
"filter",
".",
"push",
"(",
"filt",
")",
"}",
"else",
"this",
".",
"invalid",
"(",
"'filter'",
",",
"filt",
")",
"}"
] | Enable filters for comments, 'all' enable all filters | [
"Enable",
"filters",
"for",
"comments",
"all",
"enable",
"all",
"filters"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/options.js#L175-L184 | train |
aMarCruz/jspreproc | lib/options.js | _createFilter | function _createFilter(res) {
for (var i = 0; i < res.length; ++i) {
var f = res[i]
if (f instanceof RegExp)
custfilt.push(f)
else {
//console.log('--- creating regex with `' + str + '`')
try {
f = new RegExp(f)
custfilt.push(f)
}
catch (e) {
f = null
}
if (!f) this.invalid('custom filter', res[i])
}
}
} | javascript | function _createFilter(res) {
for (var i = 0; i < res.length; ++i) {
var f = res[i]
if (f instanceof RegExp)
custfilt.push(f)
else {
//console.log('--- creating regex with `' + str + '`')
try {
f = new RegExp(f)
custfilt.push(f)
}
catch (e) {
f = null
}
if (!f) this.invalid('custom filter', res[i])
}
}
} | [
"function",
"_createFilter",
"(",
"res",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"res",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"f",
"=",
"res",
"[",
"i",
"]",
"if",
"(",
"f",
"instanceof",
"RegExp",
")",
"custfilt",
".",
"push",
"(",
"f",
")",
"else",
"{",
"try",
"{",
"f",
"=",
"new",
"RegExp",
"(",
"f",
")",
"custfilt",
".",
"push",
"(",
"f",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"f",
"=",
"null",
"}",
"if",
"(",
"!",
"f",
")",
"this",
".",
"invalid",
"(",
"'custom filter'",
",",
"res",
"[",
"i",
"]",
")",
"}",
"}",
"}"
] | Creates a custom filter | [
"Creates",
"a",
"custom",
"filter"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/options.js#L187-L205 | train |
ascartabelli/lamb | src/privates/_getPathKey.js | _getPathKey | function _getPathKey (target, key, includeNonEnumerables) {
if (includeNonEnumerables && key in Object(target) || _isEnumerable(target, key)) {
return key;
}
var n = +key;
var len = target && target.length;
return n >= -len && n < len ? n < 0 ? n + len : n : void 0;
} | javascript | function _getPathKey (target, key, includeNonEnumerables) {
if (includeNonEnumerables && key in Object(target) || _isEnumerable(target, key)) {
return key;
}
var n = +key;
var len = target && target.length;
return n >= -len && n < len ? n < 0 ? n + len : n : void 0;
} | [
"function",
"_getPathKey",
"(",
"target",
",",
"key",
",",
"includeNonEnumerables",
")",
"{",
"if",
"(",
"includeNonEnumerables",
"&&",
"key",
"in",
"Object",
"(",
"target",
")",
"||",
"_isEnumerable",
"(",
"target",
",",
"key",
")",
")",
"{",
"return",
"key",
";",
"}",
"var",
"n",
"=",
"+",
"key",
";",
"var",
"len",
"=",
"target",
"&&",
"target",
".",
"length",
";",
"return",
"n",
">=",
"-",
"len",
"&&",
"n",
"<",
"len",
"?",
"n",
"<",
"0",
"?",
"n",
"+",
"len",
":",
"n",
":",
"void",
"0",
";",
"}"
] | Helper to retrieve the correct key while evaluating a path.
@private
@param {Object} target
@param {String} key
@param {Boolean} includeNonEnumerables
@returns {String|Number|Undefined} | [
"Helper",
"to",
"retrieve",
"the",
"correct",
"key",
"while",
"evaluating",
"a",
"path",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_getPathKey.js#L11-L20 | train |
ascartabelli/lamb | src/privates/_sorter.js | _sorter | function _sorter (reader, isDescending, comparer) {
if (typeof reader !== "function" || reader === identity) {
reader = null;
}
if (typeof comparer !== "function") {
comparer = _comparer;
}
return {
isDescending: isDescending === true,
compare: function (a, b) {
if (reader) {
a = reader(a);
b = reader(b);
}
return comparer(a, b);
}
};
} | javascript | function _sorter (reader, isDescending, comparer) {
if (typeof reader !== "function" || reader === identity) {
reader = null;
}
if (typeof comparer !== "function") {
comparer = _comparer;
}
return {
isDescending: isDescending === true,
compare: function (a, b) {
if (reader) {
a = reader(a);
b = reader(b);
}
return comparer(a, b);
}
};
} | [
"function",
"_sorter",
"(",
"reader",
",",
"isDescending",
",",
"comparer",
")",
"{",
"if",
"(",
"typeof",
"reader",
"!==",
"\"function\"",
"||",
"reader",
"===",
"identity",
")",
"{",
"reader",
"=",
"null",
";",
"}",
"if",
"(",
"typeof",
"comparer",
"!==",
"\"function\"",
")",
"{",
"comparer",
"=",
"_comparer",
";",
"}",
"return",
"{",
"isDescending",
":",
"isDescending",
"===",
"true",
",",
"compare",
":",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"reader",
")",
"{",
"a",
"=",
"reader",
"(",
"a",
")",
";",
"b",
"=",
"reader",
"(",
"b",
")",
";",
"}",
"return",
"comparer",
"(",
"a",
",",
"b",
")",
";",
"}",
"}",
";",
"}"
] | Builds a sorting criterion. If the comparer function is missing, the default
comparer will be used instead.
@private
@param {Function} reader
@param {Boolean} isDescending
@param {Function} [comparer]
@returns {Sorter} | [
"Builds",
"a",
"sorting",
"criterion",
".",
"If",
"the",
"comparer",
"function",
"is",
"missing",
"the",
"default",
"comparer",
"will",
"be",
"used",
"instead",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_sorter.js#L13-L33 | train |
ascartabelli/lamb | src/privates/_merge.js | _merge | function _merge (getKeys, a, b) {
return reduce([a, b], function (result, source) {
forEach(getKeys(source), function (key) {
result[key] = source[key];
});
return result;
}, {});
} | javascript | function _merge (getKeys, a, b) {
return reduce([a, b], function (result, source) {
forEach(getKeys(source), function (key) {
result[key] = source[key];
});
return result;
}, {});
} | [
"function",
"_merge",
"(",
"getKeys",
",",
"a",
",",
"b",
")",
"{",
"return",
"reduce",
"(",
"[",
"a",
",",
"b",
"]",
",",
"function",
"(",
"result",
",",
"source",
")",
"{",
"forEach",
"(",
"getKeys",
"(",
"source",
")",
",",
"function",
"(",
"key",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] | Merges the received objects using the provided function to retrieve their keys.
@private
@param {Function} getKeys
@param {Object} a
@param {Object} b
@returns {Function} | [
"Merges",
"the",
"received",
"objects",
"using",
"the",
"provided",
"function",
"to",
"retrieve",
"their",
"keys",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_merge.js#L12-L20 | train |
wearefractal/recorder | recorder.js | trigger | function trigger(el, name, options){
var event, type;
type = eventTypes[name];
if (!type) {
throw new SyntaxError('Unknown event type: '+type);
}
options = options || {};
inherit(defaults, options);
if (document.createEvent) {
// Standard Event
event = document.createEvent(type);
initializers[type](el, name, event, options);
el.dispatchEvent(event);
} else {
// IE Event
event = document.createEventObject();
for (var key in options){
event[key] = options[key];
}
el.fireEvent('on' + name, event);
}
} | javascript | function trigger(el, name, options){
var event, type;
type = eventTypes[name];
if (!type) {
throw new SyntaxError('Unknown event type: '+type);
}
options = options || {};
inherit(defaults, options);
if (document.createEvent) {
// Standard Event
event = document.createEvent(type);
initializers[type](el, name, event, options);
el.dispatchEvent(event);
} else {
// IE Event
event = document.createEventObject();
for (var key in options){
event[key] = options[key];
}
el.fireEvent('on' + name, event);
}
} | [
"function",
"trigger",
"(",
"el",
",",
"name",
",",
"options",
")",
"{",
"var",
"event",
",",
"type",
";",
"type",
"=",
"eventTypes",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"type",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Unknown event type: '",
"+",
"type",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"inherit",
"(",
"defaults",
",",
"options",
")",
";",
"if",
"(",
"document",
".",
"createEvent",
")",
"{",
"event",
"=",
"document",
".",
"createEvent",
"(",
"type",
")",
";",
"initializers",
"[",
"type",
"]",
"(",
"el",
",",
"name",
",",
"event",
",",
"options",
")",
";",
"el",
".",
"dispatchEvent",
"(",
"event",
")",
";",
"}",
"else",
"{",
"event",
"=",
"document",
".",
"createEventObject",
"(",
")",
";",
"for",
"(",
"var",
"key",
"in",
"options",
")",
"{",
"event",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
";",
"}",
"el",
".",
"fireEvent",
"(",
"'on'",
"+",
"name",
",",
"event",
")",
";",
"}",
"}"
] | Trigger a DOM event.
trigger(document.body, "click", {clientX: 10, clientY: 35});
Where sensible, sane defaults will be filled in. See the list of event
types for supported events.
Loosely based on:
https://github.com/kangax/protolicious/blob/master/event.simulate.js | [
"Trigger",
"a",
"DOM",
"event",
"."
] | 527cca4f66560ea68b769f24ae1393f095c494f0 | https://github.com/wearefractal/recorder/blob/527cca4f66560ea68b769f24ae1393f095c494f0/recorder.js#L447-L471 | train |
aMarCruz/jspreproc | spec/helpers/SpecHelper.js | function (util) {
function printable(str) {
return ('' + str).replace(/\n/g, '\\n').replace(/\r/g, '\\r')
}
function compare(actual, expected) {
var pass = actual === expected
return {
pass: pass,
message: util.buildFailureMessage(
'toHasLinesLike', pass, printable(actual), printable(expected))
}
}
return {compare: compare}
} | javascript | function (util) {
function printable(str) {
return ('' + str).replace(/\n/g, '\\n').replace(/\r/g, '\\r')
}
function compare(actual, expected) {
var pass = actual === expected
return {
pass: pass,
message: util.buildFailureMessage(
'toHasLinesLike', pass, printable(actual), printable(expected))
}
}
return {compare: compare}
} | [
"function",
"(",
"util",
")",
"{",
"function",
"printable",
"(",
"str",
")",
"{",
"return",
"(",
"''",
"+",
"str",
")",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"'\\\\n'",
")",
".",
"\\\\",
"replace",
"}",
"(",
"/",
"\\r",
"/",
"g",
",",
"'\\\\r'",
")",
"\\\\",
"}"
] | simple string comparator, mainly for easy visualization of eols | [
"simple",
"string",
"comparator",
"mainly",
"for",
"easy",
"visualization",
"of",
"eols"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/helpers/SpecHelper.js#L6-L21 | train |
|
aMarCruz/jspreproc | spec/helpers/SpecHelper.js | function (/*util*/) {
function compare(actual, expected) {
return {
pass: actual instanceof Error && ('' + actual).indexOf(expected) >= 0
}
}
return {compare: compare}
} | javascript | function (/*util*/) {
function compare(actual, expected) {
return {
pass: actual instanceof Error && ('' + actual).indexOf(expected) >= 0
}
}
return {compare: compare}
} | [
"function",
"(",
")",
"{",
"function",
"compare",
"(",
"actual",
",",
"expected",
")",
"{",
"return",
"{",
"pass",
":",
"actual",
"instanceof",
"Error",
"&&",
"(",
"''",
"+",
"actual",
")",
".",
"indexOf",
"(",
"expected",
")",
">=",
"0",
"}",
"}",
"return",
"{",
"compare",
":",
"compare",
"}",
"}"
] | actual has to be an Error instance, and contain the expected string | [
"actual",
"has",
"to",
"be",
"an",
"Error",
"instance",
"and",
"contain",
"the",
"expected",
"string"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/helpers/SpecHelper.js#L24-L33 | train |
|
ILLGrenoble/guacamole-common-js | src/Mouse.js | mousewheel_handler | function mousewheel_handler(e) {
// Determine approximate scroll amount (in pixels)
var delta = e.deltaY || -e.wheelDeltaY || -e.wheelDelta;
// If successfully retrieved scroll amount, convert to pixels if not
// already in pixels
if (delta) {
// Convert to pixels if delta was lines
if (e.deltaMode === 1)
delta = e.deltaY * guac_mouse.PIXELS_PER_LINE;
// Convert to pixels if delta was pages
else if (e.deltaMode === 2)
delta = e.deltaY * guac_mouse.PIXELS_PER_PAGE;
}
// Otherwise, assume legacy mousewheel event and line scrolling
else
delta = e.detail * guac_mouse.PIXELS_PER_LINE;
// Update overall delta
scroll_delta += delta;
// Up
if (scroll_delta <= -guac_mouse.scrollThreshold) {
// Repeatedly click the up button until insufficient delta remains
do {
if (guac_mouse.onmousedown) {
guac_mouse.currentState.up = true;
guac_mouse.onmousedown(guac_mouse.currentState);
}
if (guac_mouse.onmouseup) {
guac_mouse.currentState.up = false;
guac_mouse.onmouseup(guac_mouse.currentState);
}
scroll_delta += guac_mouse.scrollThreshold;
} while (scroll_delta <= -guac_mouse.scrollThreshold);
// Reset delta
scroll_delta = 0;
}
// Down
if (scroll_delta >= guac_mouse.scrollThreshold) {
// Repeatedly click the down button until insufficient delta remains
do {
if (guac_mouse.onmousedown) {
guac_mouse.currentState.down = true;
guac_mouse.onmousedown(guac_mouse.currentState);
}
if (guac_mouse.onmouseup) {
guac_mouse.currentState.down = false;
guac_mouse.onmouseup(guac_mouse.currentState);
}
scroll_delta -= guac_mouse.scrollThreshold;
} while (scroll_delta >= guac_mouse.scrollThreshold);
// Reset delta
scroll_delta = 0;
}
cancelEvent(e);
} | javascript | function mousewheel_handler(e) {
// Determine approximate scroll amount (in pixels)
var delta = e.deltaY || -e.wheelDeltaY || -e.wheelDelta;
// If successfully retrieved scroll amount, convert to pixels if not
// already in pixels
if (delta) {
// Convert to pixels if delta was lines
if (e.deltaMode === 1)
delta = e.deltaY * guac_mouse.PIXELS_PER_LINE;
// Convert to pixels if delta was pages
else if (e.deltaMode === 2)
delta = e.deltaY * guac_mouse.PIXELS_PER_PAGE;
}
// Otherwise, assume legacy mousewheel event and line scrolling
else
delta = e.detail * guac_mouse.PIXELS_PER_LINE;
// Update overall delta
scroll_delta += delta;
// Up
if (scroll_delta <= -guac_mouse.scrollThreshold) {
// Repeatedly click the up button until insufficient delta remains
do {
if (guac_mouse.onmousedown) {
guac_mouse.currentState.up = true;
guac_mouse.onmousedown(guac_mouse.currentState);
}
if (guac_mouse.onmouseup) {
guac_mouse.currentState.up = false;
guac_mouse.onmouseup(guac_mouse.currentState);
}
scroll_delta += guac_mouse.scrollThreshold;
} while (scroll_delta <= -guac_mouse.scrollThreshold);
// Reset delta
scroll_delta = 0;
}
// Down
if (scroll_delta >= guac_mouse.scrollThreshold) {
// Repeatedly click the down button until insufficient delta remains
do {
if (guac_mouse.onmousedown) {
guac_mouse.currentState.down = true;
guac_mouse.onmousedown(guac_mouse.currentState);
}
if (guac_mouse.onmouseup) {
guac_mouse.currentState.down = false;
guac_mouse.onmouseup(guac_mouse.currentState);
}
scroll_delta -= guac_mouse.scrollThreshold;
} while (scroll_delta >= guac_mouse.scrollThreshold);
// Reset delta
scroll_delta = 0;
}
cancelEvent(e);
} | [
"function",
"mousewheel_handler",
"(",
"e",
")",
"{",
"var",
"delta",
"=",
"e",
".",
"deltaY",
"||",
"-",
"e",
".",
"wheelDeltaY",
"||",
"-",
"e",
".",
"wheelDelta",
";",
"if",
"(",
"delta",
")",
"{",
"if",
"(",
"e",
".",
"deltaMode",
"===",
"1",
")",
"delta",
"=",
"e",
".",
"deltaY",
"*",
"guac_mouse",
".",
"PIXELS_PER_LINE",
";",
"else",
"if",
"(",
"e",
".",
"deltaMode",
"===",
"2",
")",
"delta",
"=",
"e",
".",
"deltaY",
"*",
"guac_mouse",
".",
"PIXELS_PER_PAGE",
";",
"}",
"else",
"delta",
"=",
"e",
".",
"detail",
"*",
"guac_mouse",
".",
"PIXELS_PER_LINE",
";",
"scroll_delta",
"+=",
"delta",
";",
"if",
"(",
"scroll_delta",
"<=",
"-",
"guac_mouse",
".",
"scrollThreshold",
")",
"{",
"do",
"{",
"if",
"(",
"guac_mouse",
".",
"onmousedown",
")",
"{",
"guac_mouse",
".",
"currentState",
".",
"up",
"=",
"true",
";",
"guac_mouse",
".",
"onmousedown",
"(",
"guac_mouse",
".",
"currentState",
")",
";",
"}",
"if",
"(",
"guac_mouse",
".",
"onmouseup",
")",
"{",
"guac_mouse",
".",
"currentState",
".",
"up",
"=",
"false",
";",
"guac_mouse",
".",
"onmouseup",
"(",
"guac_mouse",
".",
"currentState",
")",
";",
"}",
"scroll_delta",
"+=",
"guac_mouse",
".",
"scrollThreshold",
";",
"}",
"while",
"(",
"scroll_delta",
"<=",
"-",
"guac_mouse",
".",
"scrollThreshold",
")",
";",
"scroll_delta",
"=",
"0",
";",
"}",
"if",
"(",
"scroll_delta",
">=",
"guac_mouse",
".",
"scrollThreshold",
")",
"{",
"do",
"{",
"if",
"(",
"guac_mouse",
".",
"onmousedown",
")",
"{",
"guac_mouse",
".",
"currentState",
".",
"down",
"=",
"true",
";",
"guac_mouse",
".",
"onmousedown",
"(",
"guac_mouse",
".",
"currentState",
")",
";",
"}",
"if",
"(",
"guac_mouse",
".",
"onmouseup",
")",
"{",
"guac_mouse",
".",
"currentState",
".",
"down",
"=",
"false",
";",
"guac_mouse",
".",
"onmouseup",
"(",
"guac_mouse",
".",
"currentState",
")",
";",
"}",
"scroll_delta",
"-=",
"guac_mouse",
".",
"scrollThreshold",
";",
"}",
"while",
"(",
"scroll_delta",
">=",
"guac_mouse",
".",
"scrollThreshold",
")",
";",
"scroll_delta",
"=",
"0",
";",
"}",
"cancelEvent",
"(",
"e",
")",
";",
"}"
] | Scroll wheel support | [
"Scroll",
"wheel",
"support"
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Mouse.js#L249-L327 | train |
ILLGrenoble/guacamole-common-js | src/Mouse.js | press_button | function press_button(button) {
if (!guac_touchscreen.currentState[button]) {
guac_touchscreen.currentState[button] = true;
if (guac_touchscreen.onmousedown)
guac_touchscreen.onmousedown(guac_touchscreen.currentState);
}
} | javascript | function press_button(button) {
if (!guac_touchscreen.currentState[button]) {
guac_touchscreen.currentState[button] = true;
if (guac_touchscreen.onmousedown)
guac_touchscreen.onmousedown(guac_touchscreen.currentState);
}
} | [
"function",
"press_button",
"(",
"button",
")",
"{",
"if",
"(",
"!",
"guac_touchscreen",
".",
"currentState",
"[",
"button",
"]",
")",
"{",
"guac_touchscreen",
".",
"currentState",
"[",
"button",
"]",
"=",
"true",
";",
"if",
"(",
"guac_touchscreen",
".",
"onmousedown",
")",
"guac_touchscreen",
".",
"onmousedown",
"(",
"guac_touchscreen",
".",
"currentState",
")",
";",
"}",
"}"
] | Presses the given mouse button, if it isn't already pressed. Valid
button values are "left", "middle", "right", "up", and "down".
@private
@param {String} button The mouse button to press. | [
"Presses",
"the",
"given",
"mouse",
"button",
"if",
"it",
"isn",
"t",
"already",
"pressed",
".",
"Valid",
"button",
"values",
"are",
"left",
"middle",
"right",
"up",
"and",
"down",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Mouse.js#L898-L904 | train |
ILLGrenoble/guacamole-common-js | src/Mouse.js | release_button | function release_button(button) {
if (guac_touchscreen.currentState[button]) {
guac_touchscreen.currentState[button] = false;
if (guac_touchscreen.onmouseup)
guac_touchscreen.onmouseup(guac_touchscreen.currentState);
}
} | javascript | function release_button(button) {
if (guac_touchscreen.currentState[button]) {
guac_touchscreen.currentState[button] = false;
if (guac_touchscreen.onmouseup)
guac_touchscreen.onmouseup(guac_touchscreen.currentState);
}
} | [
"function",
"release_button",
"(",
"button",
")",
"{",
"if",
"(",
"guac_touchscreen",
".",
"currentState",
"[",
"button",
"]",
")",
"{",
"guac_touchscreen",
".",
"currentState",
"[",
"button",
"]",
"=",
"false",
";",
"if",
"(",
"guac_touchscreen",
".",
"onmouseup",
")",
"guac_touchscreen",
".",
"onmouseup",
"(",
"guac_touchscreen",
".",
"currentState",
")",
";",
"}",
"}"
] | Releases the given mouse button, if it isn't already released. Valid
button values are "left", "middle", "right", "up", and "down".
@private
@param {String} button The mouse button to release. | [
"Releases",
"the",
"given",
"mouse",
"button",
"if",
"it",
"isn",
"t",
"already",
"released",
".",
"Valid",
"button",
"values",
"are",
"left",
"middle",
"right",
"up",
"and",
"down",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Mouse.js#L913-L919 | train |
ILLGrenoble/guacamole-common-js | src/Mouse.js | move_mouse | function move_mouse(x, y) {
guac_touchscreen.currentState.fromClientPosition(element, x, y);
if (guac_touchscreen.onmousemove)
guac_touchscreen.onmousemove(guac_touchscreen.currentState);
} | javascript | function move_mouse(x, y) {
guac_touchscreen.currentState.fromClientPosition(element, x, y);
if (guac_touchscreen.onmousemove)
guac_touchscreen.onmousemove(guac_touchscreen.currentState);
} | [
"function",
"move_mouse",
"(",
"x",
",",
"y",
")",
"{",
"guac_touchscreen",
".",
"currentState",
".",
"fromClientPosition",
"(",
"element",
",",
"x",
",",
"y",
")",
";",
"if",
"(",
"guac_touchscreen",
".",
"onmousemove",
")",
"guac_touchscreen",
".",
"onmousemove",
"(",
"guac_touchscreen",
".",
"currentState",
")",
";",
"}"
] | Moves the mouse to the given coordinates. These coordinates must be
relative to the browser window, as they will be translated based on
the touch event target's location within the browser window.
@private
@param {Number} x The X coordinate of the mouse pointer.
@param {Number} y The Y coordinate of the mouse pointer. | [
"Moves",
"the",
"mouse",
"to",
"the",
"given",
"coordinates",
".",
"These",
"coordinates",
"must",
"be",
"relative",
"to",
"the",
"browser",
"window",
"as",
"they",
"will",
"be",
"translated",
"based",
"on",
"the",
"touch",
"event",
"target",
"s",
"location",
"within",
"the",
"browser",
"window",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Mouse.js#L942-L946 | train |
ILLGrenoble/guacamole-common-js | src/Mouse.js | finger_moved | function finger_moved(e) {
var touch = e.touches[0] || e.changedTouches[0];
var delta_x = touch.clientX - gesture_start_x;
var delta_y = touch.clientY - gesture_start_y;
return Math.sqrt(delta_x*delta_x + delta_y*delta_y) >= guac_touchscreen.clickMoveThreshold;
} | javascript | function finger_moved(e) {
var touch = e.touches[0] || e.changedTouches[0];
var delta_x = touch.clientX - gesture_start_x;
var delta_y = touch.clientY - gesture_start_y;
return Math.sqrt(delta_x*delta_x + delta_y*delta_y) >= guac_touchscreen.clickMoveThreshold;
} | [
"function",
"finger_moved",
"(",
"e",
")",
"{",
"var",
"touch",
"=",
"e",
".",
"touches",
"[",
"0",
"]",
"||",
"e",
".",
"changedTouches",
"[",
"0",
"]",
";",
"var",
"delta_x",
"=",
"touch",
".",
"clientX",
"-",
"gesture_start_x",
";",
"var",
"delta_y",
"=",
"touch",
".",
"clientY",
"-",
"gesture_start_y",
";",
"return",
"Math",
".",
"sqrt",
"(",
"delta_x",
"*",
"delta_x",
"+",
"delta_y",
"*",
"delta_y",
")",
">=",
"guac_touchscreen",
".",
"clickMoveThreshold",
";",
"}"
] | Returns whether the given touch event exceeds the movement threshold for
clicking, based on where the touch gesture began.
@private
@param {TouchEvent} e The touch event to check.
@return {Boolean} true if the movement threshold is exceeded, false
otherwise. | [
"Returns",
"whether",
"the",
"given",
"touch",
"event",
"exceeds",
"the",
"movement",
"threshold",
"for",
"clicking",
"based",
"on",
"where",
"the",
"touch",
"gesture",
"began",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Mouse.js#L957-L962 | train |
ILLGrenoble/guacamole-common-js | src/Mouse.js | begin_gesture | function begin_gesture(e) {
var touch = e.touches[0];
gesture_in_progress = true;
gesture_start_x = touch.clientX;
gesture_start_y = touch.clientY;
} | javascript | function begin_gesture(e) {
var touch = e.touches[0];
gesture_in_progress = true;
gesture_start_x = touch.clientX;
gesture_start_y = touch.clientY;
} | [
"function",
"begin_gesture",
"(",
"e",
")",
"{",
"var",
"touch",
"=",
"e",
".",
"touches",
"[",
"0",
"]",
";",
"gesture_in_progress",
"=",
"true",
";",
"gesture_start_x",
"=",
"touch",
".",
"clientX",
";",
"gesture_start_y",
"=",
"touch",
".",
"clientY",
";",
"}"
] | Begins a new gesture at the location of the first touch in the given
touch event.
@private
@param {TouchEvent} e The touch event beginning this new gesture. | [
"Begins",
"a",
"new",
"gesture",
"at",
"the",
"location",
"of",
"the",
"first",
"touch",
"in",
"the",
"given",
"touch",
"event",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Mouse.js#L971-L976 | train |
tooleks/shevchenko-js | src/api.js | shevchenko | function shevchenko(anthroponym, inflectionCase) {
return anthroponymInflector.inflect(new Anthroponym(anthroponym), new InflectionCase(inflectionCase)).toObject();
} | javascript | function shevchenko(anthroponym, inflectionCase) {
return anthroponymInflector.inflect(new Anthroponym(anthroponym), new InflectionCase(inflectionCase)).toObject();
} | [
"function",
"shevchenko",
"(",
"anthroponym",
",",
"inflectionCase",
")",
"{",
"return",
"anthroponymInflector",
".",
"inflect",
"(",
"new",
"Anthroponym",
"(",
"anthroponym",
")",
",",
"new",
"InflectionCase",
"(",
"inflectionCase",
")",
")",
".",
"toObject",
"(",
")",
";",
"}"
] | Inflects the anthroponym.
@param {object} anthroponym
@param {string} anthroponym.firstName
@param {string} anthroponym.lastName
@param {string} anthroponym.middleName
@param {string} anthroponym.gender
@param {string} inflectionCase | [
"Inflects",
"the",
"anthroponym",
"."
] | 6c0b9543065585876dac5799bf90aa69ec48e0bc | https://github.com/tooleks/shevchenko-js/blob/6c0b9543065585876dac5799bf90aa69ec48e0bc/src/api.js#L16-L18 | train |
ILLGrenoble/guacamole-common-js | src/Object.js | dequeueBodyCallback | function dequeueBodyCallback(name) {
// If no callbacks defined, simply return null
var callbacks = bodyCallbacks[name];
if (!callbacks)
return null;
// Otherwise, pull off first callback, deleting the queue if empty
var callback = callbacks.shift();
if (callbacks.length === 0)
delete bodyCallbacks[name];
// Return found callback
return callback;
} | javascript | function dequeueBodyCallback(name) {
// If no callbacks defined, simply return null
var callbacks = bodyCallbacks[name];
if (!callbacks)
return null;
// Otherwise, pull off first callback, deleting the queue if empty
var callback = callbacks.shift();
if (callbacks.length === 0)
delete bodyCallbacks[name];
// Return found callback
return callback;
} | [
"function",
"dequeueBodyCallback",
"(",
"name",
")",
"{",
"var",
"callbacks",
"=",
"bodyCallbacks",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"callbacks",
")",
"return",
"null",
";",
"var",
"callback",
"=",
"callbacks",
".",
"shift",
"(",
")",
";",
"if",
"(",
"callbacks",
".",
"length",
"===",
"0",
")",
"delete",
"bodyCallbacks",
"[",
"name",
"]",
";",
"return",
"callback",
";",
"}"
] | Removes and returns the callback at the head of the callback queue for
the stream having the given name. If no such callbacks exist, null is
returned.
@private
@param {String} name
The name of the stream to retrieve a callback for.
@returns {Function}
The next callback associated with the stream having the given name,
or null if no such callback exists. | [
"Removes",
"and",
"returns",
"the",
"callback",
"at",
"the",
"head",
"of",
"the",
"callback",
"queue",
"for",
"the",
"stream",
"having",
"the",
"given",
"name",
".",
"If",
"no",
"such",
"callbacks",
"exist",
"null",
"is",
"returned",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Object.js#L65-L80 | train |
ILLGrenoble/guacamole-common-js | src/Object.js | enqueueBodyCallback | function enqueueBodyCallback(name, callback) {
// Get callback queue by name, creating first if necessary
var callbacks = bodyCallbacks[name];
if (!callbacks) {
callbacks = [];
bodyCallbacks[name] = callbacks;
}
// Add callback to end of queue
callbacks.push(callback);
} | javascript | function enqueueBodyCallback(name, callback) {
// Get callback queue by name, creating first if necessary
var callbacks = bodyCallbacks[name];
if (!callbacks) {
callbacks = [];
bodyCallbacks[name] = callbacks;
}
// Add callback to end of queue
callbacks.push(callback);
} | [
"function",
"enqueueBodyCallback",
"(",
"name",
",",
"callback",
")",
"{",
"var",
"callbacks",
"=",
"bodyCallbacks",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"callbacks",
")",
"{",
"callbacks",
"=",
"[",
"]",
";",
"bodyCallbacks",
"[",
"name",
"]",
"=",
"callbacks",
";",
"}",
"callbacks",
".",
"push",
"(",
"callback",
")",
";",
"}"
] | Adds the given callback to the tail of the callback queue for the stream
having the given name.
@private
@param {String} name
The name of the stream to associate with the given callback.
@param {Function} callback
The callback to add to the queue of the stream with the given name. | [
"Adds",
"the",
"given",
"callback",
"to",
"the",
"tail",
"of",
"the",
"callback",
"queue",
"for",
"the",
"stream",
"having",
"the",
"given",
"name",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Object.js#L93-L105 | train |
ILLGrenoble/guacamole-common-js | src/Client.js | getLayer | function getLayer(index) {
// Get layer, create if necessary
var layer = layers[index];
if (!layer) {
// Create layer based on index
if (index === 0)
layer = display.getDefaultLayer();
else if (index > 0)
layer = display.createLayer();
else
layer = display.createBuffer();
// Add new layer
layers[index] = layer;
}
return layer;
} | javascript | function getLayer(index) {
// Get layer, create if necessary
var layer = layers[index];
if (!layer) {
// Create layer based on index
if (index === 0)
layer = display.getDefaultLayer();
else if (index > 0)
layer = display.createLayer();
else
layer = display.createBuffer();
// Add new layer
layers[index] = layer;
}
return layer;
} | [
"function",
"getLayer",
"(",
"index",
")",
"{",
"var",
"layer",
"=",
"layers",
"[",
"index",
"]",
";",
"if",
"(",
"!",
"layer",
")",
"{",
"if",
"(",
"index",
"===",
"0",
")",
"layer",
"=",
"display",
".",
"getDefaultLayer",
"(",
")",
";",
"else",
"if",
"(",
"index",
">",
"0",
")",
"layer",
"=",
"display",
".",
"createLayer",
"(",
")",
";",
"else",
"layer",
"=",
"display",
".",
"createBuffer",
"(",
")",
";",
"layers",
"[",
"index",
"]",
"=",
"layer",
";",
"}",
"return",
"layer",
";",
"}"
] | Returns the layer with the given index, creating it if necessary.
Positive indices refer to visible layers, an index of zero refers to
the default layer, and negative indices refer to buffers.
@private
@param {Number} index
The index of the layer to retrieve.
@return {Guacamole.Display.VisibleLayer|Guacamole.Layer}
The layer having the given index. | [
"Returns",
"the",
"layer",
"with",
"the",
"given",
"index",
"creating",
"it",
"if",
"necessary",
".",
"Positive",
"indices",
"refer",
"to",
"visible",
"layers",
"an",
"index",
"of",
"zero",
"refers",
"to",
"the",
"default",
"layer",
"and",
"negative",
"indices",
"refer",
"to",
"buffers",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Client.js#L723-L744 | train |
ILLGrenoble/guacamole-common-js | src/SessionRecording.js | findFrame | function findFrame(minIndex, maxIndex, timestamp) {
// Do not search if the region contains only one element
if (minIndex === maxIndex)
return minIndex;
// Split search region into two halves
var midIndex = Math.floor((minIndex + maxIndex) / 2);
var midTimestamp = toRelativeTimestamp(frames[midIndex].timestamp);
// If timestamp is within lesser half, search again within that half
if (timestamp < midTimestamp && midIndex > minIndex)
return findFrame(minIndex, midIndex - 1, timestamp);
// If timestamp is within greater half, search again within that half
if (timestamp > midTimestamp && midIndex < maxIndex)
return findFrame(midIndex + 1, maxIndex, timestamp);
// Otherwise, we lucked out and found a frame with exactly the
// desired timestamp
return midIndex;
} | javascript | function findFrame(minIndex, maxIndex, timestamp) {
// Do not search if the region contains only one element
if (minIndex === maxIndex)
return minIndex;
// Split search region into two halves
var midIndex = Math.floor((minIndex + maxIndex) / 2);
var midTimestamp = toRelativeTimestamp(frames[midIndex].timestamp);
// If timestamp is within lesser half, search again within that half
if (timestamp < midTimestamp && midIndex > minIndex)
return findFrame(minIndex, midIndex - 1, timestamp);
// If timestamp is within greater half, search again within that half
if (timestamp > midTimestamp && midIndex < maxIndex)
return findFrame(midIndex + 1, maxIndex, timestamp);
// Otherwise, we lucked out and found a frame with exactly the
// desired timestamp
return midIndex;
} | [
"function",
"findFrame",
"(",
"minIndex",
",",
"maxIndex",
",",
"timestamp",
")",
"{",
"if",
"(",
"minIndex",
"===",
"maxIndex",
")",
"return",
"minIndex",
";",
"var",
"midIndex",
"=",
"Math",
".",
"floor",
"(",
"(",
"minIndex",
"+",
"maxIndex",
")",
"/",
"2",
")",
";",
"var",
"midTimestamp",
"=",
"toRelativeTimestamp",
"(",
"frames",
"[",
"midIndex",
"]",
".",
"timestamp",
")",
";",
"if",
"(",
"timestamp",
"<",
"midTimestamp",
"&&",
"midIndex",
">",
"minIndex",
")",
"return",
"findFrame",
"(",
"minIndex",
",",
"midIndex",
"-",
"1",
",",
"timestamp",
")",
";",
"if",
"(",
"timestamp",
">",
"midTimestamp",
"&&",
"midIndex",
"<",
"maxIndex",
")",
"return",
"findFrame",
"(",
"midIndex",
"+",
"1",
",",
"maxIndex",
",",
"timestamp",
")",
";",
"return",
"midIndex",
";",
"}"
] | Searches through the given region of frames for the frame having a
relative timestamp closest to the timestamp given.
@private
@param {Number} minIndex
The index of the first frame in the region (the frame having the
smallest timestamp).
@param {Number} maxIndex
The index of the last frame in the region (the frame having the
largest timestamp).
@param {Number} timestamp
The relative timestamp to search for, where zero denotes the first
frame in the recording.
@returns {Number}
The index of the frame having a relative timestamp closest to the
given value. | [
"Searches",
"through",
"the",
"given",
"region",
"of",
"frames",
"for",
"the",
"frame",
"having",
"a",
"relative",
"timestamp",
"closest",
"to",
"the",
"timestamp",
"given",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/SessionRecording.js#L254-L276 | train |
ILLGrenoble/guacamole-common-js | src/SessionRecording.js | replayFrame | function replayFrame(index) {
var frame = frames[index];
// Replay all instructions within the retrieved frame
for (var i = 0; i < frame.instructions.length; i++) {
var instruction = frame.instructions[i];
playbackTunnel.receiveInstruction(instruction.opcode, instruction.args);
}
// Store client state if frame is flagged as a keyframe
if (frame.keyframe && !frame.clientState) {
playbackClient.exportState(function storeClientState(state) {
frame.clientState = state;
});
}
} | javascript | function replayFrame(index) {
var frame = frames[index];
// Replay all instructions within the retrieved frame
for (var i = 0; i < frame.instructions.length; i++) {
var instruction = frame.instructions[i];
playbackTunnel.receiveInstruction(instruction.opcode, instruction.args);
}
// Store client state if frame is flagged as a keyframe
if (frame.keyframe && !frame.clientState) {
playbackClient.exportState(function storeClientState(state) {
frame.clientState = state;
});
}
} | [
"function",
"replayFrame",
"(",
"index",
")",
"{",
"var",
"frame",
"=",
"frames",
"[",
"index",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"frame",
".",
"instructions",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"instruction",
"=",
"frame",
".",
"instructions",
"[",
"i",
"]",
";",
"playbackTunnel",
".",
"receiveInstruction",
"(",
"instruction",
".",
"opcode",
",",
"instruction",
".",
"args",
")",
";",
"}",
"if",
"(",
"frame",
".",
"keyframe",
"&&",
"!",
"frame",
".",
"clientState",
")",
"{",
"playbackClient",
".",
"exportState",
"(",
"function",
"storeClientState",
"(",
"state",
")",
"{",
"frame",
".",
"clientState",
"=",
"state",
";",
"}",
")",
";",
"}",
"}"
] | Replays the instructions associated with the given frame, sending those
instructions to the playback client.
@private
@param {Number} index
The index of the frame within the frames array which should be
replayed. | [
"Replays",
"the",
"instructions",
"associated",
"with",
"the",
"given",
"frame",
"sending",
"those",
"instructions",
"to",
"the",
"playback",
"client",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/SessionRecording.js#L287-L304 | train |
ILLGrenoble/guacamole-common-js | src/SessionRecording.js | seekToFrame | function seekToFrame(index, callback, delay) {
// Abort any in-progress seek
abortSeek();
// Replay frames asynchronously
seekTimeout = window.setTimeout(function continueSeek() {
var startIndex;
// Back up until startIndex represents current state
for (startIndex = index; startIndex >= 0; startIndex--) {
var frame = frames[startIndex];
// If we've reached the current frame, startIndex represents
// current state by definition
if (startIndex === currentFrame)
break;
// If frame has associated absolute state, make that frame the
// current state
if (frame.clientState) {
playbackClient.importState(frame.clientState);
break;
}
}
// Advance to frame index after current state
startIndex++;
var startTime = new Date().getTime();
// Replay any applicable incremental frames
for (; startIndex <= index; startIndex++) {
// Stop seeking if the operation is taking too long
var currentTime = new Date().getTime();
if (currentTime - startTime >= MAXIMUM_SEEK_TIME)
break;
replayFrame(startIndex);
}
// Current frame is now at requested index
currentFrame = startIndex - 1;
// Notify of changes in position
if (recording.onseek)
recording.onseek(recording.getPosition());
// If the seek operation has not yet completed, schedule continuation
if (currentFrame !== index)
seekToFrame(index, callback,
Math.max(delay - (new Date().getTime() - startTime), 0));
// Notify that the requested seek has completed
else
callback();
}, delay || 0);
} | javascript | function seekToFrame(index, callback, delay) {
// Abort any in-progress seek
abortSeek();
// Replay frames asynchronously
seekTimeout = window.setTimeout(function continueSeek() {
var startIndex;
// Back up until startIndex represents current state
for (startIndex = index; startIndex >= 0; startIndex--) {
var frame = frames[startIndex];
// If we've reached the current frame, startIndex represents
// current state by definition
if (startIndex === currentFrame)
break;
// If frame has associated absolute state, make that frame the
// current state
if (frame.clientState) {
playbackClient.importState(frame.clientState);
break;
}
}
// Advance to frame index after current state
startIndex++;
var startTime = new Date().getTime();
// Replay any applicable incremental frames
for (; startIndex <= index; startIndex++) {
// Stop seeking if the operation is taking too long
var currentTime = new Date().getTime();
if (currentTime - startTime >= MAXIMUM_SEEK_TIME)
break;
replayFrame(startIndex);
}
// Current frame is now at requested index
currentFrame = startIndex - 1;
// Notify of changes in position
if (recording.onseek)
recording.onseek(recording.getPosition());
// If the seek operation has not yet completed, schedule continuation
if (currentFrame !== index)
seekToFrame(index, callback,
Math.max(delay - (new Date().getTime() - startTime), 0));
// Notify that the requested seek has completed
else
callback();
}, delay || 0);
} | [
"function",
"seekToFrame",
"(",
"index",
",",
"callback",
",",
"delay",
")",
"{",
"abortSeek",
"(",
")",
";",
"seekTimeout",
"=",
"window",
".",
"setTimeout",
"(",
"function",
"continueSeek",
"(",
")",
"{",
"var",
"startIndex",
";",
"for",
"(",
"startIndex",
"=",
"index",
";",
"startIndex",
">=",
"0",
";",
"startIndex",
"--",
")",
"{",
"var",
"frame",
"=",
"frames",
"[",
"startIndex",
"]",
";",
"if",
"(",
"startIndex",
"===",
"currentFrame",
")",
"break",
";",
"if",
"(",
"frame",
".",
"clientState",
")",
"{",
"playbackClient",
".",
"importState",
"(",
"frame",
".",
"clientState",
")",
";",
"break",
";",
"}",
"}",
"startIndex",
"++",
";",
"var",
"startTime",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"for",
"(",
";",
"startIndex",
"<=",
"index",
";",
"startIndex",
"++",
")",
"{",
"var",
"currentTime",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"currentTime",
"-",
"startTime",
">=",
"MAXIMUM_SEEK_TIME",
")",
"break",
";",
"replayFrame",
"(",
"startIndex",
")",
";",
"}",
"currentFrame",
"=",
"startIndex",
"-",
"1",
";",
"if",
"(",
"recording",
".",
"onseek",
")",
"recording",
".",
"onseek",
"(",
"recording",
".",
"getPosition",
"(",
")",
")",
";",
"if",
"(",
"currentFrame",
"!==",
"index",
")",
"seekToFrame",
"(",
"index",
",",
"callback",
",",
"Math",
".",
"max",
"(",
"delay",
"-",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"startTime",
")",
",",
"0",
")",
")",
";",
"else",
"callback",
"(",
")",
";",
"}",
",",
"delay",
"||",
"0",
")",
";",
"}"
] | Moves the playback position to the given frame, resetting the state of
the playback client and replaying frames as necessary. The seek
operation will proceed asynchronously. If a seek operation is already in
progress, that seek is first aborted. The progress of the seek operation
can be observed through the onseek handler and the provided callback.
@private
@param {Number} index
The index of the frame which should become the new playback
position.
@param {function} callback
The callback to invoke once the seek operation has completed.
@param {Number} [delay=0]
The number of milliseconds that the seek operation should be
scheduled to take. | [
"Moves",
"the",
"playback",
"position",
"to",
"the",
"given",
"frame",
"resetting",
"the",
"state",
"of",
"the",
"playback",
"client",
"and",
"replaying",
"frames",
"as",
"necessary",
".",
"The",
"seek",
"operation",
"will",
"proceed",
"asynchronously",
".",
"If",
"a",
"seek",
"operation",
"is",
"already",
"in",
"progress",
"that",
"seek",
"is",
"first",
"aborted",
".",
"The",
"progress",
"of",
"the",
"seek",
"operation",
"can",
"be",
"observed",
"through",
"the",
"onseek",
"handler",
"and",
"the",
"provided",
"callback",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/SessionRecording.js#L325-L388 | train |
ILLGrenoble/guacamole-common-js | src/SessionRecording.js | continuePlayback | function continuePlayback() {
// If frames remain after advancing, schedule next frame
if (currentFrame + 1 < frames.length) {
// Pull the upcoming frame
var next = frames[currentFrame + 1];
// Calculate the real timestamp corresponding to when the next
// frame begins
var nextRealTimestamp = next.timestamp - startVideoTimestamp + startRealTimestamp;
// Calculate the relative delay between the current time and
// the next frame start
var delay = Math.max(nextRealTimestamp - new Date().getTime(), 0);
// Advance to next frame after enough time has elapsed
seekToFrame(currentFrame + 1, function frameDelayElapsed() {
continuePlayback();
}, delay);
}
// Otherwise stop playback
else
recording.pause();
} | javascript | function continuePlayback() {
// If frames remain after advancing, schedule next frame
if (currentFrame + 1 < frames.length) {
// Pull the upcoming frame
var next = frames[currentFrame + 1];
// Calculate the real timestamp corresponding to when the next
// frame begins
var nextRealTimestamp = next.timestamp - startVideoTimestamp + startRealTimestamp;
// Calculate the relative delay between the current time and
// the next frame start
var delay = Math.max(nextRealTimestamp - new Date().getTime(), 0);
// Advance to next frame after enough time has elapsed
seekToFrame(currentFrame + 1, function frameDelayElapsed() {
continuePlayback();
}, delay);
}
// Otherwise stop playback
else
recording.pause();
} | [
"function",
"continuePlayback",
"(",
")",
"{",
"if",
"(",
"currentFrame",
"+",
"1",
"<",
"frames",
".",
"length",
")",
"{",
"var",
"next",
"=",
"frames",
"[",
"currentFrame",
"+",
"1",
"]",
";",
"var",
"nextRealTimestamp",
"=",
"next",
".",
"timestamp",
"-",
"startVideoTimestamp",
"+",
"startRealTimestamp",
";",
"var",
"delay",
"=",
"Math",
".",
"max",
"(",
"nextRealTimestamp",
"-",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
",",
"0",
")",
";",
"seekToFrame",
"(",
"currentFrame",
"+",
"1",
",",
"function",
"frameDelayElapsed",
"(",
")",
"{",
"continuePlayback",
"(",
")",
";",
"}",
",",
"delay",
")",
";",
"}",
"else",
"recording",
".",
"pause",
"(",
")",
";",
"}"
] | Advances playback to the next frame in the frames array and schedules
playback of the frame following that frame based on their associated
timestamps. If no frames exist after the next frame, playback is paused.
@private | [
"Advances",
"playback",
"to",
"the",
"next",
"frame",
"in",
"the",
"frames",
"array",
"and",
"schedules",
"playback",
"of",
"the",
"frame",
"following",
"that",
"frame",
"based",
"on",
"their",
"associated",
"timestamps",
".",
"If",
"no",
"frames",
"exist",
"after",
"the",
"next",
"frame",
"playback",
"is",
"paused",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/SessionRecording.js#L407-L434 | train |
etpinard/sane-topojson | bin/shp2geo.js | getCmd | function getCmd(program, opt) {
var cmd,
expr;
if(program==='ogr2ogr') {
if(opt==='where') {
expr = [
'-where ',
"\"", specs.key, " IN ",
"('", specs.val, "')\" ",
'-clipsrc ',
specs.bounds.join(' ')
].join('');
}
else if(opt==='clipsrc') {
expr = [
'-clipsrc ',
specs.bounds.join(' ')
].join('');
}
else expr = '';
cmd = [
"ogr2ogr -f GeoJSON",
expr,
common.geojsonDir + common.tn(r, s.name, v.name, 'geo.json'),
common.wgetDir + common.srcPrefix + common.bn(r, v.src, 'shp')
].join(' ');
}
else if(program==='mapshaper') {
cmd = [
mapshaper,
common.wgetDir + common.srcPrefix + common.bn(r, v.src, 'shp'),
"encoding=utf8",
"-clip",
common.wgetDir + common.tn(r, s.name, specs.src, 'shp'),
"-filter remove-empty",
"-o",
common.geojsonDir + common.tn(r, s.name, v.name, 'geo.json')
].join(' ');
}
return cmd;
} | javascript | function getCmd(program, opt) {
var cmd,
expr;
if(program==='ogr2ogr') {
if(opt==='where') {
expr = [
'-where ',
"\"", specs.key, " IN ",
"('", specs.val, "')\" ",
'-clipsrc ',
specs.bounds.join(' ')
].join('');
}
else if(opt==='clipsrc') {
expr = [
'-clipsrc ',
specs.bounds.join(' ')
].join('');
}
else expr = '';
cmd = [
"ogr2ogr -f GeoJSON",
expr,
common.geojsonDir + common.tn(r, s.name, v.name, 'geo.json'),
common.wgetDir + common.srcPrefix + common.bn(r, v.src, 'shp')
].join(' ');
}
else if(program==='mapshaper') {
cmd = [
mapshaper,
common.wgetDir + common.srcPrefix + common.bn(r, v.src, 'shp'),
"encoding=utf8",
"-clip",
common.wgetDir + common.tn(r, s.name, specs.src, 'shp'),
"-filter remove-empty",
"-o",
common.geojsonDir + common.tn(r, s.name, v.name, 'geo.json')
].join(' ');
}
return cmd;
} | [
"function",
"getCmd",
"(",
"program",
",",
"opt",
")",
"{",
"var",
"cmd",
",",
"expr",
";",
"if",
"(",
"program",
"===",
"'ogr2ogr'",
")",
"{",
"if",
"(",
"opt",
"===",
"'where'",
")",
"{",
"expr",
"=",
"[",
"'-where '",
",",
"\"\\\"\"",
",",
"\\\"",
",",
"specs",
".",
"key",
",",
"\" IN \"",
",",
"\"('\"",
",",
"specs",
".",
"val",
",",
"\"')\\\" \"",
",",
"\\\"",
"]",
".",
"'-clipsrc '",
"specs",
".",
"bounds",
".",
"join",
"(",
"' '",
")",
";",
"}",
"else",
"join",
"(",
"''",
")",
"}",
"else",
"if",
"(",
"opt",
"===",
"'clipsrc'",
")",
"{",
"expr",
"=",
"[",
"'-clipsrc '",
",",
"specs",
".",
"bounds",
".",
"join",
"(",
"' '",
")",
"]",
".",
"join",
"(",
"''",
")",
";",
"}",
"else",
"expr",
"=",
"''",
";",
"cmd",
"=",
"[",
"\"ogr2ogr -f GeoJSON\"",
",",
"expr",
",",
"common",
".",
"geojsonDir",
"+",
"common",
".",
"tn",
"(",
"r",
",",
"s",
".",
"name",
",",
"v",
".",
"name",
",",
"'geo.json'",
")",
",",
"common",
".",
"wgetDir",
"+",
"common",
".",
"srcPrefix",
"+",
"common",
".",
"bn",
"(",
"r",
",",
"v",
".",
"src",
",",
"'shp'",
")",
"]",
".",
"join",
"(",
"' '",
")",
";",
"}"
] | use ogr2ogr for clip around bound use mapshaper for clip around shapefile polygons | [
"use",
"ogr2ogr",
"for",
"clip",
"around",
"bound",
"use",
"mapshaper",
"for",
"clip",
"around",
"shapefile",
"polygons"
] | 3efc5797df570fc7143a121d0ca9903defb8a8d5 | https://github.com/etpinard/sane-topojson/blob/3efc5797df570fc7143a121d0ca9903defb8a8d5/bin/shp2geo.js#L69-L114 | train |
kibertoad/objection-swagger | lib/converters/query-params-to-json-schema.converter.js | swaggerQueryParamsToSchema | function swaggerQueryParamsToSchema(queryModel) {
const requiredFields = [];
const transformedProperties = {};
_.forOwn(queryModel.items.properties, (value, key) => {
if (value.required) {
requiredFields.push(key);
}
transformedProperties[key] = {
...value
};
if (!_.isNil(transformedProperties[key].required)) {
delete transformedProperties[key].required;
}
});
return {
title: queryModel.title,
description: queryModel.description,
additionalProperties: false,
required: requiredFields,
properties: transformedProperties
};
} | javascript | function swaggerQueryParamsToSchema(queryModel) {
const requiredFields = [];
const transformedProperties = {};
_.forOwn(queryModel.items.properties, (value, key) => {
if (value.required) {
requiredFields.push(key);
}
transformedProperties[key] = {
...value
};
if (!_.isNil(transformedProperties[key].required)) {
delete transformedProperties[key].required;
}
});
return {
title: queryModel.title,
description: queryModel.description,
additionalProperties: false,
required: requiredFields,
properties: transformedProperties
};
} | [
"function",
"swaggerQueryParamsToSchema",
"(",
"queryModel",
")",
"{",
"const",
"requiredFields",
"=",
"[",
"]",
";",
"const",
"transformedProperties",
"=",
"{",
"}",
";",
"_",
".",
"forOwn",
"(",
"queryModel",
".",
"items",
".",
"properties",
",",
"(",
"value",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"value",
".",
"required",
")",
"{",
"requiredFields",
".",
"push",
"(",
"key",
")",
";",
"}",
"transformedProperties",
"[",
"key",
"]",
"=",
"{",
"...",
"value",
"}",
";",
"if",
"(",
"!",
"_",
".",
"isNil",
"(",
"transformedProperties",
"[",
"key",
"]",
".",
"required",
")",
")",
"{",
"delete",
"transformedProperties",
"[",
"key",
"]",
".",
"required",
";",
"}",
"}",
")",
";",
"return",
"{",
"title",
":",
"queryModel",
".",
"title",
",",
"description",
":",
"queryModel",
".",
"description",
",",
"additionalProperties",
":",
"false",
",",
"required",
":",
"requiredFields",
",",
"properties",
":",
"transformedProperties",
"}",
";",
"}"
] | Transforms Swagger query params into correct JSON Schema
@param {Object} queryModel - Swagger query params model
@returns {Object} JSON Schema object | [
"Transforms",
"Swagger",
"query",
"params",
"into",
"correct",
"JSON",
"Schema"
] | 2109b58ce323e78252729a46bcc94e617035b541 | https://github.com/kibertoad/objection-swagger/blob/2109b58ce323e78252729a46bcc94e617035b541/lib/converters/query-params-to-json-schema.converter.js#L9-L32 | train |
kibertoad/objection-swagger | lib/objection-swagger.js | generateSchemaRaw | function generateSchemaRaw(modelParam, opts = {}) {
validate.notNil(modelParam, "modelParam is mandatory");
let models;
if (_.isArray(modelParam)) {
models = modelParam;
} else if (_.isObject(modelParam)) {
models = [modelParam];
} else {
throw new Error("modelParam should be an object or an array of objects");
}
return models.map(model => {
const processedSchema = modelTransformer.transformJsonSchemaFromModel(
model,
opts
);
return {
name: model.name,
schema: processedSchema
};
});
} | javascript | function generateSchemaRaw(modelParam, opts = {}) {
validate.notNil(modelParam, "modelParam is mandatory");
let models;
if (_.isArray(modelParam)) {
models = modelParam;
} else if (_.isObject(modelParam)) {
models = [modelParam];
} else {
throw new Error("modelParam should be an object or an array of objects");
}
return models.map(model => {
const processedSchema = modelTransformer.transformJsonSchemaFromModel(
model,
opts
);
return {
name: model.name,
schema: processedSchema
};
});
} | [
"function",
"generateSchemaRaw",
"(",
"modelParam",
",",
"opts",
"=",
"{",
"}",
")",
"{",
"validate",
".",
"notNil",
"(",
"modelParam",
",",
"\"modelParam is mandatory\"",
")",
";",
"let",
"models",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"modelParam",
")",
")",
"{",
"models",
"=",
"modelParam",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"modelParam",
")",
")",
"{",
"models",
"=",
"[",
"modelParam",
"]",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"modelParam should be an object or an array of objects\"",
")",
";",
"}",
"return",
"models",
".",
"map",
"(",
"model",
"=>",
"{",
"const",
"processedSchema",
"=",
"modelTransformer",
".",
"transformJsonSchemaFromModel",
"(",
"model",
",",
"opts",
")",
";",
"return",
"{",
"name",
":",
"model",
".",
"name",
",",
"schema",
":",
"processedSchema",
"}",
";",
"}",
")",
";",
"}"
] | Generates JSON schemas from Objection.js models
@param {Model|Model[]} modelParam - model(s) to generate schemas for
@param {Options} opts
@returns {GeneratedSwagger[]} generated JSON schemas as objects | [
"Generates",
"JSON",
"schemas",
"from",
"Objection",
".",
"js",
"models"
] | 2109b58ce323e78252729a46bcc94e617035b541 | https://github.com/kibertoad/objection-swagger/blob/2109b58ce323e78252729a46bcc94e617035b541/lib/objection-swagger.js#L44-L67 | train |
kibertoad/objection-swagger | lib/objection-swagger.js | saveSchema | function saveSchema(modelParam, targetDir, opts = {}) {
validate.notNil(modelParam, "modelParam is mandatory");
validate.notNil(targetDir, "targetDir is mandatory");
const yamlSchemaContainers = generateSchema(modelParam, opts);
return yamlWriter.writeYamlsToFs(yamlSchemaContainers, targetDir, opts);
} | javascript | function saveSchema(modelParam, targetDir, opts = {}) {
validate.notNil(modelParam, "modelParam is mandatory");
validate.notNil(targetDir, "targetDir is mandatory");
const yamlSchemaContainers = generateSchema(modelParam, opts);
return yamlWriter.writeYamlsToFs(yamlSchemaContainers, targetDir, opts);
} | [
"function",
"saveSchema",
"(",
"modelParam",
",",
"targetDir",
",",
"opts",
"=",
"{",
"}",
")",
"{",
"validate",
".",
"notNil",
"(",
"modelParam",
",",
"\"modelParam is mandatory\"",
")",
";",
"validate",
".",
"notNil",
"(",
"targetDir",
",",
"\"targetDir is mandatory\"",
")",
";",
"const",
"yamlSchemaContainers",
"=",
"generateSchema",
"(",
"modelParam",
",",
"opts",
")",
";",
"return",
"yamlWriter",
".",
"writeYamlsToFs",
"(",
"yamlSchemaContainers",
",",
"targetDir",
",",
"opts",
")",
";",
"}"
] | Generates and saves into specified directory JSON schema files for inclusion in Swagger specifications from given
Objection.js models
@param {Model|Model[]} modelParam - model(s) to generate schemas for
@param {string} targetDir - directory to write generated schemas to. Do not add '/' to the end.
@param {Options} opts
@returns {Promise} - promise that is resolved after schemas are written | [
"Generates",
"and",
"saves",
"into",
"specified",
"directory",
"JSON",
"schema",
"files",
"for",
"inclusion",
"in",
"Swagger",
"specifications",
"from",
"given",
"Objection",
".",
"js",
"models"
] | 2109b58ce323e78252729a46bcc94e617035b541 | https://github.com/kibertoad/objection-swagger/blob/2109b58ce323e78252729a46bcc94e617035b541/lib/objection-swagger.js#L77-L83 | train |
kibertoad/objection-swagger | lib/objection-swagger.js | saveNonModelSchema | function saveNonModelSchema(schemaParam, targetDir, opts = {}) {
validate.notNil(schemaParam, "schemaParam is mandatory");
validate.notNil(targetDir, "targetDir is mandatory");
if (!Array.isArray(schemaParam)) {
schemaParam = [schemaParam];
}
const yamlSchemaContainers = schemaParam.map(schema => {
const processedSchema = jsonSchemaTransformer.transformSchema(schema, opts);
return {
name: schema.title,
schema: yaml.dump(processedSchema)
};
});
return yamlWriter.writeYamlsToFs(yamlSchemaContainers, targetDir, opts);
} | javascript | function saveNonModelSchema(schemaParam, targetDir, opts = {}) {
validate.notNil(schemaParam, "schemaParam is mandatory");
validate.notNil(targetDir, "targetDir is mandatory");
if (!Array.isArray(schemaParam)) {
schemaParam = [schemaParam];
}
const yamlSchemaContainers = schemaParam.map(schema => {
const processedSchema = jsonSchemaTransformer.transformSchema(schema, opts);
return {
name: schema.title,
schema: yaml.dump(processedSchema)
};
});
return yamlWriter.writeYamlsToFs(yamlSchemaContainers, targetDir, opts);
} | [
"function",
"saveNonModelSchema",
"(",
"schemaParam",
",",
"targetDir",
",",
"opts",
"=",
"{",
"}",
")",
"{",
"validate",
".",
"notNil",
"(",
"schemaParam",
",",
"\"schemaParam is mandatory\"",
")",
";",
"validate",
".",
"notNil",
"(",
"targetDir",
",",
"\"targetDir is mandatory\"",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"schemaParam",
")",
")",
"{",
"schemaParam",
"=",
"[",
"schemaParam",
"]",
";",
"}",
"const",
"yamlSchemaContainers",
"=",
"schemaParam",
".",
"map",
"(",
"schema",
"=>",
"{",
"const",
"processedSchema",
"=",
"jsonSchemaTransformer",
".",
"transformSchema",
"(",
"schema",
",",
"opts",
")",
";",
"return",
"{",
"name",
":",
"schema",
".",
"title",
",",
"schema",
":",
"yaml",
".",
"dump",
"(",
"processedSchema",
")",
"}",
";",
"}",
")",
";",
"return",
"yamlWriter",
".",
"writeYamlsToFs",
"(",
"yamlSchemaContainers",
",",
"targetDir",
",",
"opts",
")",
";",
"}"
] | Generates and saves into specified directory JSON-schema YAML files for inclusion in Swagger specifications from
given JSON-schemas
@param {Object|Object[]} schemaParam - JSON-Schema(s) to generate yamls for. Title param is used as a filename
@param {string} targetDir - directory to write generated schemas to. Do not add '/' to the end.
@param {Options} opts
@returns {Promise} - promise that is resolved after yamls are written | [
"Generates",
"and",
"saves",
"into",
"specified",
"directory",
"JSON",
"-",
"schema",
"YAML",
"files",
"for",
"inclusion",
"in",
"Swagger",
"specifications",
"from",
"given",
"JSON",
"-",
"schemas"
] | 2109b58ce323e78252729a46bcc94e617035b541 | https://github.com/kibertoad/objection-swagger/blob/2109b58ce323e78252729a46bcc94e617035b541/lib/objection-swagger.js#L93-L110 | train |
kibertoad/objection-swagger | lib/objection-swagger.js | saveQueryParamSchema | function saveQueryParamSchema(schemaParam, targetDir, opts = {}) {
validate.notNil(schemaParam, "schemaParam is mandatory");
validate.notNil(targetDir, "targetDir is mandatory");
if (!Array.isArray(schemaParam)) {
schemaParam = [schemaParam];
}
const yamlSchemaContainers = schemaParam.map(schema => {
const modelSchema = jsonSchemaTransformer.transformSchema(schema, opts);
const queryParamSchema = queryParamTransformer.transformIntoQueryParamSchema(
modelSchema
);
return {
name: schema.title,
schema: yaml.dump(queryParamSchema)
};
});
return yamlWriter.writeYamlsToFs(yamlSchemaContainers, targetDir, opts);
} | javascript | function saveQueryParamSchema(schemaParam, targetDir, opts = {}) {
validate.notNil(schemaParam, "schemaParam is mandatory");
validate.notNil(targetDir, "targetDir is mandatory");
if (!Array.isArray(schemaParam)) {
schemaParam = [schemaParam];
}
const yamlSchemaContainers = schemaParam.map(schema => {
const modelSchema = jsonSchemaTransformer.transformSchema(schema, opts);
const queryParamSchema = queryParamTransformer.transformIntoQueryParamSchema(
modelSchema
);
return {
name: schema.title,
schema: yaml.dump(queryParamSchema)
};
});
return yamlWriter.writeYamlsToFs(yamlSchemaContainers, targetDir, opts);
} | [
"function",
"saveQueryParamSchema",
"(",
"schemaParam",
",",
"targetDir",
",",
"opts",
"=",
"{",
"}",
")",
"{",
"validate",
".",
"notNil",
"(",
"schemaParam",
",",
"\"schemaParam is mandatory\"",
")",
";",
"validate",
".",
"notNil",
"(",
"targetDir",
",",
"\"targetDir is mandatory\"",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"schemaParam",
")",
")",
"{",
"schemaParam",
"=",
"[",
"schemaParam",
"]",
";",
"}",
"const",
"yamlSchemaContainers",
"=",
"schemaParam",
".",
"map",
"(",
"schema",
"=>",
"{",
"const",
"modelSchema",
"=",
"jsonSchemaTransformer",
".",
"transformSchema",
"(",
"schema",
",",
"opts",
")",
";",
"const",
"queryParamSchema",
"=",
"queryParamTransformer",
".",
"transformIntoQueryParamSchema",
"(",
"modelSchema",
")",
";",
"return",
"{",
"name",
":",
"schema",
".",
"title",
",",
"schema",
":",
"yaml",
".",
"dump",
"(",
"queryParamSchema",
")",
"}",
";",
"}",
")",
";",
"return",
"yamlWriter",
".",
"writeYamlsToFs",
"(",
"yamlSchemaContainers",
",",
"targetDir",
",",
"opts",
")",
";",
"}"
] | Generates and saves into specified directory JSON-schema YAML files for inclusion in Swagger query param
specifications from given JSON-schemas
@param {Object|Object[]} schemaParam - JSON-Schema(s) to generate yamls for. Title param is used as a filename
@param {string} targetDir - directory to write generated schemas to. Do not add '/' to the end.
@param {Options} opts
@returns {Promise} - promise that is resolved after yamls are written | [
"Generates",
"and",
"saves",
"into",
"specified",
"directory",
"JSON",
"-",
"schema",
"YAML",
"files",
"for",
"inclusion",
"in",
"Swagger",
"query",
"param",
"specifications",
"from",
"given",
"JSON",
"-",
"schemas"
] | 2109b58ce323e78252729a46bcc94e617035b541 | https://github.com/kibertoad/objection-swagger/blob/2109b58ce323e78252729a46bcc94e617035b541/lib/objection-swagger.js#L120-L140 | train |
ascartabelli/lamb | src/privates/_toInteger.js | _toInteger | function _toInteger (value) {
var n = +value;
if (n !== n) { // eslint-disable-line no-self-compare
return 0;
} else if (n % 1 === 0) {
return n;
} else {
return Math.floor(Math.abs(n)) * (n < 0 ? -1 : 1);
}
} | javascript | function _toInteger (value) {
var n = +value;
if (n !== n) { // eslint-disable-line no-self-compare
return 0;
} else if (n % 1 === 0) {
return n;
} else {
return Math.floor(Math.abs(n)) * (n < 0 ? -1 : 1);
}
} | [
"function",
"_toInteger",
"(",
"value",
")",
"{",
"var",
"n",
"=",
"+",
"value",
";",
"if",
"(",
"n",
"!==",
"n",
")",
"{",
"return",
"0",
";",
"}",
"else",
"if",
"(",
"n",
"%",
"1",
"===",
"0",
")",
"{",
"return",
"n",
";",
"}",
"else",
"{",
"return",
"Math",
".",
"floor",
"(",
"Math",
".",
"abs",
"(",
"n",
")",
")",
"*",
"(",
"n",
"<",
"0",
"?",
"-",
"1",
":",
"1",
")",
";",
"}",
"}"
] | Converts a value to an integer.
@private
@param {*} value
@returns {Number} | [
"Converts",
"a",
"value",
"to",
"an",
"integer",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_toInteger.js#L7-L17 | train |
sven-piller/eslint-formatter-markdown | markdown.js | renderStats | function renderStats(stats) {
/**
* Creates table Header if necessary
* @param {string} type error or warning
* @returns {string} The formatted string
*/
function injectHeader(type) {
return (stats[type]) ? '| rule | count | visual |\n| --- | --- | --- |\n' : '';
}
/**
* renders templates for each rule
* @param {string} type error or warning
* @returns {string} The formatted string, pluralized where necessary
*/
function output(type) {
var statstype = stats[type];
return injectHeader(type) + lodash.map(statstype, function (ruleStats, ruleId) {
return statsRowTemplate({
ruleId: ruleId,
ruleCount: ruleStats,
visual: lodash.repeat('X', lodash.min([ruleStats, 20]))
});
}, '').join('');
}
/**
* render template for severity
* @param {string} type severity
* @returns {string} template
*/
function renderTemplate(type) {
var lcType = lodash.lowerCase(type);
if (lodash.size(stats[lcType])) {
return statsTemplate({
title: '### ' + type,
items: output(lcType)
});
} else {
return '';
}
}
return renderTemplate('Errors') + renderTemplate('Warnings');
} | javascript | function renderStats(stats) {
/**
* Creates table Header if necessary
* @param {string} type error or warning
* @returns {string} The formatted string
*/
function injectHeader(type) {
return (stats[type]) ? '| rule | count | visual |\n| --- | --- | --- |\n' : '';
}
/**
* renders templates for each rule
* @param {string} type error or warning
* @returns {string} The formatted string, pluralized where necessary
*/
function output(type) {
var statstype = stats[type];
return injectHeader(type) + lodash.map(statstype, function (ruleStats, ruleId) {
return statsRowTemplate({
ruleId: ruleId,
ruleCount: ruleStats,
visual: lodash.repeat('X', lodash.min([ruleStats, 20]))
});
}, '').join('');
}
/**
* render template for severity
* @param {string} type severity
* @returns {string} template
*/
function renderTemplate(type) {
var lcType = lodash.lowerCase(type);
if (lodash.size(stats[lcType])) {
return statsTemplate({
title: '### ' + type,
items: output(lcType)
});
} else {
return '';
}
}
return renderTemplate('Errors') + renderTemplate('Warnings');
} | [
"function",
"renderStats",
"(",
"stats",
")",
"{",
"function",
"injectHeader",
"(",
"type",
")",
"{",
"return",
"(",
"stats",
"[",
"type",
"]",
")",
"?",
"'| rule | count | visual |\\n| --- | --- | --- |\\n'",
":",
"\\n",
";",
"}",
"\\n",
"''",
"function",
"output",
"(",
"type",
")",
"{",
"var",
"statstype",
"=",
"stats",
"[",
"type",
"]",
";",
"return",
"injectHeader",
"(",
"type",
")",
"+",
"lodash",
".",
"map",
"(",
"statstype",
",",
"function",
"(",
"ruleStats",
",",
"ruleId",
")",
"{",
"return",
"statsRowTemplate",
"(",
"{",
"ruleId",
":",
"ruleId",
",",
"ruleCount",
":",
"ruleStats",
",",
"visual",
":",
"lodash",
".",
"repeat",
"(",
"'X'",
",",
"lodash",
".",
"min",
"(",
"[",
"ruleStats",
",",
"20",
"]",
")",
")",
"}",
")",
";",
"}",
",",
"''",
")",
".",
"join",
"(",
"''",
")",
";",
"}",
"}"
] | Renders MARKDOWN for stats
@param {Object} stats the rules and their stats
@returns {string} The formatted string, pluralized where necessary | [
"Renders",
"MARKDOWN",
"for",
"stats"
] | 46fc4cb074b1f599f02df67d814a6a83b37de060 | https://github.com/sven-piller/eslint-formatter-markdown/blob/46fc4cb074b1f599f02df67d814a6a83b37de060/markdown.js#L64-L109 | train |
sven-piller/eslint-formatter-markdown | markdown.js | output | function output(type) {
var statstype = stats[type];
return injectHeader(type) + lodash.map(statstype, function (ruleStats, ruleId) {
return statsRowTemplate({
ruleId: ruleId,
ruleCount: ruleStats,
visual: lodash.repeat('X', lodash.min([ruleStats, 20]))
});
}, '').join('');
} | javascript | function output(type) {
var statstype = stats[type];
return injectHeader(type) + lodash.map(statstype, function (ruleStats, ruleId) {
return statsRowTemplate({
ruleId: ruleId,
ruleCount: ruleStats,
visual: lodash.repeat('X', lodash.min([ruleStats, 20]))
});
}, '').join('');
} | [
"function",
"output",
"(",
"type",
")",
"{",
"var",
"statstype",
"=",
"stats",
"[",
"type",
"]",
";",
"return",
"injectHeader",
"(",
"type",
")",
"+",
"lodash",
".",
"map",
"(",
"statstype",
",",
"function",
"(",
"ruleStats",
",",
"ruleId",
")",
"{",
"return",
"statsRowTemplate",
"(",
"{",
"ruleId",
":",
"ruleId",
",",
"ruleCount",
":",
"ruleStats",
",",
"visual",
":",
"lodash",
".",
"repeat",
"(",
"'X'",
",",
"lodash",
".",
"min",
"(",
"[",
"ruleStats",
",",
"20",
"]",
")",
")",
"}",
")",
";",
"}",
",",
"''",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
] | renders templates for each rule
@param {string} type error or warning
@returns {string} The formatted string, pluralized where necessary | [
"renders",
"templates",
"for",
"each",
"rule"
] | 46fc4cb074b1f599f02df67d814a6a83b37de060 | https://github.com/sven-piller/eslint-formatter-markdown/blob/46fc4cb074b1f599f02df67d814a6a83b37de060/markdown.js#L80-L89 | train |
sven-piller/eslint-formatter-markdown | markdown.js | renderTemplate | function renderTemplate(type) {
var lcType = lodash.lowerCase(type);
if (lodash.size(stats[lcType])) {
return statsTemplate({
title: '### ' + type,
items: output(lcType)
});
} else {
return '';
}
} | javascript | function renderTemplate(type) {
var lcType = lodash.lowerCase(type);
if (lodash.size(stats[lcType])) {
return statsTemplate({
title: '### ' + type,
items: output(lcType)
});
} else {
return '';
}
} | [
"function",
"renderTemplate",
"(",
"type",
")",
"{",
"var",
"lcType",
"=",
"lodash",
".",
"lowerCase",
"(",
"type",
")",
";",
"if",
"(",
"lodash",
".",
"size",
"(",
"stats",
"[",
"lcType",
"]",
")",
")",
"{",
"return",
"statsTemplate",
"(",
"{",
"title",
":",
"'### '",
"+",
"type",
",",
"items",
":",
"output",
"(",
"lcType",
")",
"}",
")",
";",
"}",
"else",
"{",
"return",
"''",
";",
"}",
"}"
] | render template for severity
@param {string} type severity
@returns {string} template | [
"render",
"template",
"for",
"severity"
] | 46fc4cb074b1f599f02df67d814a6a83b37de060 | https://github.com/sven-piller/eslint-formatter-markdown/blob/46fc4cb074b1f599f02df67d814a6a83b37de060/markdown.js#L96-L106 | train |
ILLGrenoble/guacamole-common-js | src/ArrayBufferWriter.js | __send_blob | function __send_blob(bytes) {
var binary = "";
// Produce binary string from bytes in buffer
for (var i=0; i<bytes.byteLength; i++)
binary += String.fromCharCode(bytes[i]);
// Send as base64
stream.sendBlob(window.btoa(binary));
} | javascript | function __send_blob(bytes) {
var binary = "";
// Produce binary string from bytes in buffer
for (var i=0; i<bytes.byteLength; i++)
binary += String.fromCharCode(bytes[i]);
// Send as base64
stream.sendBlob(window.btoa(binary));
} | [
"function",
"__send_blob",
"(",
"bytes",
")",
"{",
"var",
"binary",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"bytes",
".",
"byteLength",
";",
"i",
"++",
")",
"binary",
"+=",
"String",
".",
"fromCharCode",
"(",
"bytes",
"[",
"i",
"]",
")",
";",
"stream",
".",
"sendBlob",
"(",
"window",
".",
"btoa",
"(",
"binary",
")",
")",
";",
"}"
] | Encodes the given data as base64, sending it as a blob. The data must
be small enough to fit into a single blob instruction.
@private
@param {Uint8Array} bytes The data to send. | [
"Encodes",
"the",
"given",
"data",
"as",
"base64",
"sending",
"it",
"as",
"a",
"blob",
".",
"The",
"data",
"must",
"be",
"small",
"enough",
"to",
"fit",
"into",
"a",
"single",
"blob",
"instruction",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/ArrayBufferWriter.js#L51-L62 | train |
jorisvervuurt/JVSDisplayOTron | examples/dot3k/bar_graph.js | setBrightnessOfLed | function setBrightnessOfLed(callback) {
var ledIndex = 8;
var setBrightnessOfLedInterval = setInterval(function() {
if (ledIndex >= 0) {
dot3k.barGraph.setBrightnessOfLed(ledIndex, 0);
ledIndex--;
} else {
clearInterval(setBrightnessOfLedInterval);
if (callback) {
callback();
}
}
}, 500);
} | javascript | function setBrightnessOfLed(callback) {
var ledIndex = 8;
var setBrightnessOfLedInterval = setInterval(function() {
if (ledIndex >= 0) {
dot3k.barGraph.setBrightnessOfLed(ledIndex, 0);
ledIndex--;
} else {
clearInterval(setBrightnessOfLedInterval);
if (callback) {
callback();
}
}
}, 500);
} | [
"function",
"setBrightnessOfLed",
"(",
"callback",
")",
"{",
"var",
"ledIndex",
"=",
"8",
";",
"var",
"setBrightnessOfLedInterval",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"ledIndex",
">=",
"0",
")",
"{",
"dot3k",
".",
"barGraph",
".",
"setBrightnessOfLed",
"(",
"ledIndex",
",",
"0",
")",
";",
"ledIndex",
"--",
";",
"}",
"else",
"{",
"clearInterval",
"(",
"setBrightnessOfLedInterval",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
"}",
",",
"500",
")",
";",
"}"
] | Sets the brightness of each individual LED.
@param {Function} callback A function to call when the operation has finished. | [
"Sets",
"the",
"brightness",
"of",
"each",
"individual",
"LED",
"."
] | c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc | https://github.com/jorisvervuurt/JVSDisplayOTron/blob/c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc/examples/dot3k/bar_graph.js#L33-L49 | train |
ascartabelli/lamb | src/privates/_getPadding.js | _getPadding | function _getPadding (source, char, len) {
if (!isNil(source) && type(source) !== "String") {
source = String(source);
}
return _repeat(String(char)[0] || "", Math.ceil(len - source.length));
} | javascript | function _getPadding (source, char, len) {
if (!isNil(source) && type(source) !== "String") {
source = String(source);
}
return _repeat(String(char)[0] || "", Math.ceil(len - source.length));
} | [
"function",
"_getPadding",
"(",
"source",
",",
"char",
",",
"len",
")",
"{",
"if",
"(",
"!",
"isNil",
"(",
"source",
")",
"&&",
"type",
"(",
"source",
")",
"!==",
"\"String\"",
")",
"{",
"source",
"=",
"String",
"(",
"source",
")",
";",
"}",
"return",
"_repeat",
"(",
"String",
"(",
"char",
")",
"[",
"0",
"]",
"||",
"\"\"",
",",
"Math",
".",
"ceil",
"(",
"len",
"-",
"source",
".",
"length",
")",
")",
";",
"}"
] | Builds the prefix or suffix to be used when padding a string.
@private
@param {String} source
@param {String} char
@param {Number} len
@returns {String} | [
"Builds",
"the",
"prefix",
"or",
"suffix",
"to",
"be",
"used",
"when",
"padding",
"a",
"string",
"."
] | d36e45945c4789e4f1a2d8805936514b53f32362 | https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_getPadding.js#L13-L19 | train |
paritytech/js-shared | src/redux/providers/tokensActions.js | fetchTokensData | function fetchTokensData (tokenRegContract, tokenIndexes) {
return (dispatch, getState) => {
const { api, tokens } = getState();
const allTokens = Object.values(tokens);
const tokensIndexesMap = allTokens
.reduce((map, token) => {
map[token.index] = token;
return map;
}, {});
const fetchedTokenIndexes = allTokens
.filter((token) => token.fetched)
.map((token) => token.index);
const fullIndexes = [];
const partialIndexes = [];
tokenIndexes.forEach((tokenIndex) => {
if (fetchedTokenIndexes.includes(tokenIndex)) {
partialIndexes.push(tokenIndex);
} else {
fullIndexes.push(tokenIndex);
}
});
log.debug('need to fully fetch', fullIndexes);
log.debug('need to partially fetch', partialIndexes);
const fullPromise = fetchTokensInfo(api, tokenRegContract, fullIndexes);
const partialPromise = fetchTokensImages(api, tokenRegContract, partialIndexes)
.then((imagesResult) => {
return imagesResult.map((image, index) => {
const tokenIndex = partialIndexes[index];
const token = tokensIndexesMap[tokenIndex];
return { ...token, image };
});
});
return Promise.all([ fullPromise, partialPromise ])
.then(([ fullResults, partialResults ]) => {
log.debug('fetched', { fullResults, partialResults });
return []
.concat(fullResults, partialResults)
.filter(({ address }) => !/0x0*$/.test(address))
.reduce((tokens, token) => {
const { id } = token;
tokens[id] = token;
return tokens;
}, {});
})
.then((tokens) => {
dispatch(setTokens(tokens));
});
};
} | javascript | function fetchTokensData (tokenRegContract, tokenIndexes) {
return (dispatch, getState) => {
const { api, tokens } = getState();
const allTokens = Object.values(tokens);
const tokensIndexesMap = allTokens
.reduce((map, token) => {
map[token.index] = token;
return map;
}, {});
const fetchedTokenIndexes = allTokens
.filter((token) => token.fetched)
.map((token) => token.index);
const fullIndexes = [];
const partialIndexes = [];
tokenIndexes.forEach((tokenIndex) => {
if (fetchedTokenIndexes.includes(tokenIndex)) {
partialIndexes.push(tokenIndex);
} else {
fullIndexes.push(tokenIndex);
}
});
log.debug('need to fully fetch', fullIndexes);
log.debug('need to partially fetch', partialIndexes);
const fullPromise = fetchTokensInfo(api, tokenRegContract, fullIndexes);
const partialPromise = fetchTokensImages(api, tokenRegContract, partialIndexes)
.then((imagesResult) => {
return imagesResult.map((image, index) => {
const tokenIndex = partialIndexes[index];
const token = tokensIndexesMap[tokenIndex];
return { ...token, image };
});
});
return Promise.all([ fullPromise, partialPromise ])
.then(([ fullResults, partialResults ]) => {
log.debug('fetched', { fullResults, partialResults });
return []
.concat(fullResults, partialResults)
.filter(({ address }) => !/0x0*$/.test(address))
.reduce((tokens, token) => {
const { id } = token;
tokens[id] = token;
return tokens;
}, {});
})
.then((tokens) => {
dispatch(setTokens(tokens));
});
};
} | [
"function",
"fetchTokensData",
"(",
"tokenRegContract",
",",
"tokenIndexes",
")",
"{",
"return",
"(",
"dispatch",
",",
"getState",
")",
"=>",
"{",
"const",
"{",
"api",
",",
"tokens",
"}",
"=",
"getState",
"(",
")",
";",
"const",
"allTokens",
"=",
"Object",
".",
"values",
"(",
"tokens",
")",
";",
"const",
"tokensIndexesMap",
"=",
"allTokens",
".",
"reduce",
"(",
"(",
"map",
",",
"token",
")",
"=>",
"{",
"map",
"[",
"token",
".",
"index",
"]",
"=",
"token",
";",
"return",
"map",
";",
"}",
",",
"{",
"}",
")",
";",
"const",
"fetchedTokenIndexes",
"=",
"allTokens",
".",
"filter",
"(",
"(",
"token",
")",
"=>",
"token",
".",
"fetched",
")",
".",
"map",
"(",
"(",
"token",
")",
"=>",
"token",
".",
"index",
")",
";",
"const",
"fullIndexes",
"=",
"[",
"]",
";",
"const",
"partialIndexes",
"=",
"[",
"]",
";",
"tokenIndexes",
".",
"forEach",
"(",
"(",
"tokenIndex",
")",
"=>",
"{",
"if",
"(",
"fetchedTokenIndexes",
".",
"includes",
"(",
"tokenIndex",
")",
")",
"{",
"partialIndexes",
".",
"push",
"(",
"tokenIndex",
")",
";",
"}",
"else",
"{",
"fullIndexes",
".",
"push",
"(",
"tokenIndex",
")",
";",
"}",
"}",
")",
";",
"log",
".",
"debug",
"(",
"'need to fully fetch'",
",",
"fullIndexes",
")",
";",
"log",
".",
"debug",
"(",
"'need to partially fetch'",
",",
"partialIndexes",
")",
";",
"const",
"fullPromise",
"=",
"fetchTokensInfo",
"(",
"api",
",",
"tokenRegContract",
",",
"fullIndexes",
")",
";",
"const",
"partialPromise",
"=",
"fetchTokensImages",
"(",
"api",
",",
"tokenRegContract",
",",
"partialIndexes",
")",
".",
"then",
"(",
"(",
"imagesResult",
")",
"=>",
"{",
"return",
"imagesResult",
".",
"map",
"(",
"(",
"image",
",",
"index",
")",
"=>",
"{",
"const",
"tokenIndex",
"=",
"partialIndexes",
"[",
"index",
"]",
";",
"const",
"token",
"=",
"tokensIndexesMap",
"[",
"tokenIndex",
"]",
";",
"return",
"{",
"...",
"token",
",",
"image",
"}",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"[",
"fullPromise",
",",
"partialPromise",
"]",
")",
".",
"then",
"(",
"(",
"[",
"fullResults",
",",
"partialResults",
"]",
")",
"=>",
"{",
"log",
".",
"debug",
"(",
"'fetched'",
",",
"{",
"fullResults",
",",
"partialResults",
"}",
")",
";",
"return",
"[",
"]",
".",
"concat",
"(",
"fullResults",
",",
"partialResults",
")",
".",
"filter",
"(",
"(",
"{",
"address",
"}",
")",
"=>",
"!",
"/",
"0x0*$",
"/",
".",
"test",
"(",
"address",
")",
")",
".",
"reduce",
"(",
"(",
"tokens",
",",
"token",
")",
"=>",
"{",
"const",
"{",
"id",
"}",
"=",
"token",
";",
"tokens",
"[",
"id",
"]",
"=",
"token",
";",
"return",
"tokens",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
"tokens",
")",
"=>",
"{",
"dispatch",
"(",
"setTokens",
"(",
"tokens",
")",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Split the given token indexes between those for whom
we already have some info, and thus just need to fetch
the image, and those for whom we don't have anything and
need to fetch all the info. | [
"Split",
"the",
"given",
"token",
"indexes",
"between",
"those",
"for",
"whom",
"we",
"already",
"have",
"some",
"info",
"and",
"thus",
"just",
"need",
"to",
"fetch",
"the",
"image",
"and",
"those",
"for",
"whom",
"we",
"don",
"t",
"have",
"anything",
"and",
"need",
"to",
"fetch",
"all",
"the",
"info",
"."
] | bb9593e4eb369ae8629f5056860f669692396f94 | https://github.com/paritytech/js-shared/blob/bb9593e4eb369ae8629f5056860f669692396f94/src/redux/providers/tokensActions.js#L188-L246 | train |
ILLGrenoble/guacamole-common-js | src/Layer.js | resize | function resize(newWidth, newHeight) {
// Default size to zero
newWidth = newWidth || 0;
newHeight = newHeight || 0;
// Calculate new dimensions of internal canvas
var canvasWidth = Math.ceil(newWidth / CANVAS_SIZE_FACTOR) * CANVAS_SIZE_FACTOR;
var canvasHeight = Math.ceil(newHeight / CANVAS_SIZE_FACTOR) * CANVAS_SIZE_FACTOR;
// Resize only if canvas dimensions are actually changing
if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
// Copy old data only if relevant and non-empty
var oldData = null;
if (!empty && canvas.width !== 0 && canvas.height !== 0) {
// Create canvas and context for holding old data
oldData = document.createElement("canvas");
oldData.width = Math.min(layer.width, newWidth);
oldData.height = Math.min(layer.height, newHeight);
var oldDataContext = oldData.getContext("2d");
// Copy image data from current
oldDataContext.drawImage(canvas,
0, 0, oldData.width, oldData.height,
0, 0, oldData.width, oldData.height);
}
// Preserve composite operation
var oldCompositeOperation = context.globalCompositeOperation;
// Resize canvas
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// Redraw old data, if any
if (oldData)
context.drawImage(oldData,
0, 0, oldData.width, oldData.height,
0, 0, oldData.width, oldData.height);
// Restore composite operation
context.globalCompositeOperation = oldCompositeOperation;
// Acknowledge reset of stack (happens on resize of canvas)
stackSize = 0;
context.save();
}
// If the canvas size is not changing, manually force state reset
else
layer.reset();
// Assign new layer dimensions
layer.width = newWidth;
layer.height = newHeight;
} | javascript | function resize(newWidth, newHeight) {
// Default size to zero
newWidth = newWidth || 0;
newHeight = newHeight || 0;
// Calculate new dimensions of internal canvas
var canvasWidth = Math.ceil(newWidth / CANVAS_SIZE_FACTOR) * CANVAS_SIZE_FACTOR;
var canvasHeight = Math.ceil(newHeight / CANVAS_SIZE_FACTOR) * CANVAS_SIZE_FACTOR;
// Resize only if canvas dimensions are actually changing
if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
// Copy old data only if relevant and non-empty
var oldData = null;
if (!empty && canvas.width !== 0 && canvas.height !== 0) {
// Create canvas and context for holding old data
oldData = document.createElement("canvas");
oldData.width = Math.min(layer.width, newWidth);
oldData.height = Math.min(layer.height, newHeight);
var oldDataContext = oldData.getContext("2d");
// Copy image data from current
oldDataContext.drawImage(canvas,
0, 0, oldData.width, oldData.height,
0, 0, oldData.width, oldData.height);
}
// Preserve composite operation
var oldCompositeOperation = context.globalCompositeOperation;
// Resize canvas
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// Redraw old data, if any
if (oldData)
context.drawImage(oldData,
0, 0, oldData.width, oldData.height,
0, 0, oldData.width, oldData.height);
// Restore composite operation
context.globalCompositeOperation = oldCompositeOperation;
// Acknowledge reset of stack (happens on resize of canvas)
stackSize = 0;
context.save();
}
// If the canvas size is not changing, manually force state reset
else
layer.reset();
// Assign new layer dimensions
layer.width = newWidth;
layer.height = newHeight;
} | [
"function",
"resize",
"(",
"newWidth",
",",
"newHeight",
")",
"{",
"newWidth",
"=",
"newWidth",
"||",
"0",
";",
"newHeight",
"=",
"newHeight",
"||",
"0",
";",
"var",
"canvasWidth",
"=",
"Math",
".",
"ceil",
"(",
"newWidth",
"/",
"CANVAS_SIZE_FACTOR",
")",
"*",
"CANVAS_SIZE_FACTOR",
";",
"var",
"canvasHeight",
"=",
"Math",
".",
"ceil",
"(",
"newHeight",
"/",
"CANVAS_SIZE_FACTOR",
")",
"*",
"CANVAS_SIZE_FACTOR",
";",
"if",
"(",
"canvas",
".",
"width",
"!==",
"canvasWidth",
"||",
"canvas",
".",
"height",
"!==",
"canvasHeight",
")",
"{",
"var",
"oldData",
"=",
"null",
";",
"if",
"(",
"!",
"empty",
"&&",
"canvas",
".",
"width",
"!==",
"0",
"&&",
"canvas",
".",
"height",
"!==",
"0",
")",
"{",
"oldData",
"=",
"document",
".",
"createElement",
"(",
"\"canvas\"",
")",
";",
"oldData",
".",
"width",
"=",
"Math",
".",
"min",
"(",
"layer",
".",
"width",
",",
"newWidth",
")",
";",
"oldData",
".",
"height",
"=",
"Math",
".",
"min",
"(",
"layer",
".",
"height",
",",
"newHeight",
")",
";",
"var",
"oldDataContext",
"=",
"oldData",
".",
"getContext",
"(",
"\"2d\"",
")",
";",
"oldDataContext",
".",
"drawImage",
"(",
"canvas",
",",
"0",
",",
"0",
",",
"oldData",
".",
"width",
",",
"oldData",
".",
"height",
",",
"0",
",",
"0",
",",
"oldData",
".",
"width",
",",
"oldData",
".",
"height",
")",
";",
"}",
"var",
"oldCompositeOperation",
"=",
"context",
".",
"globalCompositeOperation",
";",
"canvas",
".",
"width",
"=",
"canvasWidth",
";",
"canvas",
".",
"height",
"=",
"canvasHeight",
";",
"if",
"(",
"oldData",
")",
"context",
".",
"drawImage",
"(",
"oldData",
",",
"0",
",",
"0",
",",
"oldData",
".",
"width",
",",
"oldData",
".",
"height",
",",
"0",
",",
"0",
",",
"oldData",
".",
"width",
",",
"oldData",
".",
"height",
")",
";",
"context",
".",
"globalCompositeOperation",
"=",
"oldCompositeOperation",
";",
"stackSize",
"=",
"0",
";",
"context",
".",
"save",
"(",
")",
";",
"}",
"else",
"layer",
".",
"reset",
"(",
")",
";",
"layer",
".",
"width",
"=",
"newWidth",
";",
"layer",
".",
"height",
"=",
"newHeight",
";",
"}"
] | Resizes the canvas element backing this Layer. This function should only
be used internally.
@private
@param {Number} [newWidth=0]
The new width to assign to this Layer.
@param {Number} [newHeight=0]
The new height to assign to this Layer. | [
"Resizes",
"the",
"canvas",
"element",
"backing",
"this",
"Layer",
".",
"This",
"function",
"should",
"only",
"be",
"used",
"internally",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Layer.js#L132-L193 | train |
ILLGrenoble/guacamole-common-js | src/Layer.js | fitRect | function fitRect(x, y, w, h) {
// Calculate bounds
var opBoundX = w + x;
var opBoundY = h + y;
// Determine max width
var resizeWidth;
if (opBoundX > layer.width)
resizeWidth = opBoundX;
else
resizeWidth = layer.width;
// Determine max height
var resizeHeight;
if (opBoundY > layer.height)
resizeHeight = opBoundY;
else
resizeHeight = layer.height;
// Resize if necessary
layer.resize(resizeWidth, resizeHeight);
} | javascript | function fitRect(x, y, w, h) {
// Calculate bounds
var opBoundX = w + x;
var opBoundY = h + y;
// Determine max width
var resizeWidth;
if (opBoundX > layer.width)
resizeWidth = opBoundX;
else
resizeWidth = layer.width;
// Determine max height
var resizeHeight;
if (opBoundY > layer.height)
resizeHeight = opBoundY;
else
resizeHeight = layer.height;
// Resize if necessary
layer.resize(resizeWidth, resizeHeight);
} | [
"function",
"fitRect",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"{",
"var",
"opBoundX",
"=",
"w",
"+",
"x",
";",
"var",
"opBoundY",
"=",
"h",
"+",
"y",
";",
"var",
"resizeWidth",
";",
"if",
"(",
"opBoundX",
">",
"layer",
".",
"width",
")",
"resizeWidth",
"=",
"opBoundX",
";",
"else",
"resizeWidth",
"=",
"layer",
".",
"width",
";",
"var",
"resizeHeight",
";",
"if",
"(",
"opBoundY",
">",
"layer",
".",
"height",
")",
"resizeHeight",
"=",
"opBoundY",
";",
"else",
"resizeHeight",
"=",
"layer",
".",
"height",
";",
"layer",
".",
"resize",
"(",
"resizeWidth",
",",
"resizeHeight",
")",
";",
"}"
] | Given the X and Y coordinates of the upper-left corner of a rectangle
and the rectangle's width and height, resize the backing canvas element
as necessary to ensure that the rectangle fits within the canvas
element's coordinate space. This function will only make the canvas
larger. If the rectangle already fits within the canvas element's
coordinate space, the canvas is left unchanged.
@private
@param {Number} x The X coordinate of the upper-left corner of the
rectangle to fit.
@param {Number} y The Y coordinate of the upper-left corner of the
rectangle to fit.
@param {Number} w The width of the the rectangle to fit.
@param {Number} h The height of the the rectangle to fit. | [
"Given",
"the",
"X",
"and",
"Y",
"coordinates",
"of",
"the",
"upper",
"-",
"left",
"corner",
"of",
"a",
"rectangle",
"and",
"the",
"rectangle",
"s",
"width",
"and",
"height",
"resize",
"the",
"backing",
"canvas",
"element",
"as",
"necessary",
"to",
"ensure",
"that",
"the",
"rectangle",
"fits",
"within",
"the",
"canvas",
"element",
"s",
"coordinate",
"space",
".",
"This",
"function",
"will",
"only",
"make",
"the",
"canvas",
"larger",
".",
"If",
"the",
"rectangle",
"already",
"fits",
"within",
"the",
"canvas",
"element",
"s",
"coordinate",
"space",
"the",
"canvas",
"is",
"left",
"unchanged",
"."
] | 71925794155ea3fc37d2a125adbca6f8be532887 | https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/Layer.js#L211-L234 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | _mkdom | function _mkdom(templ, html) {
var match = templ && templ.match(/^\s*<([-\w]+)/),
tagName = match && match[1].toLowerCase(),
rootTag = rootEls[tagName] || GENERIC,
el = mkEl(rootTag)
el.stub = true
// replace all the yield tags with the tag inner html
if (html) templ = replaceYield(templ, html)
/* istanbul ignore next */
if (checkIE && tagName && (match = tagName.match(SPECIAL_TAGS_REGEX)))
ie9elem(el, templ, tagName, !!match[1])
else
el.innerHTML = templ
return el
} | javascript | function _mkdom(templ, html) {
var match = templ && templ.match(/^\s*<([-\w]+)/),
tagName = match && match[1].toLowerCase(),
rootTag = rootEls[tagName] || GENERIC,
el = mkEl(rootTag)
el.stub = true
// replace all the yield tags with the tag inner html
if (html) templ = replaceYield(templ, html)
/* istanbul ignore next */
if (checkIE && tagName && (match = tagName.match(SPECIAL_TAGS_REGEX)))
ie9elem(el, templ, tagName, !!match[1])
else
el.innerHTML = templ
return el
} | [
"function",
"_mkdom",
"(",
"templ",
",",
"html",
")",
"{",
"var",
"match",
"=",
"templ",
"&&",
"templ",
".",
"match",
"(",
"/",
"^\\s*<([-\\w]+)",
"/",
")",
",",
"tagName",
"=",
"match",
"&&",
"match",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
",",
"rootTag",
"=",
"rootEls",
"[",
"tagName",
"]",
"||",
"GENERIC",
",",
"el",
"=",
"mkEl",
"(",
"rootTag",
")",
"el",
".",
"stub",
"=",
"true",
"if",
"(",
"html",
")",
"templ",
"=",
"replaceYield",
"(",
"templ",
",",
"html",
")",
"if",
"(",
"checkIE",
"&&",
"tagName",
"&&",
"(",
"match",
"=",
"tagName",
".",
"match",
"(",
"SPECIAL_TAGS_REGEX",
")",
")",
")",
"ie9elem",
"(",
"el",
",",
"templ",
",",
"tagName",
",",
"!",
"!",
"match",
"[",
"1",
"]",
")",
"else",
"el",
".",
"innerHTML",
"=",
"templ",
"return",
"el",
"}"
] | creates any dom element in a div, table, or colgroup container | [
"creates",
"any",
"dom",
"element",
"in",
"a",
"div",
"table",
"or",
"colgroup",
"container"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L913-L932 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | update | function update(expressions, tag) {
each(expressions, function(expr, i) {
var dom = expr.dom,
attrName = expr.attr,
value = tmpl(expr.expr, tag),
parent = expr.dom.parentNode
if (expr.bool)
value = value ? attrName : false
else if (value == null)
value = ''
// leave out riot- prefixes from strings inside textarea
// fix #815: any value -> string
if (parent && parent.tagName == 'TEXTAREA') {
value = ('' + value).replace(/riot-/g, '')
// change textarea's value
parent.value = value
}
// no change
if (expr.value === value) return
expr.value = value
// text node
if (!attrName) {
dom.nodeValue = '' + value // #815 related
return
}
// remove original attribute
remAttr(dom, attrName)
// event handler
if (isFunction(value)) {
setEventHandler(attrName, value, dom, tag)
// if- conditional
} else if (attrName == 'if') {
var stub = expr.stub,
add = function() { insertTo(stub.parentNode, stub, dom) },
remove = function() { insertTo(dom.parentNode, dom, stub) }
// add to DOM
if (value) {
if (stub) {
add()
dom.inStub = false
// avoid to trigger the mount event if the tags is not visible yet
// maybe we can optimize this avoiding to mount the tag at all
if (!isInStub(dom)) {
walk(dom, function(el) {
if (el._tag && !el._tag.isMounted)
el._tag.isMounted = !!el._tag.trigger('mount')
})
}
}
// remove from DOM
} else {
stub = expr.stub = stub || document.createTextNode('')
// if the parentNode is defined we can easily replace the tag
if (dom.parentNode)
remove()
// otherwise we need to wait the updated event
else (tag.parent || tag).one('updated', remove)
dom.inStub = true
}
// show / hide
} else if (/^(show|hide)$/.test(attrName)) {
if (attrName == 'hide') value = !value
dom.style.display = value ? '' : 'none'
// field value
} else if (attrName == 'value') {
dom.value = value
// <img src="{ expr }">
} else if (startsWith(attrName, RIOT_PREFIX) && attrName != RIOT_TAG) {
if (value)
setAttr(dom, attrName.slice(RIOT_PREFIX.length), value)
} else {
if (expr.bool) {
dom[attrName] = value
if (!value) return
}
if (value === 0 || value && typeof value !== T_OBJECT)
setAttr(dom, attrName, value)
}
})
} | javascript | function update(expressions, tag) {
each(expressions, function(expr, i) {
var dom = expr.dom,
attrName = expr.attr,
value = tmpl(expr.expr, tag),
parent = expr.dom.parentNode
if (expr.bool)
value = value ? attrName : false
else if (value == null)
value = ''
// leave out riot- prefixes from strings inside textarea
// fix #815: any value -> string
if (parent && parent.tagName == 'TEXTAREA') {
value = ('' + value).replace(/riot-/g, '')
// change textarea's value
parent.value = value
}
// no change
if (expr.value === value) return
expr.value = value
// text node
if (!attrName) {
dom.nodeValue = '' + value // #815 related
return
}
// remove original attribute
remAttr(dom, attrName)
// event handler
if (isFunction(value)) {
setEventHandler(attrName, value, dom, tag)
// if- conditional
} else if (attrName == 'if') {
var stub = expr.stub,
add = function() { insertTo(stub.parentNode, stub, dom) },
remove = function() { insertTo(dom.parentNode, dom, stub) }
// add to DOM
if (value) {
if (stub) {
add()
dom.inStub = false
// avoid to trigger the mount event if the tags is not visible yet
// maybe we can optimize this avoiding to mount the tag at all
if (!isInStub(dom)) {
walk(dom, function(el) {
if (el._tag && !el._tag.isMounted)
el._tag.isMounted = !!el._tag.trigger('mount')
})
}
}
// remove from DOM
} else {
stub = expr.stub = stub || document.createTextNode('')
// if the parentNode is defined we can easily replace the tag
if (dom.parentNode)
remove()
// otherwise we need to wait the updated event
else (tag.parent || tag).one('updated', remove)
dom.inStub = true
}
// show / hide
} else if (/^(show|hide)$/.test(attrName)) {
if (attrName == 'hide') value = !value
dom.style.display = value ? '' : 'none'
// field value
} else if (attrName == 'value') {
dom.value = value
// <img src="{ expr }">
} else if (startsWith(attrName, RIOT_PREFIX) && attrName != RIOT_TAG) {
if (value)
setAttr(dom, attrName.slice(RIOT_PREFIX.length), value)
} else {
if (expr.bool) {
dom[attrName] = value
if (!value) return
}
if (value === 0 || value && typeof value !== T_OBJECT)
setAttr(dom, attrName, value)
}
})
} | [
"function",
"update",
"(",
"expressions",
",",
"tag",
")",
"{",
"each",
"(",
"expressions",
",",
"function",
"(",
"expr",
",",
"i",
")",
"{",
"var",
"dom",
"=",
"expr",
".",
"dom",
",",
"attrName",
"=",
"expr",
".",
"attr",
",",
"value",
"=",
"tmpl",
"(",
"expr",
".",
"expr",
",",
"tag",
")",
",",
"parent",
"=",
"expr",
".",
"dom",
".",
"parentNode",
"if",
"(",
"expr",
".",
"bool",
")",
"value",
"=",
"value",
"?",
"attrName",
":",
"false",
"else",
"if",
"(",
"value",
"==",
"null",
")",
"value",
"=",
"''",
"if",
"(",
"parent",
"&&",
"parent",
".",
"tagName",
"==",
"'TEXTAREA'",
")",
"{",
"value",
"=",
"(",
"''",
"+",
"value",
")",
".",
"replace",
"(",
"/",
"riot-",
"/",
"g",
",",
"''",
")",
"parent",
".",
"value",
"=",
"value",
"}",
"if",
"(",
"expr",
".",
"value",
"===",
"value",
")",
"return",
"expr",
".",
"value",
"=",
"value",
"if",
"(",
"!",
"attrName",
")",
"{",
"dom",
".",
"nodeValue",
"=",
"''",
"+",
"value",
"return",
"}",
"remAttr",
"(",
"dom",
",",
"attrName",
")",
"if",
"(",
"isFunction",
"(",
"value",
")",
")",
"{",
"setEventHandler",
"(",
"attrName",
",",
"value",
",",
"dom",
",",
"tag",
")",
"}",
"else",
"if",
"(",
"attrName",
"==",
"'if'",
")",
"{",
"var",
"stub",
"=",
"expr",
".",
"stub",
",",
"add",
"=",
"function",
"(",
")",
"{",
"insertTo",
"(",
"stub",
".",
"parentNode",
",",
"stub",
",",
"dom",
")",
"}",
",",
"remove",
"=",
"function",
"(",
")",
"{",
"insertTo",
"(",
"dom",
".",
"parentNode",
",",
"dom",
",",
"stub",
")",
"}",
"if",
"(",
"value",
")",
"{",
"if",
"(",
"stub",
")",
"{",
"add",
"(",
")",
"dom",
".",
"inStub",
"=",
"false",
"if",
"(",
"!",
"isInStub",
"(",
"dom",
")",
")",
"{",
"walk",
"(",
"dom",
",",
"function",
"(",
"el",
")",
"{",
"if",
"(",
"el",
".",
"_tag",
"&&",
"!",
"el",
".",
"_tag",
".",
"isMounted",
")",
"el",
".",
"_tag",
".",
"isMounted",
"=",
"!",
"!",
"el",
".",
"_tag",
".",
"trigger",
"(",
"'mount'",
")",
"}",
")",
"}",
"}",
"}",
"else",
"{",
"stub",
"=",
"expr",
".",
"stub",
"=",
"stub",
"||",
"document",
".",
"createTextNode",
"(",
"''",
")",
"if",
"(",
"dom",
".",
"parentNode",
")",
"remove",
"(",
")",
"else",
"(",
"tag",
".",
"parent",
"||",
"tag",
")",
".",
"one",
"(",
"'updated'",
",",
"remove",
")",
"dom",
".",
"inStub",
"=",
"true",
"}",
"}",
"else",
"if",
"(",
"/",
"^(show|hide)$",
"/",
".",
"test",
"(",
"attrName",
")",
")",
"{",
"if",
"(",
"attrName",
"==",
"'hide'",
")",
"value",
"=",
"!",
"value",
"dom",
".",
"style",
".",
"display",
"=",
"value",
"?",
"''",
":",
"'none'",
"}",
"else",
"if",
"(",
"attrName",
"==",
"'value'",
")",
"{",
"dom",
".",
"value",
"=",
"value",
"}",
"else",
"if",
"(",
"startsWith",
"(",
"attrName",
",",
"RIOT_PREFIX",
")",
"&&",
"attrName",
"!=",
"RIOT_TAG",
")",
"{",
"if",
"(",
"value",
")",
"setAttr",
"(",
"dom",
",",
"attrName",
".",
"slice",
"(",
"RIOT_PREFIX",
".",
"length",
")",
",",
"value",
")",
"}",
"else",
"{",
"if",
"(",
"expr",
".",
"bool",
")",
"{",
"dom",
"[",
"attrName",
"]",
"=",
"value",
"if",
"(",
"!",
"value",
")",
"return",
"}",
"if",
"(",
"value",
"===",
"0",
"||",
"value",
"&&",
"typeof",
"value",
"!==",
"T_OBJECT",
")",
"setAttr",
"(",
"dom",
",",
"attrName",
",",
"value",
")",
"}",
"}",
")",
"}"
] | Update the expressions in a Tag instance
@param { Array } expressions - expression that must be re evaluated
@param { Tag } tag - tag instance | [
"Update",
"the",
"expressions",
"in",
"a",
"Tag",
"instance"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L1666-L1762 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | each | function each(els, fn) {
for (var i = 0, len = (els || []).length, el; i < len; i++) {
el = els[i]
// return false -> remove current item during loop
if (el != null && fn(el, i) === false) i--
}
return els
} | javascript | function each(els, fn) {
for (var i = 0, len = (els || []).length, el; i < len; i++) {
el = els[i]
// return false -> remove current item during loop
if (el != null && fn(el, i) === false) i--
}
return els
} | [
"function",
"each",
"(",
"els",
",",
"fn",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"(",
"els",
"||",
"[",
"]",
")",
".",
"length",
",",
"el",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"el",
"=",
"els",
"[",
"i",
"]",
"if",
"(",
"el",
"!=",
"null",
"&&",
"fn",
"(",
"el",
",",
"i",
")",
"===",
"false",
")",
"i",
"--",
"}",
"return",
"els",
"}"
] | Loops an array
@param { Array } els - collection of items
@param {Function} fn - callback function
@returns { Array } the array looped | [
"Loops",
"an",
"array"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L1769-L1776 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | addChildTag | function addChildTag(tag, tagName, parent) {
var cachedTag = parent.tags[tagName]
// if there are multiple children tags having the same name
if (cachedTag) {
// if the parent tags property is not yet an array
// create it adding the first cached tag
if (!isArray(cachedTag))
// don't add the same tag twice
if (cachedTag !== tag)
parent.tags[tagName] = [cachedTag]
// add the new nested tag to the array
if (!contains(parent.tags[tagName], tag))
parent.tags[tagName].push(tag)
} else {
parent.tags[tagName] = tag
}
} | javascript | function addChildTag(tag, tagName, parent) {
var cachedTag = parent.tags[tagName]
// if there are multiple children tags having the same name
if (cachedTag) {
// if the parent tags property is not yet an array
// create it adding the first cached tag
if (!isArray(cachedTag))
// don't add the same tag twice
if (cachedTag !== tag)
parent.tags[tagName] = [cachedTag]
// add the new nested tag to the array
if (!contains(parent.tags[tagName], tag))
parent.tags[tagName].push(tag)
} else {
parent.tags[tagName] = tag
}
} | [
"function",
"addChildTag",
"(",
"tag",
",",
"tagName",
",",
"parent",
")",
"{",
"var",
"cachedTag",
"=",
"parent",
".",
"tags",
"[",
"tagName",
"]",
"if",
"(",
"cachedTag",
")",
"{",
"if",
"(",
"!",
"isArray",
"(",
"cachedTag",
")",
")",
"if",
"(",
"cachedTag",
"!==",
"tag",
")",
"parent",
".",
"tags",
"[",
"tagName",
"]",
"=",
"[",
"cachedTag",
"]",
"if",
"(",
"!",
"contains",
"(",
"parent",
".",
"tags",
"[",
"tagName",
"]",
",",
"tag",
")",
")",
"parent",
".",
"tags",
"[",
"tagName",
"]",
".",
"push",
"(",
"tag",
")",
"}",
"else",
"{",
"parent",
".",
"tags",
"[",
"tagName",
"]",
"=",
"tag",
"}",
"}"
] | Add a child tag to its parent into the `tags` object
@param { Object } tag - child tag instance
@param { String } tagName - key where the new tag will be stored
@param { Object } parent - tag instance where the new child tag will be included | [
"Add",
"a",
"child",
"tag",
"to",
"its",
"parent",
"into",
"the",
"tags",
"object"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L1841-L1858 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | isWritable | function isWritable(obj, key) {
var props = Object.getOwnPropertyDescriptor(obj, key)
return typeof obj[key] === T_UNDEF || props && props.writable
} | javascript | function isWritable(obj, key) {
var props = Object.getOwnPropertyDescriptor(obj, key)
return typeof obj[key] === T_UNDEF || props && props.writable
} | [
"function",
"isWritable",
"(",
"obj",
",",
"key",
")",
"{",
"var",
"props",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"obj",
",",
"key",
")",
"return",
"typeof",
"obj",
"[",
"key",
"]",
"===",
"T_UNDEF",
"||",
"props",
"&&",
"props",
".",
"writable",
"}"
] | Detect whether a property of an object could be overridden
@param { Object } obj - source object
@param { String } key - object property
@returns { Boolean } is this property writable? | [
"Detect",
"whether",
"a",
"property",
"of",
"an",
"object",
"could",
"be",
"overridden"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L2004-L2007 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | isInStub | function isInStub(dom) {
while (dom) {
if (dom.inStub) return true
dom = dom.parentNode
}
return false
} | javascript | function isInStub(dom) {
while (dom) {
if (dom.inStub) return true
dom = dom.parentNode
}
return false
} | [
"function",
"isInStub",
"(",
"dom",
")",
"{",
"while",
"(",
"dom",
")",
"{",
"if",
"(",
"dom",
".",
"inStub",
")",
"return",
"true",
"dom",
"=",
"dom",
".",
"parentNode",
"}",
"return",
"false",
"}"
] | Check whether a DOM node is in stub mode, useful for the riot 'if' directive
@param { Object } dom - DOM node we want to parse
@returns { Boolean } - | [
"Check",
"whether",
"a",
"DOM",
"node",
"is",
"in",
"stub",
"mode",
"useful",
"for",
"the",
"riot",
"if",
"directive"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L2066-L2072 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | setNamed | function setNamed(dom, parent, keys) {
// get the key value we want to add to the tag instance
var key = getNamedKey(dom),
isArr,
// add the node detected to a tag instance using the named property
add = function(value) {
// avoid to override the tag properties already set
if (contains(keys, key)) return
// check whether this value is an array
isArr = isArray(value)
// if the key was never set
if (!value)
// set it once on the tag instance
parent[key] = dom
// if it was an array and not yet set
else if (!isArr || isArr && !contains(value, dom)) {
// add the dom node into the array
if (isArr)
value.push(dom)
else
parent[key] = [value, dom]
}
}
// skip the elements with no named properties
if (!key) return
// check whether this key has been already evaluated
if (tmpl.hasExpr(key))
// wait the first updated event only once
parent.one('mount', function() {
key = getNamedKey(dom)
add(parent[key])
})
else
add(parent[key])
} | javascript | function setNamed(dom, parent, keys) {
// get the key value we want to add to the tag instance
var key = getNamedKey(dom),
isArr,
// add the node detected to a tag instance using the named property
add = function(value) {
// avoid to override the tag properties already set
if (contains(keys, key)) return
// check whether this value is an array
isArr = isArray(value)
// if the key was never set
if (!value)
// set it once on the tag instance
parent[key] = dom
// if it was an array and not yet set
else if (!isArr || isArr && !contains(value, dom)) {
// add the dom node into the array
if (isArr)
value.push(dom)
else
parent[key] = [value, dom]
}
}
// skip the elements with no named properties
if (!key) return
// check whether this key has been already evaluated
if (tmpl.hasExpr(key))
// wait the first updated event only once
parent.one('mount', function() {
key = getNamedKey(dom)
add(parent[key])
})
else
add(parent[key])
} | [
"function",
"setNamed",
"(",
"dom",
",",
"parent",
",",
"keys",
")",
"{",
"var",
"key",
"=",
"getNamedKey",
"(",
"dom",
")",
",",
"isArr",
",",
"add",
"=",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"contains",
"(",
"keys",
",",
"key",
")",
")",
"return",
"isArr",
"=",
"isArray",
"(",
"value",
")",
"if",
"(",
"!",
"value",
")",
"parent",
"[",
"key",
"]",
"=",
"dom",
"else",
"if",
"(",
"!",
"isArr",
"||",
"isArr",
"&&",
"!",
"contains",
"(",
"value",
",",
"dom",
")",
")",
"{",
"if",
"(",
"isArr",
")",
"value",
".",
"push",
"(",
"dom",
")",
"else",
"parent",
"[",
"key",
"]",
"=",
"[",
"value",
",",
"dom",
"]",
"}",
"}",
"if",
"(",
"!",
"key",
")",
"return",
"if",
"(",
"tmpl",
".",
"hasExpr",
"(",
"key",
")",
")",
"parent",
".",
"one",
"(",
"'mount'",
",",
"function",
"(",
")",
"{",
"key",
"=",
"getNamedKey",
"(",
"dom",
")",
"add",
"(",
"parent",
"[",
"key",
"]",
")",
"}",
")",
"else",
"add",
"(",
"parent",
"[",
"key",
"]",
")",
"}"
] | Set the named properties of a tag element
@param { Object } dom - DOM node we need to parse
@param { Object } parent - tag instance where the named dom element will be eventually added
@param { Array } keys - list of all the tag instance properties | [
"Set",
"the",
"named",
"properties",
"of",
"a",
"tag",
"element"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L2129-L2166 | train |
aMarCruz/jspreproc | spec/uglify/riot.js | function(value) {
// avoid to override the tag properties already set
if (contains(keys, key)) return
// check whether this value is an array
isArr = isArray(value)
// if the key was never set
if (!value)
// set it once on the tag instance
parent[key] = dom
// if it was an array and not yet set
else if (!isArr || isArr && !contains(value, dom)) {
// add the dom node into the array
if (isArr)
value.push(dom)
else
parent[key] = [value, dom]
}
} | javascript | function(value) {
// avoid to override the tag properties already set
if (contains(keys, key)) return
// check whether this value is an array
isArr = isArray(value)
// if the key was never set
if (!value)
// set it once on the tag instance
parent[key] = dom
// if it was an array and not yet set
else if (!isArr || isArr && !contains(value, dom)) {
// add the dom node into the array
if (isArr)
value.push(dom)
else
parent[key] = [value, dom]
}
} | [
"function",
"(",
"value",
")",
"{",
"if",
"(",
"contains",
"(",
"keys",
",",
"key",
")",
")",
"return",
"isArr",
"=",
"isArray",
"(",
"value",
")",
"if",
"(",
"!",
"value",
")",
"parent",
"[",
"key",
"]",
"=",
"dom",
"else",
"if",
"(",
"!",
"isArr",
"||",
"isArr",
"&&",
"!",
"contains",
"(",
"value",
",",
"dom",
")",
")",
"{",
"if",
"(",
"isArr",
")",
"value",
".",
"push",
"(",
"dom",
")",
"else",
"parent",
"[",
"key",
"]",
"=",
"[",
"value",
",",
"dom",
"]",
"}",
"}"
] | get the key value we want to add to the tag instance | [
"get",
"the",
"key",
"value",
"we",
"want",
"to",
"add",
"to",
"the",
"tag",
"instance"
] | 5f31820d702a329e8aa25f0f3983f13097610250 | https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/spec/uglify/riot.js#L2134-L2151 | train |
|
fin-hypergrid/grouped-header-plugin | index.js | isColumnReorderable | function isColumnReorderable() {
var originalMethodFromPrototype = Object.getPrototypeOf(this).isColumnReorderable,
isReorderable = originalMethodFromPrototype.call(this),
groupedHeaderCellRenderer = this.grid.cellRenderers.get(CLASS_NAME),
delimiter = groupedHeaderCellRenderer.delimiter;
return (
isReorderable &&
!this.columns.find(function(column) { // but only if no grouped columns
return column.getCellProperty(0, 'renderer') === CLASS_NAME && // header cell using GroupedHeader
column.header.indexOf(delimiter) !== -1; // header is part of a group
})
);
} | javascript | function isColumnReorderable() {
var originalMethodFromPrototype = Object.getPrototypeOf(this).isColumnReorderable,
isReorderable = originalMethodFromPrototype.call(this),
groupedHeaderCellRenderer = this.grid.cellRenderers.get(CLASS_NAME),
delimiter = groupedHeaderCellRenderer.delimiter;
return (
isReorderable &&
!this.columns.find(function(column) { // but only if no grouped columns
return column.getCellProperty(0, 'renderer') === CLASS_NAME && // header cell using GroupedHeader
column.header.indexOf(delimiter) !== -1; // header is part of a group
})
);
} | [
"function",
"isColumnReorderable",
"(",
")",
"{",
"var",
"originalMethodFromPrototype",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"this",
")",
".",
"isColumnReorderable",
",",
"isReorderable",
"=",
"originalMethodFromPrototype",
".",
"call",
"(",
"this",
")",
",",
"groupedHeaderCellRenderer",
"=",
"this",
".",
"grid",
".",
"cellRenderers",
".",
"get",
"(",
"CLASS_NAME",
")",
",",
"delimiter",
"=",
"groupedHeaderCellRenderer",
".",
"delimiter",
";",
"return",
"(",
"isReorderable",
"&&",
"!",
"this",
".",
"columns",
".",
"find",
"(",
"function",
"(",
"column",
")",
"{",
"return",
"column",
".",
"getCellProperty",
"(",
"0",
",",
"'renderer'",
")",
"===",
"CLASS_NAME",
"&&",
"column",
".",
"header",
".",
"indexOf",
"(",
"delimiter",
")",
"!==",
"-",
"1",
";",
"}",
")",
")",
";",
"}"
] | Prevent column moving when there are any grouped headers.
@returns {boolean}
@memberOf groupedHeader
@inner | [
"Prevent",
"column",
"moving",
"when",
"there",
"are",
"any",
"grouped",
"headers",
"."
] | c73214e72242e2d0a2687f9dffa359a68e323be0 | https://github.com/fin-hypergrid/grouped-header-plugin/blob/c73214e72242e2d0a2687f9dffa359a68e323be0/index.js#L299-L312 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.