id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
41,100 | elsehow/signal-protocol | build/components_concat.js | function(builder, svc, name, request, response, request_stream, response_stream, options) {
Method.call(this, builder, svc, name, options);
/**
* @override
*/
this.className = "Service.RPCMethod";
/**
* Request message name.
* @type {string}
* @expose
*/
this.requestName = request;
/**
* Response message name.
* @type {string}
* @expose
*/
this.responseName = response;
/**
* Whether requests are streamed
* @type {bool}
* @expose
*/
this.requestStream = request_stream;
/**
* Whether responses are streamed
* @type {bool}
* @expose
*/
this.responseStream = response_stream;
/**
* Resolved request message type.
* @type {ProtoBuf.Reflect.Message}
* @expose
*/
this.resolvedRequestType = null;
/**
* Resolved response message type.
* @type {ProtoBuf.Reflect.Message}
* @expose
*/
this.resolvedResponseType = null;
} | javascript | function(builder, svc, name, request, response, request_stream, response_stream, options) {
Method.call(this, builder, svc, name, options);
/**
* @override
*/
this.className = "Service.RPCMethod";
/**
* Request message name.
* @type {string}
* @expose
*/
this.requestName = request;
/**
* Response message name.
* @type {string}
* @expose
*/
this.responseName = response;
/**
* Whether requests are streamed
* @type {bool}
* @expose
*/
this.requestStream = request_stream;
/**
* Whether responses are streamed
* @type {bool}
* @expose
*/
this.responseStream = response_stream;
/**
* Resolved request message type.
* @type {ProtoBuf.Reflect.Message}
* @expose
*/
this.resolvedRequestType = null;
/**
* Resolved response message type.
* @type {ProtoBuf.Reflect.Message}
* @expose
*/
this.resolvedResponseType = null;
} | [
"function",
"(",
"builder",
",",
"svc",
",",
"name",
",",
"request",
",",
"response",
",",
"request_stream",
",",
"response_stream",
",",
"options",
")",
"{",
"Method",
".",
"call",
"(",
"this",
",",
"builder",
",",
"svc",
",",
"name",
",",
"options",
")",
";",
"/**\r\n * @override\r\n */",
"this",
".",
"className",
"=",
"\"Service.RPCMethod\"",
";",
"/**\r\n * Request message name.\r\n * @type {string}\r\n * @expose\r\n */",
"this",
".",
"requestName",
"=",
"request",
";",
"/**\r\n * Response message name.\r\n * @type {string}\r\n * @expose\r\n */",
"this",
".",
"responseName",
"=",
"response",
";",
"/**\r\n * Whether requests are streamed\r\n * @type {bool}\r\n * @expose\r\n */",
"this",
".",
"requestStream",
"=",
"request_stream",
";",
"/**\r\n * Whether responses are streamed\r\n * @type {bool}\r\n * @expose\r\n */",
"this",
".",
"responseStream",
"=",
"response_stream",
";",
"/**\r\n * Resolved request message type.\r\n * @type {ProtoBuf.Reflect.Message}\r\n * @expose\r\n */",
"this",
".",
"resolvedRequestType",
"=",
"null",
";",
"/**\r\n * Resolved response message type.\r\n * @type {ProtoBuf.Reflect.Message}\r\n * @expose\r\n */",
"this",
".",
"resolvedResponseType",
"=",
"null",
";",
"}"
]
| RPC service method.
@exports ProtoBuf.Reflect.Service.RPCMethod
@param {!ProtoBuf.Builder} builder Builder reference
@param {!ProtoBuf.Reflect.Service} svc Service
@param {string} name Method name
@param {string} request Request message name
@param {string} response Response message name
@param {boolean} request_stream Whether requests are streamed
@param {boolean} response_stream Whether responses are streamed
@param {Object.<string,*>=} options Options
@constructor
@extends ProtoBuf.Reflect.Service.Method | [
"RPC",
"service",
"method",
"."
]
| 221be558728f4e1ff35627d68033911dd928b9fa | https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8696-L8745 |
|
41,101 | elsehow/signal-protocol | build/components_concat.js | function(options) {
/**
* Namespace.
* @type {ProtoBuf.Reflect.Namespace}
* @expose
*/
this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
/**
* Namespace pointer.
* @type {ProtoBuf.Reflect.T}
* @expose
*/
this.ptr = this.ns;
/**
* Resolved flag.
* @type {boolean}
* @expose
*/
this.resolved = false;
/**
* The current building result.
* @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
* @expose
*/
this.result = null;
/**
* Imported files.
* @type {Array.<string>}
* @expose
*/
this.files = {};
/**
* Import root override.
* @type {?string}
* @expose
*/
this.importRoot = null;
/**
* Options.
* @type {!Object.<string, *>}
* @expose
*/
this.options = options || {};
} | javascript | function(options) {
/**
* Namespace.
* @type {ProtoBuf.Reflect.Namespace}
* @expose
*/
this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
/**
* Namespace pointer.
* @type {ProtoBuf.Reflect.T}
* @expose
*/
this.ptr = this.ns;
/**
* Resolved flag.
* @type {boolean}
* @expose
*/
this.resolved = false;
/**
* The current building result.
* @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
* @expose
*/
this.result = null;
/**
* Imported files.
* @type {Array.<string>}
* @expose
*/
this.files = {};
/**
* Import root override.
* @type {?string}
* @expose
*/
this.importRoot = null;
/**
* Options.
* @type {!Object.<string, *>}
* @expose
*/
this.options = options || {};
} | [
"function",
"(",
"options",
")",
"{",
"/**\r\n * Namespace.\r\n * @type {ProtoBuf.Reflect.Namespace}\r\n * @expose\r\n */",
"this",
".",
"ns",
"=",
"new",
"Reflect",
".",
"Namespace",
"(",
"this",
",",
"null",
",",
"\"\"",
")",
";",
"// Global namespace\r",
"/**\r\n * Namespace pointer.\r\n * @type {ProtoBuf.Reflect.T}\r\n * @expose\r\n */",
"this",
".",
"ptr",
"=",
"this",
".",
"ns",
";",
"/**\r\n * Resolved flag.\r\n * @type {boolean}\r\n * @expose\r\n */",
"this",
".",
"resolved",
"=",
"false",
";",
"/**\r\n * The current building result.\r\n * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}\r\n * @expose\r\n */",
"this",
".",
"result",
"=",
"null",
";",
"/**\r\n * Imported files.\r\n * @type {Array.<string>}\r\n * @expose\r\n */",
"this",
".",
"files",
"=",
"{",
"}",
";",
"/**\r\n * Import root override.\r\n * @type {?string}\r\n * @expose\r\n */",
"this",
".",
"importRoot",
"=",
"null",
";",
"/**\r\n * Options.\r\n * @type {!Object.<string, *>}\r\n * @expose\r\n */",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"}"
]
| Constructs a new Builder.
@exports ProtoBuf.Builder
@class Provides the functionality to build protocol messages.
@param {Object.<string,*>=} options Options
@constructor | [
"Constructs",
"a",
"new",
"Builder",
"."
]
| 221be558728f4e1ff35627d68033911dd928b9fa | https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8774-L8824 |
|
41,102 | elsehow/signal-protocol | build/components_concat.js | propagateSyntax | function propagateSyntax(parent) {
if (parent['messages']) {
parent['messages'].forEach(function(child) {
child["syntax"] = parent["syntax"];
propagateSyntax(child);
});
}
if (parent['enums']) {
parent['enums'].forEach(function(child) {
child["syntax"] = parent["syntax"];
});
}
} | javascript | function propagateSyntax(parent) {
if (parent['messages']) {
parent['messages'].forEach(function(child) {
child["syntax"] = parent["syntax"];
propagateSyntax(child);
});
}
if (parent['enums']) {
parent['enums'].forEach(function(child) {
child["syntax"] = parent["syntax"];
});
}
} | [
"function",
"propagateSyntax",
"(",
"parent",
")",
"{",
"if",
"(",
"parent",
"[",
"'messages'",
"]",
")",
"{",
"parent",
"[",
"'messages'",
"]",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"child",
"[",
"\"syntax\"",
"]",
"=",
"parent",
"[",
"\"syntax\"",
"]",
";",
"propagateSyntax",
"(",
"child",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"parent",
"[",
"'enums'",
"]",
")",
"{",
"parent",
"[",
"'enums'",
"]",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"child",
"[",
"\"syntax\"",
"]",
"=",
"parent",
"[",
"\"syntax\"",
"]",
";",
"}",
")",
";",
"}",
"}"
]
| Propagates syntax to all children.
@param {!Object} parent
@inner | [
"Propagates",
"syntax",
"to",
"all",
"children",
"."
]
| 221be558728f4e1ff35627d68033911dd928b9fa | https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L9097-L9109 |
41,103 | elsehow/signal-protocol | build/components_concat.js | function(field, contents) {
if (!field.map)
throw Error("field is not a map");
/**
* The field corresponding to this map.
* @type {!ProtoBuf.Reflect.Field}
*/
this.field = field;
/**
* Element instance corresponding to key type.
* @type {!ProtoBuf.Reflect.Element}
*/
this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
/**
* Element instance corresponding to value type.
* @type {!ProtoBuf.Reflect.Element}
*/
this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
/**
* Internal map: stores mapping of (string form of key) -> (key, value)
* pair.
*
* We provide map semantics for arbitrary key types, but we build on top
* of an Object, which has only string keys. In order to avoid the need
* to convert a string key back to its native type in many situations,
* we store the native key value alongside the value. Thus, we only need
* a one-way mapping from a key type to its string form that guarantees
* uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
* === K2).
*
* @type {!Object<string, {key: *, value: *}>}
*/
this.map = {};
/**
* Returns the number of elements in the map.
*/
Object.defineProperty(this, "size", {
get: function() { return Object.keys(this.map).length; }
});
// Fill initial contents from a raw object.
if (contents) {
var keys = Object.keys(contents);
for (var i = 0; i < keys.length; i++) {
var key = this.keyElem.valueFromString(keys[i]);
var val = this.valueElem.verifyValue(contents[keys[i]]);
this.map[this.keyElem.valueToString(key)] =
{ key: key, value: val };
}
}
} | javascript | function(field, contents) {
if (!field.map)
throw Error("field is not a map");
/**
* The field corresponding to this map.
* @type {!ProtoBuf.Reflect.Field}
*/
this.field = field;
/**
* Element instance corresponding to key type.
* @type {!ProtoBuf.Reflect.Element}
*/
this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
/**
* Element instance corresponding to value type.
* @type {!ProtoBuf.Reflect.Element}
*/
this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
/**
* Internal map: stores mapping of (string form of key) -> (key, value)
* pair.
*
* We provide map semantics for arbitrary key types, but we build on top
* of an Object, which has only string keys. In order to avoid the need
* to convert a string key back to its native type in many situations,
* we store the native key value alongside the value. Thus, we only need
* a one-way mapping from a key type to its string form that guarantees
* uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
* === K2).
*
* @type {!Object<string, {key: *, value: *}>}
*/
this.map = {};
/**
* Returns the number of elements in the map.
*/
Object.defineProperty(this, "size", {
get: function() { return Object.keys(this.map).length; }
});
// Fill initial contents from a raw object.
if (contents) {
var keys = Object.keys(contents);
for (var i = 0; i < keys.length; i++) {
var key = this.keyElem.valueFromString(keys[i]);
var val = this.valueElem.verifyValue(contents[keys[i]]);
this.map[this.keyElem.valueToString(key)] =
{ key: key, value: val };
}
}
} | [
"function",
"(",
"field",
",",
"contents",
")",
"{",
"if",
"(",
"!",
"field",
".",
"map",
")",
"throw",
"Error",
"(",
"\"field is not a map\"",
")",
";",
"/**\r\n * The field corresponding to this map.\r\n * @type {!ProtoBuf.Reflect.Field}\r\n */",
"this",
".",
"field",
"=",
"field",
";",
"/**\r\n * Element instance corresponding to key type.\r\n * @type {!ProtoBuf.Reflect.Element}\r\n */",
"this",
".",
"keyElem",
"=",
"new",
"Reflect",
".",
"Element",
"(",
"field",
".",
"keyType",
",",
"null",
",",
"true",
",",
"field",
".",
"syntax",
")",
";",
"/**\r\n * Element instance corresponding to value type.\r\n * @type {!ProtoBuf.Reflect.Element}\r\n */",
"this",
".",
"valueElem",
"=",
"new",
"Reflect",
".",
"Element",
"(",
"field",
".",
"type",
",",
"field",
".",
"resolvedType",
",",
"false",
",",
"field",
".",
"syntax",
")",
";",
"/**\r\n * Internal map: stores mapping of (string form of key) -> (key, value)\r\n * pair.\r\n *\r\n * We provide map semantics for arbitrary key types, but we build on top\r\n * of an Object, which has only string keys. In order to avoid the need\r\n * to convert a string key back to its native type in many situations,\r\n * we store the native key value alongside the value. Thus, we only need\r\n * a one-way mapping from a key type to its string form that guarantees\r\n * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1\r\n * === K2).\r\n *\r\n * @type {!Object<string, {key: *, value: *}>}\r\n */",
"this",
".",
"map",
"=",
"{",
"}",
";",
"/**\r\n * Returns the number of elements in the map.\r\n */",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"\"size\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"this",
".",
"map",
")",
".",
"length",
";",
"}",
"}",
")",
";",
"// Fill initial contents from a raw object.\r",
"if",
"(",
"contents",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"contents",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"this",
".",
"keyElem",
".",
"valueFromString",
"(",
"keys",
"[",
"i",
"]",
")",
";",
"var",
"val",
"=",
"this",
".",
"valueElem",
".",
"verifyValue",
"(",
"contents",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
";",
"this",
".",
"map",
"[",
"this",
".",
"keyElem",
".",
"valueToString",
"(",
"key",
")",
"]",
"=",
"{",
"key",
":",
"key",
",",
"value",
":",
"val",
"}",
";",
"}",
"}",
"}"
]
| Constructs a new Map. A Map is a container that is used to implement map
fields on message objects. It closely follows the ES6 Map API; however,
it is distinct because we do not want to depend on external polyfills or
on ES6 itself.
@exports ProtoBuf.Map
@param {!ProtoBuf.Reflect.Field} field Map field
@param {Object.<string,*>=} contents Initial contents
@constructor | [
"Constructs",
"a",
"new",
"Map",
".",
"A",
"Map",
"is",
"a",
"container",
"that",
"is",
"used",
"to",
"implement",
"map",
"fields",
"on",
"message",
"objects",
".",
"It",
"closely",
"follows",
"the",
"ES6",
"Map",
"API",
";",
"however",
"it",
"is",
"distinct",
"because",
"we",
"do",
"not",
"want",
"to",
"depend",
"on",
"external",
"polyfills",
"or",
"on",
"ES6",
"itself",
"."
]
| 221be558728f4e1ff35627d68033911dd928b9fa | https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L9396-L9451 |
|
41,104 | espadrine/sc | lib/camp.js | getCompressedStream | function getCompressedStream(req, res) {
var encoding = req.headers['accept-encoding'] || '';
var stream;
var contentEncodingHeader = res.getHeader('Content-Encoding');
if ((contentEncodingHeader === 'gzip') || /\bgzip\b/.test(encoding)) {
if (!contentEncodingHeader) {
res.setHeader('Content-Encoding', 'gzip');
}
stream = zlib.createGzip();
stream.pipe(res);
} else if ((contentEncodingHeader === 'deflate') ||
/\bdeflate\b/.test(encoding)) {
if (!contentEncodingHeader) {
res.setHeader('Content-Encoding', 'deflate');
}
stream = zlib.createDeflate();
stream.pipe(res);
}
return stream;
} | javascript | function getCompressedStream(req, res) {
var encoding = req.headers['accept-encoding'] || '';
var stream;
var contentEncodingHeader = res.getHeader('Content-Encoding');
if ((contentEncodingHeader === 'gzip') || /\bgzip\b/.test(encoding)) {
if (!contentEncodingHeader) {
res.setHeader('Content-Encoding', 'gzip');
}
stream = zlib.createGzip();
stream.pipe(res);
} else if ((contentEncodingHeader === 'deflate') ||
/\bdeflate\b/.test(encoding)) {
if (!contentEncodingHeader) {
res.setHeader('Content-Encoding', 'deflate');
}
stream = zlib.createDeflate();
stream.pipe(res);
}
return stream;
} | [
"function",
"getCompressedStream",
"(",
"req",
",",
"res",
")",
"{",
"var",
"encoding",
"=",
"req",
".",
"headers",
"[",
"'accept-encoding'",
"]",
"||",
"''",
";",
"var",
"stream",
";",
"var",
"contentEncodingHeader",
"=",
"res",
".",
"getHeader",
"(",
"'Content-Encoding'",
")",
";",
"if",
"(",
"(",
"contentEncodingHeader",
"===",
"'gzip'",
")",
"||",
"/",
"\\bgzip\\b",
"/",
".",
"test",
"(",
"encoding",
")",
")",
"{",
"if",
"(",
"!",
"contentEncodingHeader",
")",
"{",
"res",
".",
"setHeader",
"(",
"'Content-Encoding'",
",",
"'gzip'",
")",
";",
"}",
"stream",
"=",
"zlib",
".",
"createGzip",
"(",
")",
";",
"stream",
".",
"pipe",
"(",
"res",
")",
";",
"}",
"else",
"if",
"(",
"(",
"contentEncodingHeader",
"===",
"'deflate'",
")",
"||",
"/",
"\\bdeflate\\b",
"/",
".",
"test",
"(",
"encoding",
")",
")",
"{",
"if",
"(",
"!",
"contentEncodingHeader",
")",
"{",
"res",
".",
"setHeader",
"(",
"'Content-Encoding'",
",",
"'deflate'",
")",
";",
"}",
"stream",
"=",
"zlib",
".",
"createDeflate",
"(",
")",
";",
"stream",
".",
"pipe",
"(",
"res",
")",
";",
"}",
"return",
"stream",
";",
"}"
]
| Return a writable response stream, using compression when possible. | [
"Return",
"a",
"writable",
"response",
"stream",
"using",
"compression",
"when",
"possible",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L247-L266 |
41,105 | espadrine/sc | lib/camp.js | concatStreams | function concatStreams(array) {
var concat = new stream.PassThrough();
function pipe(i) {
if (i < array.length - 1) {
array[i].pipe(concat, {end: false});
array[i].on('end', function () { pipe(i + 1) });
} else {
array[i].pipe(concat);
}
}
if (array.length > 0) {
pipe(0);
}
return concat;
} | javascript | function concatStreams(array) {
var concat = new stream.PassThrough();
function pipe(i) {
if (i < array.length - 1) {
array[i].pipe(concat, {end: false});
array[i].on('end', function () { pipe(i + 1) });
} else {
array[i].pipe(concat);
}
}
if (array.length > 0) {
pipe(0);
}
return concat;
} | [
"function",
"concatStreams",
"(",
"array",
")",
"{",
"var",
"concat",
"=",
"new",
"stream",
".",
"PassThrough",
"(",
")",
";",
"function",
"pipe",
"(",
"i",
")",
"{",
"if",
"(",
"i",
"<",
"array",
".",
"length",
"-",
"1",
")",
"{",
"array",
"[",
"i",
"]",
".",
"pipe",
"(",
"concat",
",",
"{",
"end",
":",
"false",
"}",
")",
";",
"array",
"[",
"i",
"]",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"pipe",
"(",
"i",
"+",
"1",
")",
"}",
")",
";",
"}",
"else",
"{",
"array",
"[",
"i",
"]",
".",
"pipe",
"(",
"concat",
")",
";",
"}",
"}",
"if",
"(",
"array",
".",
"length",
">",
"0",
")",
"{",
"pipe",
"(",
"0",
")",
";",
"}",
"return",
"concat",
";",
"}"
]
| Concatenate an array of streams into a single stream. | [
"Concatenate",
"an",
"array",
"of",
"streams",
"into",
"a",
"single",
"stream",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L269-L285 |
41,106 | espadrine/sc | lib/camp.js | augmentServer | function augmentServer(server, opts) {
server.templateReader = opts.templateReader || templateReader;
server.documentRoot = opts.documentRoot || p.join(process.cwd(), 'web');
server.saveRequestChunks = !!opts.saveRequestChunks;
server.template = template;
server.stack = [];
server.stackInsertion = 0;
defaultRoute.forEach(function(mkfn) { server.handle(mkfn(server)); });
server.stackInsertion = 0;
server.on('request', function(req, res) { listener(server, req, res) });
} | javascript | function augmentServer(server, opts) {
server.templateReader = opts.templateReader || templateReader;
server.documentRoot = opts.documentRoot || p.join(process.cwd(), 'web');
server.saveRequestChunks = !!opts.saveRequestChunks;
server.template = template;
server.stack = [];
server.stackInsertion = 0;
defaultRoute.forEach(function(mkfn) { server.handle(mkfn(server)); });
server.stackInsertion = 0;
server.on('request', function(req, res) { listener(server, req, res) });
} | [
"function",
"augmentServer",
"(",
"server",
",",
"opts",
")",
"{",
"server",
".",
"templateReader",
"=",
"opts",
".",
"templateReader",
"||",
"templateReader",
";",
"server",
".",
"documentRoot",
"=",
"opts",
".",
"documentRoot",
"||",
"p",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'web'",
")",
";",
"server",
".",
"saveRequestChunks",
"=",
"!",
"!",
"opts",
".",
"saveRequestChunks",
";",
"server",
".",
"template",
"=",
"template",
";",
"server",
".",
"stack",
"=",
"[",
"]",
";",
"server",
".",
"stackInsertion",
"=",
"0",
";",
"defaultRoute",
".",
"forEach",
"(",
"function",
"(",
"mkfn",
")",
"{",
"server",
".",
"handle",
"(",
"mkfn",
"(",
"server",
")",
")",
";",
"}",
")",
";",
"server",
".",
"stackInsertion",
"=",
"0",
";",
"server",
".",
"on",
"(",
"'request'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"listener",
"(",
"server",
",",
"req",
",",
"res",
")",
"}",
")",
";",
"}"
]
| Camp class is classy. Camp has a router function that returns the stack of functions to call, one after the other, in order to process the request. | [
"Camp",
"class",
"is",
"classy",
".",
"Camp",
"has",
"a",
"router",
"function",
"that",
"returns",
"the",
"stack",
"of",
"functions",
"to",
"call",
"one",
"after",
"the",
"other",
"in",
"order",
"to",
"process",
"the",
"request",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L356-L366 |
41,107 | espadrine/sc | lib/camp.js | listener | function listener(server, req, res) {
augmentReqRes(req, res, server);
var ask = new Ask(server, req, res);
req.ask = ask; // Legacy.
bubble(ask, 0);
} | javascript | function listener(server, req, res) {
augmentReqRes(req, res, server);
var ask = new Ask(server, req, res);
req.ask = ask; // Legacy.
bubble(ask, 0);
} | [
"function",
"listener",
"(",
"server",
",",
"req",
",",
"res",
")",
"{",
"augmentReqRes",
"(",
"req",
",",
"res",
",",
"server",
")",
";",
"var",
"ask",
"=",
"new",
"Ask",
"(",
"server",
",",
"req",
",",
"res",
")",
";",
"req",
".",
"ask",
"=",
"ask",
";",
"// Legacy.",
"bubble",
"(",
"ask",
",",
"0",
")",
";",
"}"
]
| Default request listener. | [
"Default",
"request",
"listener",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L404-L409 |
41,108 | espadrine/sc | lib/camp.js | bubble | function bubble(ask, layer) {
ask.server.stack[layer](ask.req, ask.res, function next() {
if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1);
else {
ask.res.statusCode = 500;
ask.res.end('Internal Server Error\n');
}
});
} | javascript | function bubble(ask, layer) {
ask.server.stack[layer](ask.req, ask.res, function next() {
if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1);
else {
ask.res.statusCode = 500;
ask.res.end('Internal Server Error\n');
}
});
} | [
"function",
"bubble",
"(",
"ask",
",",
"layer",
")",
"{",
"ask",
".",
"server",
".",
"stack",
"[",
"layer",
"]",
"(",
"ask",
".",
"req",
",",
"ask",
".",
"res",
",",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"ask",
".",
"server",
".",
"stack",
".",
"length",
">",
"layer",
"+",
"1",
")",
"bubble",
"(",
"ask",
",",
"layer",
"+",
"1",
")",
";",
"else",
"{",
"ask",
".",
"res",
".",
"statusCode",
"=",
"500",
";",
"ask",
".",
"res",
".",
"end",
"(",
"'Internal Server Error\\n'",
")",
";",
"}",
"}",
")",
";",
"}"
]
| The bubble goes through each layer of the stack until it reaches the surface. The surface is a Server Error, btw. | [
"The",
"bubble",
"goes",
"through",
"each",
"layer",
"of",
"the",
"stack",
"until",
"it",
"reaches",
"the",
"surface",
".",
"The",
"surface",
"is",
"a",
"Server",
"Error",
"btw",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L413-L421 |
41,109 | espadrine/sc | lib/camp.js | genericUnit | function genericUnit (server) {
var processors = [];
server.handler = function (f) { processors.push(f); };
return function genericLayer (req, res, next) {
for (var i = 0; i < processors.length; i++) {
var keep = processors[i](req.ask);
if (keep) { return; } // Don't call next, nor the rest.
}
next(); // We never catch that request.
};
} | javascript | function genericUnit (server) {
var processors = [];
server.handler = function (f) { processors.push(f); };
return function genericLayer (req, res, next) {
for (var i = 0; i < processors.length; i++) {
var keep = processors[i](req.ask);
if (keep) { return; } // Don't call next, nor the rest.
}
next(); // We never catch that request.
};
} | [
"function",
"genericUnit",
"(",
"server",
")",
"{",
"var",
"processors",
"=",
"[",
"]",
";",
"server",
".",
"handler",
"=",
"function",
"(",
"f",
")",
"{",
"processors",
".",
"push",
"(",
"f",
")",
";",
"}",
";",
"return",
"function",
"genericLayer",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"processors",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"keep",
"=",
"processors",
"[",
"i",
"]",
"(",
"req",
".",
"ask",
")",
";",
"if",
"(",
"keep",
")",
"{",
"return",
";",
"}",
"// Don't call next, nor the rest.",
"}",
"next",
"(",
")",
";",
"// We never catch that request.",
"}",
";",
"}"
]
| Generic unit. Deprecated. | [
"Generic",
"unit",
".",
"Deprecated",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L444-L454 |
41,110 | espadrine/sc | lib/camp.js | socketUnit | function socketUnit (server) {
var io = server.io;
// Client-side: <script src="/$socket.io/socket.io.js"></script>
return function socketLayer (req, res, next) {
// Socket.io doesn't care about anything but /$socket.io now.
if (req.path.slice(1, 11) !== '$socket.io') next();
};
} | javascript | function socketUnit (server) {
var io = server.io;
// Client-side: <script src="/$socket.io/socket.io.js"></script>
return function socketLayer (req, res, next) {
// Socket.io doesn't care about anything but /$socket.io now.
if (req.path.slice(1, 11) !== '$socket.io') next();
};
} | [
"function",
"socketUnit",
"(",
"server",
")",
"{",
"var",
"io",
"=",
"server",
".",
"io",
";",
"// Client-side: <script src=\"/$socket.io/socket.io.js\"></script>",
"return",
"function",
"socketLayer",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"// Socket.io doesn't care about anything but /$socket.io now.",
"if",
"(",
"req",
".",
"path",
".",
"slice",
"(",
"1",
",",
"11",
")",
"!==",
"'$socket.io'",
")",
"next",
"(",
")",
";",
"}",
";",
"}"
]
| Socket.io unit. | [
"Socket",
".",
"io",
"unit",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L457-L465 |
41,111 | espadrine/sc | lib/camp.js | wsUnit | function wsUnit (server) {
var chanPool = server.wsChannels = {};
// Main WebSocket API:
// ws(channel :: String, conListener :: function(socket))
server.ws = function ws (channel, conListener) {
if (channel[0] !== '/') {
channel = '/$websocket:' + channel; // Deprecated API.
}
if (chanPool[channel] !== undefined) {
chanPool[channel].close();
}
chanPool[channel] = new WebSocket.Server({
server: server,
path: channel,
});
chanPool[channel].on('connection', conListener);
return chanPool[channel];
};
// WebSocket broadcast API.
// webBroadcast(channel :: String, recvListener :: function(data, end))
server.wsBroadcast = function wsBroadcast (channel, recvListener) {
if (channel[0] === '/') {
return server.ws(channel, function (socket) {
socket.on('message', function wsBroadcastRecv (data, flags) {
recvListener({data: data, flags: flags}, {
send: function wsBroadcastSend (dataBack) {
chanPool[channel].clients.forEach(function (s) {
s.send(dataBack);
});
},
});
});
});
} else { // Deprecated API
return server.ws(channel, function (socket) {
socket.on('message', function wsBroadcastRecv (data, flags) {
recvListener(data, function wsBroadcastSend (dataBack) {
chanPool[channel].clients.forEach(function (s) { s.send(dataBack); });
});
});
});
}
};
return function wsLayer (req, res, next) {
// This doesn't actually get run, since ws overrides it at the root.
if (chanPool[req.path] === undefined) return next();
};
} | javascript | function wsUnit (server) {
var chanPool = server.wsChannels = {};
// Main WebSocket API:
// ws(channel :: String, conListener :: function(socket))
server.ws = function ws (channel, conListener) {
if (channel[0] !== '/') {
channel = '/$websocket:' + channel; // Deprecated API.
}
if (chanPool[channel] !== undefined) {
chanPool[channel].close();
}
chanPool[channel] = new WebSocket.Server({
server: server,
path: channel,
});
chanPool[channel].on('connection', conListener);
return chanPool[channel];
};
// WebSocket broadcast API.
// webBroadcast(channel :: String, recvListener :: function(data, end))
server.wsBroadcast = function wsBroadcast (channel, recvListener) {
if (channel[0] === '/') {
return server.ws(channel, function (socket) {
socket.on('message', function wsBroadcastRecv (data, flags) {
recvListener({data: data, flags: flags}, {
send: function wsBroadcastSend (dataBack) {
chanPool[channel].clients.forEach(function (s) {
s.send(dataBack);
});
},
});
});
});
} else { // Deprecated API
return server.ws(channel, function (socket) {
socket.on('message', function wsBroadcastRecv (data, flags) {
recvListener(data, function wsBroadcastSend (dataBack) {
chanPool[channel].clients.forEach(function (s) { s.send(dataBack); });
});
});
});
}
};
return function wsLayer (req, res, next) {
// This doesn't actually get run, since ws overrides it at the root.
if (chanPool[req.path] === undefined) return next();
};
} | [
"function",
"wsUnit",
"(",
"server",
")",
"{",
"var",
"chanPool",
"=",
"server",
".",
"wsChannels",
"=",
"{",
"}",
";",
"// Main WebSocket API:",
"// ws(channel :: String, conListener :: function(socket))",
"server",
".",
"ws",
"=",
"function",
"ws",
"(",
"channel",
",",
"conListener",
")",
"{",
"if",
"(",
"channel",
"[",
"0",
"]",
"!==",
"'/'",
")",
"{",
"channel",
"=",
"'/$websocket:'",
"+",
"channel",
";",
"// Deprecated API.",
"}",
"if",
"(",
"chanPool",
"[",
"channel",
"]",
"!==",
"undefined",
")",
"{",
"chanPool",
"[",
"channel",
"]",
".",
"close",
"(",
")",
";",
"}",
"chanPool",
"[",
"channel",
"]",
"=",
"new",
"WebSocket",
".",
"Server",
"(",
"{",
"server",
":",
"server",
",",
"path",
":",
"channel",
",",
"}",
")",
";",
"chanPool",
"[",
"channel",
"]",
".",
"on",
"(",
"'connection'",
",",
"conListener",
")",
";",
"return",
"chanPool",
"[",
"channel",
"]",
";",
"}",
";",
"// WebSocket broadcast API.",
"// webBroadcast(channel :: String, recvListener :: function(data, end))",
"server",
".",
"wsBroadcast",
"=",
"function",
"wsBroadcast",
"(",
"channel",
",",
"recvListener",
")",
"{",
"if",
"(",
"channel",
"[",
"0",
"]",
"===",
"'/'",
")",
"{",
"return",
"server",
".",
"ws",
"(",
"channel",
",",
"function",
"(",
"socket",
")",
"{",
"socket",
".",
"on",
"(",
"'message'",
",",
"function",
"wsBroadcastRecv",
"(",
"data",
",",
"flags",
")",
"{",
"recvListener",
"(",
"{",
"data",
":",
"data",
",",
"flags",
":",
"flags",
"}",
",",
"{",
"send",
":",
"function",
"wsBroadcastSend",
"(",
"dataBack",
")",
"{",
"chanPool",
"[",
"channel",
"]",
".",
"clients",
".",
"forEach",
"(",
"function",
"(",
"s",
")",
"{",
"s",
".",
"send",
"(",
"dataBack",
")",
";",
"}",
")",
";",
"}",
",",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// Deprecated API",
"return",
"server",
".",
"ws",
"(",
"channel",
",",
"function",
"(",
"socket",
")",
"{",
"socket",
".",
"on",
"(",
"'message'",
",",
"function",
"wsBroadcastRecv",
"(",
"data",
",",
"flags",
")",
"{",
"recvListener",
"(",
"data",
",",
"function",
"wsBroadcastSend",
"(",
"dataBack",
")",
"{",
"chanPool",
"[",
"channel",
"]",
".",
"clients",
".",
"forEach",
"(",
"function",
"(",
"s",
")",
"{",
"s",
".",
"send",
"(",
"dataBack",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"return",
"function",
"wsLayer",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"// This doesn't actually get run, since ws overrides it at the root.",
"if",
"(",
"chanPool",
"[",
"req",
".",
"path",
"]",
"===",
"undefined",
")",
"return",
"next",
"(",
")",
";",
"}",
";",
"}"
]
| WebSocket unit. | [
"WebSocket",
"unit",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L468-L516 |
41,112 | espadrine/sc | lib/camp.js | ajaxUnit | function ajaxUnit (server) {
var ajax = server.ajax = new EventEmitter();
// Register events to be fired before loading the ajax data.
var ajaxReq = server.ajaxReq = new EventEmitter();
return function ajaxLayer (req, res, next) {
if (req.path[1] !== '$') { return next(); }
var action = req.path.slice(2);
if (ajax.listeners(action).length <= 0) { return next(); }
res.setHeader('Content-Type', mime.json);
ajaxReq.emit(action, req.ask);
// Get all data requests.
getQueries(req, function(err) {
if (err == null) {
ajax.emit(action, req.query, function ajaxEnd(data) {
res.compressed().end(JSON.stringify(data || {}));
}, req.ask);
} else {
log('While parsing', req.url + ':\n'
+ err
, 'error');
return next();
}
});
};
} | javascript | function ajaxUnit (server) {
var ajax = server.ajax = new EventEmitter();
// Register events to be fired before loading the ajax data.
var ajaxReq = server.ajaxReq = new EventEmitter();
return function ajaxLayer (req, res, next) {
if (req.path[1] !== '$') { return next(); }
var action = req.path.slice(2);
if (ajax.listeners(action).length <= 0) { return next(); }
res.setHeader('Content-Type', mime.json);
ajaxReq.emit(action, req.ask);
// Get all data requests.
getQueries(req, function(err) {
if (err == null) {
ajax.emit(action, req.query, function ajaxEnd(data) {
res.compressed().end(JSON.stringify(data || {}));
}, req.ask);
} else {
log('While parsing', req.url + ':\n'
+ err
, 'error');
return next();
}
});
};
} | [
"function",
"ajaxUnit",
"(",
"server",
")",
"{",
"var",
"ajax",
"=",
"server",
".",
"ajax",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"// Register events to be fired before loading the ajax data.",
"var",
"ajaxReq",
"=",
"server",
".",
"ajaxReq",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"return",
"function",
"ajaxLayer",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"path",
"[",
"1",
"]",
"!==",
"'$'",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"var",
"action",
"=",
"req",
".",
"path",
".",
"slice",
"(",
"2",
")",
";",
"if",
"(",
"ajax",
".",
"listeners",
"(",
"action",
")",
".",
"length",
"<=",
"0",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"res",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"mime",
".",
"json",
")",
";",
"ajaxReq",
".",
"emit",
"(",
"action",
",",
"req",
".",
"ask",
")",
";",
"// Get all data requests.",
"getQueries",
"(",
"req",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"==",
"null",
")",
"{",
"ajax",
".",
"emit",
"(",
"action",
",",
"req",
".",
"query",
",",
"function",
"ajaxEnd",
"(",
"data",
")",
"{",
"res",
".",
"compressed",
"(",
")",
".",
"end",
"(",
"JSON",
".",
"stringify",
"(",
"data",
"||",
"{",
"}",
")",
")",
";",
"}",
",",
"req",
".",
"ask",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'While parsing'",
",",
"req",
".",
"url",
"+",
"':\\n'",
"+",
"err",
",",
"'error'",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
]
| Ajax unit. | [
"Ajax",
"unit",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L519-L547 |
41,113 | espadrine/sc | lib/camp.js | staticUnit | function staticUnit (server) {
return function staticLayer (req, res, next) {
respondWithFile(req, res, req.path, next);
};
} | javascript | function staticUnit (server) {
return function staticLayer (req, res, next) {
respondWithFile(req, res, req.path, next);
};
} | [
"function",
"staticUnit",
"(",
"server",
")",
"{",
"return",
"function",
"staticLayer",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"respondWithFile",
"(",
"req",
",",
"res",
",",
"req",
".",
"path",
",",
"next",
")",
";",
"}",
";",
"}"
]
| Static unit. | [
"Static",
"unit",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L699-L703 |
41,114 | espadrine/sc | lib/camp.js | routeUnit | function routeUnit (server) {
var regexes = [];
var callbacks = [];
function route (paths, literalCall) {
regexes.push(RegExp(paths));
callbacks.push(literalCall);
}
server.route = route;
return function routeLayer (req, res, next) {
var matched = null;
var cbindex = -1;
for (var i = 0; i < regexes.length; i++) {
matched = req.path.match (regexes[i]);
if (matched !== null) { cbindex = i; break; }
}
if (cbindex >= 0) {
catchpath(req, res, matched, callbacks[cbindex], server.templateReader);
} else {
next();
}
};
} | javascript | function routeUnit (server) {
var regexes = [];
var callbacks = [];
function route (paths, literalCall) {
regexes.push(RegExp(paths));
callbacks.push(literalCall);
}
server.route = route;
return function routeLayer (req, res, next) {
var matched = null;
var cbindex = -1;
for (var i = 0; i < regexes.length; i++) {
matched = req.path.match (regexes[i]);
if (matched !== null) { cbindex = i; break; }
}
if (cbindex >= 0) {
catchpath(req, res, matched, callbacks[cbindex], server.templateReader);
} else {
next();
}
};
} | [
"function",
"routeUnit",
"(",
"server",
")",
"{",
"var",
"regexes",
"=",
"[",
"]",
";",
"var",
"callbacks",
"=",
"[",
"]",
";",
"function",
"route",
"(",
"paths",
",",
"literalCall",
")",
"{",
"regexes",
".",
"push",
"(",
"RegExp",
"(",
"paths",
")",
")",
";",
"callbacks",
".",
"push",
"(",
"literalCall",
")",
";",
"}",
"server",
".",
"route",
"=",
"route",
";",
"return",
"function",
"routeLayer",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"matched",
"=",
"null",
";",
"var",
"cbindex",
"=",
"-",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"regexes",
".",
"length",
";",
"i",
"++",
")",
"{",
"matched",
"=",
"req",
".",
"path",
".",
"match",
"(",
"regexes",
"[",
"i",
"]",
")",
";",
"if",
"(",
"matched",
"!==",
"null",
")",
"{",
"cbindex",
"=",
"i",
";",
"break",
";",
"}",
"}",
"if",
"(",
"cbindex",
">=",
"0",
")",
"{",
"catchpath",
"(",
"req",
",",
"res",
",",
"matched",
",",
"callbacks",
"[",
"cbindex",
"]",
",",
"server",
".",
"templateReader",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
";",
"}"
]
| Template unit. | [
"Template",
"unit",
"."
]
| c1042e58fb849e1a2ec87dc22695d21329b0e8e1 | https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L854-L878 |
41,115 | damoclark/node-persistent-queue | index.js | removeJob | function removeJob(self,id) {
if(id === undefined) {
id = self.queue.shift().id ;
}
else {
// Search queue for id and remove if exists
for(var i=0;i<self.queue.length;i++) {
if(self.queue[i].id === id) {
self.queue.splice(i,1) ;
break ;
}
}
}
return new Promise(function(resolve,reject) {
if(self.db === null)
reject('Open queue database before starting queue') ;
if(self.debug) console.log('About to delete') ;
if(self.debug) console.log('Removing job: '+id) ;
if(self.debug) console.log('From table: '+table) ;
if(self.debug) console.log('With queue length: '+self.length) ;
self.db.run("DELETE FROM " + table + " WHERE id = ?", id, function(err) {
if(err !== null)
reject(err) ;
if(this.changes) // Number of rows affected (0 == false)
resolve(id) ;
reject("Job id "+id+" was not removed from queue") ;
});
}) ;
} | javascript | function removeJob(self,id) {
if(id === undefined) {
id = self.queue.shift().id ;
}
else {
// Search queue for id and remove if exists
for(var i=0;i<self.queue.length;i++) {
if(self.queue[i].id === id) {
self.queue.splice(i,1) ;
break ;
}
}
}
return new Promise(function(resolve,reject) {
if(self.db === null)
reject('Open queue database before starting queue') ;
if(self.debug) console.log('About to delete') ;
if(self.debug) console.log('Removing job: '+id) ;
if(self.debug) console.log('From table: '+table) ;
if(self.debug) console.log('With queue length: '+self.length) ;
self.db.run("DELETE FROM " + table + " WHERE id = ?", id, function(err) {
if(err !== null)
reject(err) ;
if(this.changes) // Number of rows affected (0 == false)
resolve(id) ;
reject("Job id "+id+" was not removed from queue") ;
});
}) ;
} | [
"function",
"removeJob",
"(",
"self",
",",
"id",
")",
"{",
"if",
"(",
"id",
"===",
"undefined",
")",
"{",
"id",
"=",
"self",
".",
"queue",
".",
"shift",
"(",
")",
".",
"id",
";",
"}",
"else",
"{",
"// Search queue for id and remove if exists",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"self",
".",
"queue",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"self",
".",
"queue",
"[",
"i",
"]",
".",
"id",
"===",
"id",
")",
"{",
"self",
".",
"queue",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"break",
";",
"}",
"}",
"}",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"self",
".",
"db",
"===",
"null",
")",
"reject",
"(",
"'Open queue database before starting queue'",
")",
";",
"if",
"(",
"self",
".",
"debug",
")",
"console",
".",
"log",
"(",
"'About to delete'",
")",
";",
"if",
"(",
"self",
".",
"debug",
")",
"console",
".",
"log",
"(",
"'Removing job: '",
"+",
"id",
")",
";",
"if",
"(",
"self",
".",
"debug",
")",
"console",
".",
"log",
"(",
"'From table: '",
"+",
"table",
")",
";",
"if",
"(",
"self",
".",
"debug",
")",
"console",
".",
"log",
"(",
"'With queue length: '",
"+",
"self",
".",
"length",
")",
";",
"self",
".",
"db",
".",
"run",
"(",
"\"DELETE FROM \"",
"+",
"table",
"+",
"\" WHERE id = ?\"",
",",
"id",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"!==",
"null",
")",
"reject",
"(",
"err",
")",
";",
"if",
"(",
"this",
".",
"changes",
")",
"// Number of rows affected (0 == false)",
"resolve",
"(",
"id",
")",
";",
"reject",
"(",
"\"Job id \"",
"+",
"id",
"+",
"\" was not removed from queue\"",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| This function will remove the given or current job from the database and in-memory array
@param {PersistentQueue} self Instance to work with
@param {integer} [id] Optional job id number to remove, if omitted, remove current job at front of queue
@return {Promise} | [
"This",
"function",
"will",
"remove",
"the",
"given",
"or",
"current",
"job",
"from",
"the",
"database",
"and",
"in",
"-",
"memory",
"array"
]
| 061d631c28e1434570b779bb3c3c732c4a9dd9c1 | https://github.com/damoclark/node-persistent-queue/blob/061d631c28e1434570b779bb3c3c732c4a9dd9c1/index.js#L530-L562 |
41,116 | nknapp/promised-handlebars | lib/utils.js | mapValues | function mapValues (obj, mapFn) {
return Object.keys(obj).reduce(function (result, key) {
result[key] = mapFn(obj[key], key, obj)
return result
}, {})
} | javascript | function mapValues (obj, mapFn) {
return Object.keys(obj).reduce(function (result, key) {
result[key] = mapFn(obj[key], key, obj)
return result
}, {})
} | [
"function",
"mapValues",
"(",
"obj",
",",
"mapFn",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"key",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"mapFn",
"(",
"obj",
"[",
"key",
"]",
",",
"key",
",",
"obj",
")",
"return",
"result",
"}",
",",
"{",
"}",
")",
"}"
]
| Apply the mapFn to all values of the object and return a new object with the applied values
@param obj the input object
@param {function(any, string, object): any} mapFn the map function (receives the value, the key and the whole object as parameter)
@returns {object} an object with the same keys as the input object | [
"Apply",
"the",
"mapFn",
"to",
"all",
"values",
"of",
"the",
"object",
"and",
"return",
"a",
"new",
"object",
"with",
"the",
"applied",
"values"
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/lib/utils.js#L39-L44 |
41,117 | nknapp/promised-handlebars | lib/utils.js | anyApplies | function anyApplies (array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return true
}
}
return false
} | javascript | function anyApplies (array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return true
}
}
return false
} | [
"function",
"anyApplies",
"(",
"array",
",",
"predicate",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"predicate",
"(",
"array",
"[",
"i",
"]",
")",
")",
"{",
"return",
"true",
"}",
"}",
"return",
"false",
"}"
]
| Check if the predicate is true for any element of the array
@param {Array} array
@param {function(any):boolean} predicate
@returns {boolean} | [
"Check",
"if",
"the",
"predicate",
"is",
"true",
"for",
"any",
"element",
"of",
"the",
"array"
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/lib/utils.js#L63-L70 |
41,118 | nknapp/promised-handlebars | index.js | prepareAndResolveMarkers | function prepareAndResolveMarkers (fn, args) {
if (markers) {
// The Markers-object has already been created for this cycle of the event loop:
// Just run the wraped function
return fn.apply(this, args)
}
try {
// No Markers yet. This is the initial call or some call that occured during a promise resolution
// Create markers, apply the function and resolve placeholders (i.e. promises) created during the
// function execution
markers = new Markers(engine, options.placeholder)
var resultWithPlaceholders = fn.apply(this, args)
return markers.resolve(resultWithPlaceholders)
} finally {
// Reset promises for the next execution run
markers = null
}
} | javascript | function prepareAndResolveMarkers (fn, args) {
if (markers) {
// The Markers-object has already been created for this cycle of the event loop:
// Just run the wraped function
return fn.apply(this, args)
}
try {
// No Markers yet. This is the initial call or some call that occured during a promise resolution
// Create markers, apply the function and resolve placeholders (i.e. promises) created during the
// function execution
markers = new Markers(engine, options.placeholder)
var resultWithPlaceholders = fn.apply(this, args)
return markers.resolve(resultWithPlaceholders)
} finally {
// Reset promises for the next execution run
markers = null
}
} | [
"function",
"prepareAndResolveMarkers",
"(",
"fn",
",",
"args",
")",
"{",
"if",
"(",
"markers",
")",
"{",
"// The Markers-object has already been created for this cycle of the event loop:",
"// Just run the wraped function",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
"}",
"try",
"{",
"// No Markers yet. This is the initial call or some call that occured during a promise resolution",
"// Create markers, apply the function and resolve placeholders (i.e. promises) created during the",
"// function execution",
"markers",
"=",
"new",
"Markers",
"(",
"engine",
",",
"options",
".",
"placeholder",
")",
"var",
"resultWithPlaceholders",
"=",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
"return",
"markers",
".",
"resolve",
"(",
"resultWithPlaceholders",
")",
"}",
"finally",
"{",
"// Reset promises for the next execution run",
"markers",
"=",
"null",
"}",
"}"
]
| Wrapper for templates, partials and block-helper callbacks
1) the `markers` variable is initialized with a new instance of Markers
2) a promise is returned instead of a string
3) promise placeholder-values are replaced with the promise-results
in the returned promise | [
"Wrapper",
"for",
"templates",
"partials",
"and",
"block",
"-",
"helper",
"callbacks"
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/index.js#L88-L105 |
41,119 | nknapp/promised-handlebars | lib/markers.js | Markers | function Markers (engine, prefix) {
/**
* This array stores the promises created in the current event-loop cycle
* @type {Promise[]}
*/
this.promiseStore = []
this.engine = engine
this.prefix = prefix
// one line from substack's quotemeta-package
var placeHolderRegexEscaped = String(this.prefix).replace(/(\W)/g, '\\$1')
this.regex = new RegExp(placeHolderRegexEscaped + '(\\d+)(>|>)', 'g')
} | javascript | function Markers (engine, prefix) {
/**
* This array stores the promises created in the current event-loop cycle
* @type {Promise[]}
*/
this.promiseStore = []
this.engine = engine
this.prefix = prefix
// one line from substack's quotemeta-package
var placeHolderRegexEscaped = String(this.prefix).replace(/(\W)/g, '\\$1')
this.regex = new RegExp(placeHolderRegexEscaped + '(\\d+)(>|>)', 'g')
} | [
"function",
"Markers",
"(",
"engine",
",",
"prefix",
")",
"{",
"/**\n * This array stores the promises created in the current event-loop cycle\n * @type {Promise[]}\n */",
"this",
".",
"promiseStore",
"=",
"[",
"]",
"this",
".",
"engine",
"=",
"engine",
"this",
".",
"prefix",
"=",
"prefix",
"// one line from substack's quotemeta-package",
"var",
"placeHolderRegexEscaped",
"=",
"String",
"(",
"this",
".",
"prefix",
")",
".",
"replace",
"(",
"/",
"(\\W)",
"/",
"g",
",",
"'\\\\$1'",
")",
"this",
".",
"regex",
"=",
"new",
"RegExp",
"(",
"placeHolderRegexEscaped",
"+",
"'(\\\\d+)(>|>)'",
",",
"'g'",
")",
"}"
]
| A class the handles the creation and resolution of markers in the Handlebars output.
Markes are used as placeholders in the output string for promises returned by helpers.
They are replaced as soon as the promises are resolved.
@param {Handlebars} engine a Handlebars instance (needed for the `escapeExpression` function)
@param {string} prefix the prefix to identify placeholders (this prefix should never occur in the template).
@constructor | [
"A",
"class",
"the",
"handles",
"the",
"creation",
"and",
"resolution",
"of",
"markers",
"in",
"the",
"Handlebars",
"output",
".",
"Markes",
"are",
"used",
"as",
"placeholders",
"in",
"the",
"output",
"string",
"for",
"promises",
"returned",
"by",
"helpers",
".",
"They",
"are",
"replaced",
"as",
"soon",
"as",
"the",
"promises",
"are",
"resolved",
"."
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/lib/markers.js#L29-L40 |
41,120 | attila/savvior | src/Helpers.js | each | function each(collection, fn, scope) {
var i = 0,
cont;
for (i; i < collection.length; i++) {
cont = fn.call(scope, collection[i], i);
if (cont === false) {
break; //allow early exit
}
}
} | javascript | function each(collection, fn, scope) {
var i = 0,
cont;
for (i; i < collection.length; i++) {
cont = fn.call(scope, collection[i], i);
if (cont === false) {
break; //allow early exit
}
}
} | [
"function",
"each",
"(",
"collection",
",",
"fn",
",",
"scope",
")",
"{",
"var",
"i",
"=",
"0",
",",
"cont",
";",
"for",
"(",
"i",
";",
"i",
"<",
"collection",
".",
"length",
";",
"i",
"++",
")",
"{",
"cont",
"=",
"fn",
".",
"call",
"(",
"scope",
",",
"collection",
"[",
"i",
"]",
",",
"i",
")",
";",
"if",
"(",
"cont",
"===",
"false",
")",
"{",
"break",
";",
"//allow early exit",
"}",
"}",
"}"
]
| Helper function for iterating over a collection
@param collection
@param fn
@param scope | [
"Helper",
"function",
"for",
"iterating",
"over",
"a",
"collection"
]
| 860e887756465acc2abf348ae7073e2d603f523f | https://github.com/attila/savvior/blob/860e887756465acc2abf348ae7073e2d603f523f/src/Helpers.js#L22-L32 |
41,121 | attila/savvior | src/Grid.js | function(element) {
this.columns = null;
this.element = element;
this.filtered = document.createDocumentFragment();
this.status = false;
this.columnClasses = null;
} | javascript | function(element) {
this.columns = null;
this.element = element;
this.filtered = document.createDocumentFragment();
this.status = false;
this.columnClasses = null;
} | [
"function",
"(",
"element",
")",
"{",
"this",
".",
"columns",
"=",
"null",
";",
"this",
".",
"element",
"=",
"element",
";",
"this",
".",
"filtered",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"this",
".",
"status",
"=",
"false",
";",
"this",
".",
"columnClasses",
"=",
"null",
";",
"}"
]
| Implements the grid element and its internal manipulation features
@param {Object} Grid
@param {String} Grid.columns Stores the current number of columns
@param {Object} Grid.element Stores the DOM object of the grid element
@param {Boolean} Grid.status Pointer to maintain the Grid status
@constructor | [
"Implements",
"the",
"grid",
"element",
"and",
"its",
"internal",
"manipulation",
"features"
]
| 860e887756465acc2abf348ae7073e2d603f523f | https://github.com/attila/savvior/blob/860e887756465acc2abf348ae7073e2d603f523f/src/Grid.js#L10-L16 |
|
41,122 | anseki/plain-overlay | plain-overlay.esm.js | setStyle | function setStyle(element, styleProps, savedStyleProps, propNames) {
var style = element.style;
(propNames || Object.keys(styleProps)).forEach(function (prop) {
if (styleProps[prop] != null) {
if (savedStyleProps && savedStyleProps[prop] == null) {
savedStyleProps[prop] = style[prop];
}
style[prop] = styleProps[prop];
styleProps[prop] = null;
}
});
return element;
} | javascript | function setStyle(element, styleProps, savedStyleProps, propNames) {
var style = element.style;
(propNames || Object.keys(styleProps)).forEach(function (prop) {
if (styleProps[prop] != null) {
if (savedStyleProps && savedStyleProps[prop] == null) {
savedStyleProps[prop] = style[prop];
}
style[prop] = styleProps[prop];
styleProps[prop] = null;
}
});
return element;
} | [
"function",
"setStyle",
"(",
"element",
",",
"styleProps",
",",
"savedStyleProps",
",",
"propNames",
")",
"{",
"var",
"style",
"=",
"element",
".",
"style",
";",
"(",
"propNames",
"||",
"Object",
".",
"keys",
"(",
"styleProps",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"if",
"(",
"styleProps",
"[",
"prop",
"]",
"!=",
"null",
")",
"{",
"if",
"(",
"savedStyleProps",
"&&",
"savedStyleProps",
"[",
"prop",
"]",
"==",
"null",
")",
"{",
"savedStyleProps",
"[",
"prop",
"]",
"=",
"style",
"[",
"prop",
"]",
";",
"}",
"style",
"[",
"prop",
"]",
"=",
"styleProps",
"[",
"prop",
"]",
";",
"styleProps",
"[",
"prop",
"]",
"=",
"null",
";",
"}",
"}",
")",
";",
"return",
"element",
";",
"}"
]
| Set style properties while saving current properties.
@param {Element} element - Target element.
@param {Object} styleProps - New style properties.
@param {(Object|null)} savedStyleProps - Current style properties holder.
@param {Array} [propNames] - Names of target properties.
@returns {Element} Target element itself. | [
"Set",
"style",
"properties",
"while",
"saving",
"current",
"properties",
"."
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/plain-overlay.esm.js#L105-L117 |
41,123 | anseki/plain-overlay | plain-overlay.esm.js | getDocClientWH | function getDocClientWH(props) {
var elmTarget = props.elmTarget,
width = elmTarget.clientWidth,
height = elmTarget.clientHeight;
if (IS_TRIDENT || IS_EDGE) {
var targetBodyCmpStyle = props.window.getComputedStyle(props.elmTargetBody, ''),
wMode = targetBodyCmpStyle.writingMode || targetBodyCmpStyle['writing-mode'],
// Trident bug
direction = targetBodyCmpStyle.direction;
return wMode === 'tb-rl' || wMode === 'bt-rl' || wMode === 'tb-lr' || wMode === 'bt-lr' || IS_EDGE && (direction === 'ltr' && (wMode === 'vertical-rl' || wMode === 'vertical-lr') || direction === 'rtl' && (wMode === 'vertical-rl' || wMode === 'vertical-lr')) ? { width: height, height: width } : // interchange
{ width: width, height: height };
}
return { width: width, height: height };
} | javascript | function getDocClientWH(props) {
var elmTarget = props.elmTarget,
width = elmTarget.clientWidth,
height = elmTarget.clientHeight;
if (IS_TRIDENT || IS_EDGE) {
var targetBodyCmpStyle = props.window.getComputedStyle(props.elmTargetBody, ''),
wMode = targetBodyCmpStyle.writingMode || targetBodyCmpStyle['writing-mode'],
// Trident bug
direction = targetBodyCmpStyle.direction;
return wMode === 'tb-rl' || wMode === 'bt-rl' || wMode === 'tb-lr' || wMode === 'bt-lr' || IS_EDGE && (direction === 'ltr' && (wMode === 'vertical-rl' || wMode === 'vertical-lr') || direction === 'rtl' && (wMode === 'vertical-rl' || wMode === 'vertical-lr')) ? { width: height, height: width } : // interchange
{ width: width, height: height };
}
return { width: width, height: height };
} | [
"function",
"getDocClientWH",
"(",
"props",
")",
"{",
"var",
"elmTarget",
"=",
"props",
".",
"elmTarget",
",",
"width",
"=",
"elmTarget",
".",
"clientWidth",
",",
"height",
"=",
"elmTarget",
".",
"clientHeight",
";",
"if",
"(",
"IS_TRIDENT",
"||",
"IS_EDGE",
")",
"{",
"var",
"targetBodyCmpStyle",
"=",
"props",
".",
"window",
".",
"getComputedStyle",
"(",
"props",
".",
"elmTargetBody",
",",
"''",
")",
",",
"wMode",
"=",
"targetBodyCmpStyle",
".",
"writingMode",
"||",
"targetBodyCmpStyle",
"[",
"'writing-mode'",
"]",
",",
"// Trident bug",
"direction",
"=",
"targetBodyCmpStyle",
".",
"direction",
";",
"return",
"wMode",
"===",
"'tb-rl'",
"||",
"wMode",
"===",
"'bt-rl'",
"||",
"wMode",
"===",
"'tb-lr'",
"||",
"wMode",
"===",
"'bt-lr'",
"||",
"IS_EDGE",
"&&",
"(",
"direction",
"===",
"'ltr'",
"&&",
"(",
"wMode",
"===",
"'vertical-rl'",
"||",
"wMode",
"===",
"'vertical-lr'",
")",
"||",
"direction",
"===",
"'rtl'",
"&&",
"(",
"wMode",
"===",
"'vertical-rl'",
"||",
"wMode",
"===",
"'vertical-lr'",
")",
")",
"?",
"{",
"width",
":",
"height",
",",
"height",
":",
"width",
"}",
":",
"// interchange",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
"}",
";",
"}",
"return",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
"}",
";",
"}"
]
| Trident and Edge bug, width and height are interchanged. | [
"Trident",
"and",
"Edge",
"bug",
"width",
"and",
"height",
"are",
"interchanged",
"."
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/plain-overlay.esm.js#L238-L251 |
41,124 | anseki/plain-overlay | plain-overlay.esm.js | nodeContainsSel | function nodeContainsSel(node, selection) {
var nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNode(node);
for (var i = 0; i < iLen; i++) {
var selRange = selection.getRangeAt(i);
if (selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 || selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return false;
}
}
return true;
} | javascript | function nodeContainsSel(node, selection) {
var nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNode(node);
for (var i = 0; i < iLen; i++) {
var selRange = selection.getRangeAt(i);
if (selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 || selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return false;
}
}
return true;
} | [
"function",
"nodeContainsSel",
"(",
"node",
",",
"selection",
")",
"{",
"var",
"nodeRange",
"=",
"node",
".",
"ownerDocument",
".",
"createRange",
"(",
")",
",",
"iLen",
"=",
"selection",
".",
"rangeCount",
";",
"nodeRange",
".",
"selectNode",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"iLen",
";",
"i",
"++",
")",
"{",
"var",
"selRange",
"=",
"selection",
".",
"getRangeAt",
"(",
"i",
")",
";",
"if",
"(",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"START_TO_START",
",",
"nodeRange",
")",
"<",
"0",
"||",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"END_TO_END",
",",
"nodeRange",
")",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Indicates whether the selection is part of the node or not.
@param {Node} node - Target node.
@param {Selection} selection - The parsed selection.
@returns {boolean} `true` if all ranges of `selection` are part of `node`. | [
"Indicates",
"whether",
"the",
"selection",
"is",
"part",
"of",
"the",
"node",
"or",
"not",
"."
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/plain-overlay.esm.js#L342-L353 |
41,125 | topliceanu/sum | sum.js | function (str) {
return _(str).chain()
.unescapeHTML()
.stripTags()
.clean()
.value()
.replace( matchJunk, '' )
.toLowerCase();
} | javascript | function (str) {
return _(str).chain()
.unescapeHTML()
.stripTags()
.clean()
.value()
.replace( matchJunk, '' )
.toLowerCase();
} | [
"function",
"(",
"str",
")",
"{",
"return",
"_",
"(",
"str",
")",
".",
"chain",
"(",
")",
".",
"unescapeHTML",
"(",
")",
".",
"stripTags",
"(",
")",
".",
"clean",
"(",
")",
".",
"value",
"(",
")",
".",
"replace",
"(",
"matchJunk",
",",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"}"
]
| Function used to clean sentences before splitting into words
@param {String} str
@return {String} | [
"Function",
"used",
"to",
"clean",
"sentences",
"before",
"splitting",
"into",
"words"
]
| b3f3195cfca95b1f690cb01aebfe7d2d59ce4890 | https://github.com/topliceanu/sum/blob/b3f3195cfca95b1f690cb01aebfe7d2d59ce4890/sum.js#L78-L86 |
|
41,126 | anseki/plain-overlay | src/plain-overlay.js | selContainsNode | function selContainsNode(selection, node, partialContainment) {
const nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNodeContents(node);
for (let i = 0; i < iLen; i++) {
const selRange = selection.getRangeAt(i);
// Edge bug (Issue #7321753); getRangeAt returns empty (collapsed) range
// NOTE: It can not recover when the selection has multiple ranges.
if (!selRange.toString().length && selection.toString().length && iLen === 1) {
console.log('Edge bug (Issue #7321753)'); // [DEBUG/]
selRange.setStart(selection.anchorNode, selection.anchorOffset);
selRange.setEnd(selection.focusNode, selection.focusOffset);
// Edge doesn't throw when end is upper than start.
if (selRange.toString() !== selection.toString()) {
selRange.setStart(selection.focusNode, selection.focusOffset);
selRange.setEnd(selection.anchorNode, selection.anchorOffset);
if (selRange.toString() !== selection.toString()) {
throw new Error('Edge bug (Issue #7321753); Couldn\'t recover');
}
}
}
if (partialContainment
? selRange.compareBoundaryPoints(Range.START_TO_END, nodeRange) >= 0 &&
selRange.compareBoundaryPoints(Range.END_TO_START, nodeRange) <= 0 :
selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 &&
selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return true;
}
}
return false;
} | javascript | function selContainsNode(selection, node, partialContainment) {
const nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNodeContents(node);
for (let i = 0; i < iLen; i++) {
const selRange = selection.getRangeAt(i);
// Edge bug (Issue #7321753); getRangeAt returns empty (collapsed) range
// NOTE: It can not recover when the selection has multiple ranges.
if (!selRange.toString().length && selection.toString().length && iLen === 1) {
console.log('Edge bug (Issue #7321753)'); // [DEBUG/]
selRange.setStart(selection.anchorNode, selection.anchorOffset);
selRange.setEnd(selection.focusNode, selection.focusOffset);
// Edge doesn't throw when end is upper than start.
if (selRange.toString() !== selection.toString()) {
selRange.setStart(selection.focusNode, selection.focusOffset);
selRange.setEnd(selection.anchorNode, selection.anchorOffset);
if (selRange.toString() !== selection.toString()) {
throw new Error('Edge bug (Issue #7321753); Couldn\'t recover');
}
}
}
if (partialContainment
? selRange.compareBoundaryPoints(Range.START_TO_END, nodeRange) >= 0 &&
selRange.compareBoundaryPoints(Range.END_TO_START, nodeRange) <= 0 :
selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 &&
selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return true;
}
}
return false;
} | [
"function",
"selContainsNode",
"(",
"selection",
",",
"node",
",",
"partialContainment",
")",
"{",
"const",
"nodeRange",
"=",
"node",
".",
"ownerDocument",
".",
"createRange",
"(",
")",
",",
"iLen",
"=",
"selection",
".",
"rangeCount",
";",
"nodeRange",
".",
"selectNodeContents",
"(",
"node",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"iLen",
";",
"i",
"++",
")",
"{",
"const",
"selRange",
"=",
"selection",
".",
"getRangeAt",
"(",
"i",
")",
";",
"// Edge bug (Issue #7321753); getRangeAt returns empty (collapsed) range",
"// NOTE: It can not recover when the selection has multiple ranges.",
"if",
"(",
"!",
"selRange",
".",
"toString",
"(",
")",
".",
"length",
"&&",
"selection",
".",
"toString",
"(",
")",
".",
"length",
"&&",
"iLen",
"===",
"1",
")",
"{",
"console",
".",
"log",
"(",
"'Edge bug (Issue #7321753)'",
")",
";",
"// [DEBUG/]",
"selRange",
".",
"setStart",
"(",
"selection",
".",
"anchorNode",
",",
"selection",
".",
"anchorOffset",
")",
";",
"selRange",
".",
"setEnd",
"(",
"selection",
".",
"focusNode",
",",
"selection",
".",
"focusOffset",
")",
";",
"// Edge doesn't throw when end is upper than start.",
"if",
"(",
"selRange",
".",
"toString",
"(",
")",
"!==",
"selection",
".",
"toString",
"(",
")",
")",
"{",
"selRange",
".",
"setStart",
"(",
"selection",
".",
"focusNode",
",",
"selection",
".",
"focusOffset",
")",
";",
"selRange",
".",
"setEnd",
"(",
"selection",
".",
"anchorNode",
",",
"selection",
".",
"anchorOffset",
")",
";",
"if",
"(",
"selRange",
".",
"toString",
"(",
")",
"!==",
"selection",
".",
"toString",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Edge bug (Issue #7321753); Couldn\\'t recover'",
")",
";",
"}",
"}",
"}",
"if",
"(",
"partialContainment",
"?",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"START_TO_END",
",",
"nodeRange",
")",
">=",
"0",
"&&",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"END_TO_START",
",",
"nodeRange",
")",
"<=",
"0",
":",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"START_TO_START",
",",
"nodeRange",
")",
"<",
"0",
"&&",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"END_TO_END",
",",
"nodeRange",
")",
">",
"0",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Selection.containsNode polyfill for Trident | [
"Selection",
".",
"containsNode",
"polyfill",
"for",
"Trident"
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/src/plain-overlay.js#L343-L373 |
41,127 | clns/node-commit-msg | lib/nlp-parser.js | getMatchingParenthesis | function getMatchingParenthesis(string, startPos) {
var length = string.length;
var bracket = 1;
for (var i=startPos+1; i<=length; i++) {
if (string[i] == '(') {
bracket += 1;
} else if (string[i] == ')') {
bracket -= 1;
}
if (bracket == 0) {
return i;
}
}
} | javascript | function getMatchingParenthesis(string, startPos) {
var length = string.length;
var bracket = 1;
for (var i=startPos+1; i<=length; i++) {
if (string[i] == '(') {
bracket += 1;
} else if (string[i] == ')') {
bracket -= 1;
}
if (bracket == 0) {
return i;
}
}
} | [
"function",
"getMatchingParenthesis",
"(",
"string",
",",
"startPos",
")",
"{",
"var",
"length",
"=",
"string",
".",
"length",
";",
"var",
"bracket",
"=",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"startPos",
"+",
"1",
";",
"i",
"<=",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"string",
"[",
"i",
"]",
"==",
"'('",
")",
"{",
"bracket",
"+=",
"1",
";",
"}",
"else",
"if",
"(",
"string",
"[",
"i",
"]",
"==",
"')'",
")",
"{",
"bracket",
"-=",
"1",
";",
"}",
"if",
"(",
"bracket",
"==",
"0",
")",
"{",
"return",
"i",
";",
"}",
"}",
"}"
]
| Find the position of a matching closing bracket for a string opening bracket | [
"Find",
"the",
"position",
"of",
"a",
"matching",
"closing",
"bracket",
"for",
"a",
"string",
"opening",
"bracket"
]
| 53108eca78f627e770d0d885e4ae0b4ddf87f141 | https://github.com/clns/node-commit-msg/blob/53108eca78f627e770d0d885e4ae0b4ddf87f141/lib/nlp-parser.js#L218-L231 |
41,128 | Maheshkumar-Kakade/otp-generator | index.js | function (length, options) {
length = length || 10
var generateOptions = options || {}
generateOptions.digits = generateOptions.hasOwnProperty('digits') ? options.digits : true
generateOptions.alphabets = generateOptions.hasOwnProperty('alphabets') ? options.alphabets : true
generateOptions.upperCase = generateOptions.hasOwnProperty('upperCase') ? options.upperCase : true
generateOptions.specialChars = generateOptions.hasOwnProperty('specialChars') ? options.specialChars : true
var allowsChars = ((generateOptions.digits || '') && digits) +
((generateOptions.alphabets || '') && alphabets) +
((generateOptions.upperCase || '') && upperCase) +
((generateOptions.specialChars || '') && specialChars)
var password = ''
for (var index = 0; index < length; ++index) {
var charIndex = rand(0, allowsChars.length - 1)
password += allowsChars[charIndex]
}
return password
} | javascript | function (length, options) {
length = length || 10
var generateOptions = options || {}
generateOptions.digits = generateOptions.hasOwnProperty('digits') ? options.digits : true
generateOptions.alphabets = generateOptions.hasOwnProperty('alphabets') ? options.alphabets : true
generateOptions.upperCase = generateOptions.hasOwnProperty('upperCase') ? options.upperCase : true
generateOptions.specialChars = generateOptions.hasOwnProperty('specialChars') ? options.specialChars : true
var allowsChars = ((generateOptions.digits || '') && digits) +
((generateOptions.alphabets || '') && alphabets) +
((generateOptions.upperCase || '') && upperCase) +
((generateOptions.specialChars || '') && specialChars)
var password = ''
for (var index = 0; index < length; ++index) {
var charIndex = rand(0, allowsChars.length - 1)
password += allowsChars[charIndex]
}
return password
} | [
"function",
"(",
"length",
",",
"options",
")",
"{",
"length",
"=",
"length",
"||",
"10",
"var",
"generateOptions",
"=",
"options",
"||",
"{",
"}",
"generateOptions",
".",
"digits",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'digits'",
")",
"?",
"options",
".",
"digits",
":",
"true",
"generateOptions",
".",
"alphabets",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'alphabets'",
")",
"?",
"options",
".",
"alphabets",
":",
"true",
"generateOptions",
".",
"upperCase",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'upperCase'",
")",
"?",
"options",
".",
"upperCase",
":",
"true",
"generateOptions",
".",
"specialChars",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'specialChars'",
")",
"?",
"options",
".",
"specialChars",
":",
"true",
"var",
"allowsChars",
"=",
"(",
"(",
"generateOptions",
".",
"digits",
"||",
"''",
")",
"&&",
"digits",
")",
"+",
"(",
"(",
"generateOptions",
".",
"alphabets",
"||",
"''",
")",
"&&",
"alphabets",
")",
"+",
"(",
"(",
"generateOptions",
".",
"upperCase",
"||",
"''",
")",
"&&",
"upperCase",
")",
"+",
"(",
"(",
"generateOptions",
".",
"specialChars",
"||",
"''",
")",
"&&",
"specialChars",
")",
"var",
"password",
"=",
"''",
"for",
"(",
"var",
"index",
"=",
"0",
";",
"index",
"<",
"length",
";",
"++",
"index",
")",
"{",
"var",
"charIndex",
"=",
"rand",
"(",
"0",
",",
"allowsChars",
".",
"length",
"-",
"1",
")",
"password",
"+=",
"allowsChars",
"[",
"charIndex",
"]",
"}",
"return",
"password",
"}"
]
| Generate OTP of the length
@param {number} length length of password.
@param {object} options
@param {boolean} options.digits Default: `true` true value includes digits in OTP
@param {boolean} options.alphabets Default: `true` true value includes alphabets in OTP
@param {boolean} options.upperCase Default: `true` true value includes upperCase in OTP
@param {boolean} options.specialChars Default: `true` true value includes specialChars in OTP | [
"Generate",
"OTP",
"of",
"the",
"length"
]
| 9d794ce1a2ae78c974ec5913588fe8043e9073ba | https://github.com/Maheshkumar-Kakade/otp-generator/blob/9d794ce1a2ae78c974ec5913588fe8043e9073ba/index.js#L24-L43 |
|
41,129 | maxazan/angular-multiple-selection | multiple-selection.js | getSelectableElements | function getSelectableElements(element) {
var out = [];
var childs = element.children();
for (var i = 0; i < childs.length; i++) {
var child = angular.element(childs[i]);
if (child.scope().isSelectable) {
out.push(child);
} else {
if (child.scope().$id!=element.scope().$id && child.scope().isSelectableZone === true) {
} else {
out = out.concat(getSelectableElements(child));
}
}
}
return out;
} | javascript | function getSelectableElements(element) {
var out = [];
var childs = element.children();
for (var i = 0; i < childs.length; i++) {
var child = angular.element(childs[i]);
if (child.scope().isSelectable) {
out.push(child);
} else {
if (child.scope().$id!=element.scope().$id && child.scope().isSelectableZone === true) {
} else {
out = out.concat(getSelectableElements(child));
}
}
}
return out;
} | [
"function",
"getSelectableElements",
"(",
"element",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"var",
"childs",
"=",
"element",
".",
"children",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childs",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"child",
"=",
"angular",
".",
"element",
"(",
"childs",
"[",
"i",
"]",
")",
";",
"if",
"(",
"child",
".",
"scope",
"(",
")",
".",
"isSelectable",
")",
"{",
"out",
".",
"push",
"(",
"child",
")",
";",
"}",
"else",
"{",
"if",
"(",
"child",
".",
"scope",
"(",
")",
".",
"$id",
"!=",
"element",
".",
"scope",
"(",
")",
".",
"$id",
"&&",
"child",
".",
"scope",
"(",
")",
".",
"isSelectableZone",
"===",
"true",
")",
"{",
"}",
"else",
"{",
"out",
"=",
"out",
".",
"concat",
"(",
"getSelectableElements",
"(",
"child",
")",
")",
";",
"}",
"}",
"}",
"return",
"out",
";",
"}"
]
| Angular JS multiple-selection module
@author Maksym Pomazan
@version 0.0.3 | [
"Angular",
"JS",
"multiple",
"-",
"selection",
"module"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L6-L22 |
41,130 | maxazan/angular-multiple-selection | multiple-selection.js | checkElementHitting | function checkElementHitting(box1, box2) {
return (box2.beginX <= box1.beginX && box1.beginX <= box2.endX || box1.beginX <= box2.beginX && box2.beginX <= box1.endX) &&
(box2.beginY <= box1.beginY && box1.beginY <= box2.endY || box1.beginY <= box2.beginY && box2.beginY <= box1.endY);
} | javascript | function checkElementHitting(box1, box2) {
return (box2.beginX <= box1.beginX && box1.beginX <= box2.endX || box1.beginX <= box2.beginX && box2.beginX <= box1.endX) &&
(box2.beginY <= box1.beginY && box1.beginY <= box2.endY || box1.beginY <= box2.beginY && box2.beginY <= box1.endY);
} | [
"function",
"checkElementHitting",
"(",
"box1",
",",
"box2",
")",
"{",
"return",
"(",
"box2",
".",
"beginX",
"<=",
"box1",
".",
"beginX",
"&&",
"box1",
".",
"beginX",
"<=",
"box2",
".",
"endX",
"||",
"box1",
".",
"beginX",
"<=",
"box2",
".",
"beginX",
"&&",
"box2",
".",
"beginX",
"<=",
"box1",
".",
"endX",
")",
"&&",
"(",
"box2",
".",
"beginY",
"<=",
"box1",
".",
"beginY",
"&&",
"box1",
".",
"beginY",
"<=",
"box2",
".",
"endY",
"||",
"box1",
".",
"beginY",
"<=",
"box2",
".",
"beginY",
"&&",
"box2",
".",
"beginY",
"<=",
"box1",
".",
"endY",
")",
";",
"}"
]
| Check that 2 boxes hitting
@param {Object} box1
@param {Object} box2
@return {Boolean} is hitting | [
"Check",
"that",
"2",
"boxes",
"hitting"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L99-L102 |
41,131 | maxazan/angular-multiple-selection | multiple-selection.js | moveSelectionHelper | function moveSelectionHelper(hepler, startX, startY, endX, endY) {
var box = transformBox(startX, startY, endX, endY);
helper.css({
"top": box.beginY + "px",
"left": box.beginX + "px",
"width": (box.endX - box.beginX) + "px",
"height": (box.endY - box.beginY) + "px"
});
} | javascript | function moveSelectionHelper(hepler, startX, startY, endX, endY) {
var box = transformBox(startX, startY, endX, endY);
helper.css({
"top": box.beginY + "px",
"left": box.beginX + "px",
"width": (box.endX - box.beginX) + "px",
"height": (box.endY - box.beginY) + "px"
});
} | [
"function",
"moveSelectionHelper",
"(",
"hepler",
",",
"startX",
",",
"startY",
",",
"endX",
",",
"endY",
")",
"{",
"var",
"box",
"=",
"transformBox",
"(",
"startX",
",",
"startY",
",",
"endX",
",",
"endY",
")",
";",
"helper",
".",
"css",
"(",
"{",
"\"top\"",
":",
"box",
".",
"beginY",
"+",
"\"px\"",
",",
"\"left\"",
":",
"box",
".",
"beginX",
"+",
"\"px\"",
",",
"\"width\"",
":",
"(",
"box",
".",
"endX",
"-",
"box",
".",
"beginX",
")",
"+",
"\"px\"",
",",
"\"height\"",
":",
"(",
"box",
".",
"endY",
"-",
"box",
".",
"beginY",
")",
"+",
"\"px\"",
"}",
")",
";",
"}"
]
| Method move selection helper
@param {Element} hepler
@param {Number} startX
@param {Number} startY
@param {Number} endX
@param {Number} endY | [
"Method",
"move",
"selection",
"helper"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L143-L153 |
41,132 | maxazan/angular-multiple-selection | multiple-selection.js | mousemove | function mousemove(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Move helper
moveSelectionHelper(helper, startX, startY, event.pageX, event.pageY);
// Check items is selecting
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (checkElementHitting(transformBox(offset(childs[i][0]).left, offset(childs[i][0]).top, offset(childs[i][0]).left + childs[i].prop('offsetWidth'), offset(childs[i][0]).top + childs[i].prop('offsetHeight')), transformBox(startX, startY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelecting === false) {
childs[i].scope().isSelecting = true;
childs[i].scope().$apply();
}
} else {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().$apply();
}
}
}
} | javascript | function mousemove(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Move helper
moveSelectionHelper(helper, startX, startY, event.pageX, event.pageY);
// Check items is selecting
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (checkElementHitting(transformBox(offset(childs[i][0]).left, offset(childs[i][0]).top, offset(childs[i][0]).left + childs[i].prop('offsetWidth'), offset(childs[i][0]).top + childs[i].prop('offsetHeight')), transformBox(startX, startY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelecting === false) {
childs[i].scope().isSelecting = true;
childs[i].scope().$apply();
}
} else {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().$apply();
}
}
}
} | [
"function",
"mousemove",
"(",
"event",
")",
"{",
"// Prevent default dragging of selected content",
"event",
".",
"preventDefault",
"(",
")",
";",
"// Move helper",
"moveSelectionHelper",
"(",
"helper",
",",
"startX",
",",
"startY",
",",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
")",
";",
"// Check items is selecting",
"var",
"childs",
"=",
"getSelectableElements",
"(",
"element",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"checkElementHitting",
"(",
"transformBox",
"(",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"left",
",",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"top",
",",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"left",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetWidth'",
")",
",",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"top",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetHeight'",
")",
")",
",",
"transformBox",
"(",
"startX",
",",
"startY",
",",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
")",
")",
")",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"===",
"false",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"=",
"true",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"===",
"true",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"=",
"false",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"}",
"}",
"}"
]
| Method on Mouse Move
@param {Event} @event | [
"Method",
"on",
"Mouse",
"Move"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L160-L180 |
41,133 | maxazan/angular-multiple-selection | multiple-selection.js | mouseup | function mouseup(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Remove helper
helper.remove();
// Change all selecting items to selected
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().isSelected = event.ctrlKey ? !childs[i].scope().isSelected : true;
childs[i].scope().$apply();
} else {
if (checkElementHitting(transformBox(childs[i].prop('offsetLeft'), childs[i].prop('offsetTop'), childs[i].prop('offsetLeft') + childs[i].prop('offsetWidth'), childs[i].prop('offsetTop') + childs[i].prop('offsetHeight')), transformBox(event.pageX, event.pageY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelected === false) {
childs[i].scope().isSelected = true;
childs[i].scope().$apply();
}
}
}
}
// Remove listeners
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
} | javascript | function mouseup(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Remove helper
helper.remove();
// Change all selecting items to selected
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().isSelected = event.ctrlKey ? !childs[i].scope().isSelected : true;
childs[i].scope().$apply();
} else {
if (checkElementHitting(transformBox(childs[i].prop('offsetLeft'), childs[i].prop('offsetTop'), childs[i].prop('offsetLeft') + childs[i].prop('offsetWidth'), childs[i].prop('offsetTop') + childs[i].prop('offsetHeight')), transformBox(event.pageX, event.pageY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelected === false) {
childs[i].scope().isSelected = true;
childs[i].scope().$apply();
}
}
}
}
// Remove listeners
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
} | [
"function",
"mouseup",
"(",
"event",
")",
"{",
"// Prevent default dragging of selected content",
"event",
".",
"preventDefault",
"(",
")",
";",
"// Remove helper",
"helper",
".",
"remove",
"(",
")",
";",
"// Change all selecting items to selected",
"var",
"childs",
"=",
"getSelectableElements",
"(",
"element",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"===",
"true",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"=",
"false",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
"=",
"event",
".",
"ctrlKey",
"?",
"!",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
":",
"true",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"checkElementHitting",
"(",
"transformBox",
"(",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetLeft'",
")",
",",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetTop'",
")",
",",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetLeft'",
")",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetWidth'",
")",
",",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetTop'",
")",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetHeight'",
")",
")",
",",
"transformBox",
"(",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
",",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
")",
")",
")",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
"===",
"false",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
"=",
"true",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"}",
"}",
"}",
"// Remove listeners",
"$document",
".",
"off",
"(",
"'mousemove'",
",",
"mousemove",
")",
";",
"$document",
".",
"off",
"(",
"'mouseup'",
",",
"mouseup",
")",
";",
"}"
]
| Event on Mouse up
@param {Event} event | [
"Event",
"on",
"Mouse",
"up"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L188-L214 |
41,134 | clns/node-commit-msg | lib/commit-message.js | function(verb) {
var matches = verb.value.match(/^VB[^P\s]+ (\S+)$/);
if (matches) {
var index = s.indexOf(matches[1]);
this._log('Use imperative present tense, eg. "Fix bug" not ' +
'"Fixed bug" or "Fixes bug". To get it right ask yourself: "If applied, ' +
'this patch will <YOUR-COMMIT-MESSAGE-HERE>"',
cfg.imperativeVerbsInSubject.type, [1, index+1+this._colOffset]);
hasError = true;
return false; // stop loop
}
return true;
} | javascript | function(verb) {
var matches = verb.value.match(/^VB[^P\s]+ (\S+)$/);
if (matches) {
var index = s.indexOf(matches[1]);
this._log('Use imperative present tense, eg. "Fix bug" not ' +
'"Fixed bug" or "Fixes bug". To get it right ask yourself: "If applied, ' +
'this patch will <YOUR-COMMIT-MESSAGE-HERE>"',
cfg.imperativeVerbsInSubject.type, [1, index+1+this._colOffset]);
hasError = true;
return false; // stop loop
}
return true;
} | [
"function",
"(",
"verb",
")",
"{",
"var",
"matches",
"=",
"verb",
".",
"value",
".",
"match",
"(",
"/",
"^VB[^P\\s]+ (\\S+)$",
"/",
")",
";",
"if",
"(",
"matches",
")",
"{",
"var",
"index",
"=",
"s",
".",
"indexOf",
"(",
"matches",
"[",
"1",
"]",
")",
";",
"this",
".",
"_log",
"(",
"'Use imperative present tense, eg. \"Fix bug\" not '",
"+",
"'\"Fixed bug\" or \"Fixes bug\". To get it right ask yourself: \"If applied, '",
"+",
"'this patch will <YOUR-COMMIT-MESSAGE-HERE>\"'",
",",
"cfg",
".",
"imperativeVerbsInSubject",
".",
"type",
",",
"[",
"1",
",",
"index",
"+",
"1",
"+",
"this",
".",
"_colOffset",
"]",
")",
";",
"hasError",
"=",
"true",
";",
"return",
"false",
";",
"// stop loop",
"}",
"return",
"true",
";",
"}"
]
| If the commit message is not a fragment and contains at least 1 verb, continue | [
"If",
"the",
"commit",
"message",
"is",
"not",
"a",
"fragment",
"and",
"contains",
"at",
"least",
"1",
"verb",
"continue"
]
| 53108eca78f627e770d0d885e4ae0b4ddf87f141 | https://github.com/clns/node-commit-msg/blob/53108eca78f627e770d0d885e4ae0b4ddf87f141/lib/commit-message.js#L357-L371 |
|
41,135 | luckylooke/dragon | example/example.js | animate | function animate( dragon, itemElm, destElm, duration ) {
duration = duration || 2;
let getOffset = dragon.space.utils.getOffset
let itemOffset = getOffset( itemElm, true )
let destOffset = getOffset( destElm, true )
let startX = itemOffset.left + ( itemOffset.width / 2 )
let startY = itemOffset.top + ( itemOffset.height / 2 )
let destX = destOffset.left + ( destOffset.width / 2 )
let destY = destOffset.top + ( destOffset.height / 2 )
let distanceX = destX - startX
let distanceY = destY - startY
let steps = duration * 60
let i = 0
animationRunning = true;
let drag = dragon.grab( itemElm )
drag.start( itemOffset.width / 2, itemOffset.height / 2 )
let cb = () => {
drag.release();
animationRunning = false;
}
step( 16 )
function step( time ) {
// console.log( 'step', drag.x, drag.y );
if ( i < steps ) {
setTimeout( () => {
let ease = easeInOutQuadDiff( i++ / steps, i-- / steps )
let ease2 = easeInOutQuartDiff( i++ / steps, i / steps )
// console.log( 'step', distanceX * ease, distanceY * ease2 )
drag.drag( drag.x + distanceX * ease, drag.y + distanceY * ease2 )
step( time )
}, time )
return
}
else
drag.drag( destX, destY )
if ( cb )
setTimeout( cb, 500 )
}
} | javascript | function animate( dragon, itemElm, destElm, duration ) {
duration = duration || 2;
let getOffset = dragon.space.utils.getOffset
let itemOffset = getOffset( itemElm, true )
let destOffset = getOffset( destElm, true )
let startX = itemOffset.left + ( itemOffset.width / 2 )
let startY = itemOffset.top + ( itemOffset.height / 2 )
let destX = destOffset.left + ( destOffset.width / 2 )
let destY = destOffset.top + ( destOffset.height / 2 )
let distanceX = destX - startX
let distanceY = destY - startY
let steps = duration * 60
let i = 0
animationRunning = true;
let drag = dragon.grab( itemElm )
drag.start( itemOffset.width / 2, itemOffset.height / 2 )
let cb = () => {
drag.release();
animationRunning = false;
}
step( 16 )
function step( time ) {
// console.log( 'step', drag.x, drag.y );
if ( i < steps ) {
setTimeout( () => {
let ease = easeInOutQuadDiff( i++ / steps, i-- / steps )
let ease2 = easeInOutQuartDiff( i++ / steps, i / steps )
// console.log( 'step', distanceX * ease, distanceY * ease2 )
drag.drag( drag.x + distanceX * ease, drag.y + distanceY * ease2 )
step( time )
}, time )
return
}
else
drag.drag( destX, destY )
if ( cb )
setTimeout( cb, 500 )
}
} | [
"function",
"animate",
"(",
"dragon",
",",
"itemElm",
",",
"destElm",
",",
"duration",
")",
"{",
"duration",
"=",
"duration",
"||",
"2",
";",
"let",
"getOffset",
"=",
"dragon",
".",
"space",
".",
"utils",
".",
"getOffset",
"let",
"itemOffset",
"=",
"getOffset",
"(",
"itemElm",
",",
"true",
")",
"let",
"destOffset",
"=",
"getOffset",
"(",
"destElm",
",",
"true",
")",
"let",
"startX",
"=",
"itemOffset",
".",
"left",
"+",
"(",
"itemOffset",
".",
"width",
"/",
"2",
")",
"let",
"startY",
"=",
"itemOffset",
".",
"top",
"+",
"(",
"itemOffset",
".",
"height",
"/",
"2",
")",
"let",
"destX",
"=",
"destOffset",
".",
"left",
"+",
"(",
"destOffset",
".",
"width",
"/",
"2",
")",
"let",
"destY",
"=",
"destOffset",
".",
"top",
"+",
"(",
"destOffset",
".",
"height",
"/",
"2",
")",
"let",
"distanceX",
"=",
"destX",
"-",
"startX",
"let",
"distanceY",
"=",
"destY",
"-",
"startY",
"let",
"steps",
"=",
"duration",
"*",
"60",
"let",
"i",
"=",
"0",
"animationRunning",
"=",
"true",
";",
"let",
"drag",
"=",
"dragon",
".",
"grab",
"(",
"itemElm",
")",
"drag",
".",
"start",
"(",
"itemOffset",
".",
"width",
"/",
"2",
",",
"itemOffset",
".",
"height",
"/",
"2",
")",
"let",
"cb",
"=",
"(",
")",
"=>",
"{",
"drag",
".",
"release",
"(",
")",
";",
"animationRunning",
"=",
"false",
";",
"}",
"step",
"(",
"16",
")",
"function",
"step",
"(",
"time",
")",
"{",
"// console.log( 'step', drag.x, drag.y );",
"if",
"(",
"i",
"<",
"steps",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"let",
"ease",
"=",
"easeInOutQuadDiff",
"(",
"i",
"++",
"/",
"steps",
",",
"i",
"--",
"/",
"steps",
")",
"let",
"ease2",
"=",
"easeInOutQuartDiff",
"(",
"i",
"++",
"/",
"steps",
",",
"i",
"/",
"steps",
")",
"// console.log( 'step', distanceX * ease, distanceY * ease2 )",
"drag",
".",
"drag",
"(",
"drag",
".",
"x",
"+",
"distanceX",
"*",
"ease",
",",
"drag",
".",
"y",
"+",
"distanceY",
"*",
"ease2",
")",
"step",
"(",
"time",
")",
"}",
",",
"time",
")",
"return",
"}",
"else",
"drag",
".",
"drag",
"(",
"destX",
",",
"destY",
")",
"if",
"(",
"cb",
")",
"setTimeout",
"(",
"cb",
",",
"500",
")",
"}",
"}"
]
| duration in seconds! | [
"duration",
"in",
"seconds!"
]
| bb0c285967db04061fc75105aaa7ef62d2bd9d74 | https://github.com/luckylooke/dragon/blob/bb0c285967db04061fc75105aaa7ef62d2bd9d74/example/example.js#L32-L85 |
41,136 | auduno/mosse | build/mosse.module.js | fft | function fft(re, im, inv) {
var d, h, ik, m, tmp, wr, wi, xr, xi,
n4 = _n >> 2;
// bit reversal
for(var l=0; l<_n; l++) {
m = _bitrev[l];
if(l < m) {
tmp = re[l];
re[l] = re[m];
re[m] = tmp;
tmp = im[l];
im[l] = im[m];
im[m] = tmp;
}
}
// butterfly operation
for(var k=1; k<_n; k<<=1) {
h = 0;
d = _n/(k << 1);
for(var j=0; j<k; j++) {
wr = _cstb[h + n4];
wi = inv*_cstb[h];
for(var i=j; i<_n; i+=(k<<1)) {
ik = i + k;
xr = wr*re[ik] + wi*im[ik];
xi = wr*im[ik] - wi*re[ik];
re[ik] = re[i] - xr;
re[i] += xr;
im[ik] = im[i] - xi;
im[i] += xi;
}
h += d;
}
}
} | javascript | function fft(re, im, inv) {
var d, h, ik, m, tmp, wr, wi, xr, xi,
n4 = _n >> 2;
// bit reversal
for(var l=0; l<_n; l++) {
m = _bitrev[l];
if(l < m) {
tmp = re[l];
re[l] = re[m];
re[m] = tmp;
tmp = im[l];
im[l] = im[m];
im[m] = tmp;
}
}
// butterfly operation
for(var k=1; k<_n; k<<=1) {
h = 0;
d = _n/(k << 1);
for(var j=0; j<k; j++) {
wr = _cstb[h + n4];
wi = inv*_cstb[h];
for(var i=j; i<_n; i+=(k<<1)) {
ik = i + k;
xr = wr*re[ik] + wi*im[ik];
xi = wr*im[ik] - wi*re[ik];
re[ik] = re[i] - xr;
re[i] += xr;
im[ik] = im[i] - xi;
im[i] += xi;
}
h += d;
}
}
} | [
"function",
"fft",
"(",
"re",
",",
"im",
",",
"inv",
")",
"{",
"var",
"d",
",",
"h",
",",
"ik",
",",
"m",
",",
"tmp",
",",
"wr",
",",
"wi",
",",
"xr",
",",
"xi",
",",
"n4",
"=",
"_n",
">>",
"2",
";",
"// bit reversal",
"for",
"(",
"var",
"l",
"=",
"0",
";",
"l",
"<",
"_n",
";",
"l",
"++",
")",
"{",
"m",
"=",
"_bitrev",
"[",
"l",
"]",
";",
"if",
"(",
"l",
"<",
"m",
")",
"{",
"tmp",
"=",
"re",
"[",
"l",
"]",
";",
"re",
"[",
"l",
"]",
"=",
"re",
"[",
"m",
"]",
";",
"re",
"[",
"m",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"im",
"[",
"l",
"]",
";",
"im",
"[",
"l",
"]",
"=",
"im",
"[",
"m",
"]",
";",
"im",
"[",
"m",
"]",
"=",
"tmp",
";",
"}",
"}",
"// butterfly operation",
"for",
"(",
"var",
"k",
"=",
"1",
";",
"k",
"<",
"_n",
";",
"k",
"<<=",
"1",
")",
"{",
"h",
"=",
"0",
";",
"d",
"=",
"_n",
"/",
"(",
"k",
"<<",
"1",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"k",
";",
"j",
"++",
")",
"{",
"wr",
"=",
"_cstb",
"[",
"h",
"+",
"n4",
"]",
";",
"wi",
"=",
"inv",
"*",
"_cstb",
"[",
"h",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"j",
";",
"i",
"<",
"_n",
";",
"i",
"+=",
"(",
"k",
"<<",
"1",
")",
")",
"{",
"ik",
"=",
"i",
"+",
"k",
";",
"xr",
"=",
"wr",
"*",
"re",
"[",
"ik",
"]",
"+",
"wi",
"*",
"im",
"[",
"ik",
"]",
";",
"xi",
"=",
"wr",
"*",
"im",
"[",
"ik",
"]",
"-",
"wi",
"*",
"re",
"[",
"ik",
"]",
";",
"re",
"[",
"ik",
"]",
"=",
"re",
"[",
"i",
"]",
"-",
"xr",
";",
"re",
"[",
"i",
"]",
"+=",
"xr",
";",
"im",
"[",
"ik",
"]",
"=",
"im",
"[",
"i",
"]",
"-",
"xi",
";",
"im",
"[",
"i",
"]",
"+=",
"xi",
";",
"}",
"h",
"+=",
"d",
";",
"}",
"}",
"}"
]
| core operation of FFT | [
"core",
"operation",
"of",
"FFT"
]
| 30b430aa091b271a884aae4211875777292304b2 | https://github.com/auduno/mosse/blob/30b430aa091b271a884aae4211875777292304b2/build/mosse.module.js#L107-L141 |
41,137 | auduno/mosse | build/mosse.module.js | _makeBitReversal | function _makeBitReversal() {
var i = 0,
j = 0,
k = 0;
_bitrev[0] = 0;
while(++i < _n) {
k = _n >> 1;
while(k <= j) {
j -= k;
k >>= 1;
}
j += k;
_bitrev[i] = j;
}
} | javascript | function _makeBitReversal() {
var i = 0,
j = 0,
k = 0;
_bitrev[0] = 0;
while(++i < _n) {
k = _n >> 1;
while(k <= j) {
j -= k;
k >>= 1;
}
j += k;
_bitrev[i] = j;
}
} | [
"function",
"_makeBitReversal",
"(",
")",
"{",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"0",
",",
"k",
"=",
"0",
";",
"_bitrev",
"[",
"0",
"]",
"=",
"0",
";",
"while",
"(",
"++",
"i",
"<",
"_n",
")",
"{",
"k",
"=",
"_n",
">>",
"1",
";",
"while",
"(",
"k",
"<=",
"j",
")",
"{",
"j",
"-=",
"k",
";",
"k",
">>=",
"1",
";",
"}",
"j",
"+=",
"k",
";",
"_bitrev",
"[",
"i",
"]",
"=",
"j",
";",
"}",
"}"
]
| make bit reversal table | [
"make",
"bit",
"reversal",
"table"
]
| 30b430aa091b271a884aae4211875777292304b2 | https://github.com/auduno/mosse/blob/30b430aa091b271a884aae4211875777292304b2/build/mosse.module.js#L162-L176 |
41,138 | auduno/mosse | build/mosse.module.js | _makeCosSinTable | function _makeCosSinTable() {
var n2 = _n >> 1,
n4 = _n >> 2,
n8 = _n >> 3,
n2p4 = n2 + n4,
t = Math.sin(Math.PI/_n),
dc = 2*t*t,
ds = Math.sqrt(dc*(2 - dc)),
c = _cstb[n4] = 1,
s = _cstb[0] = 0;
t = 2*dc;
for(var i=1; i<n8; i++) {
c -= dc;
dc += t*c;
s += ds;
ds -= t*s;
_cstb[i] = s;
_cstb[n4 - i] = c;
}
if(n8 !== 0) {
_cstb[n8] = Math.sqrt(0.5);
}
for(var j=0; j<n4; j++) {
_cstb[n2 - j] = _cstb[j];
}
for(var k=0; k<n2p4; k++) {
_cstb[k + n2] = -_cstb[k];
}
} | javascript | function _makeCosSinTable() {
var n2 = _n >> 1,
n4 = _n >> 2,
n8 = _n >> 3,
n2p4 = n2 + n4,
t = Math.sin(Math.PI/_n),
dc = 2*t*t,
ds = Math.sqrt(dc*(2 - dc)),
c = _cstb[n4] = 1,
s = _cstb[0] = 0;
t = 2*dc;
for(var i=1; i<n8; i++) {
c -= dc;
dc += t*c;
s += ds;
ds -= t*s;
_cstb[i] = s;
_cstb[n4 - i] = c;
}
if(n8 !== 0) {
_cstb[n8] = Math.sqrt(0.5);
}
for(var j=0; j<n4; j++) {
_cstb[n2 - j] = _cstb[j];
}
for(var k=0; k<n2p4; k++) {
_cstb[k + n2] = -_cstb[k];
}
} | [
"function",
"_makeCosSinTable",
"(",
")",
"{",
"var",
"n2",
"=",
"_n",
">>",
"1",
",",
"n4",
"=",
"_n",
">>",
"2",
",",
"n8",
"=",
"_n",
">>",
"3",
",",
"n2p4",
"=",
"n2",
"+",
"n4",
",",
"t",
"=",
"Math",
".",
"sin",
"(",
"Math",
".",
"PI",
"/",
"_n",
")",
",",
"dc",
"=",
"2",
"*",
"t",
"*",
"t",
",",
"ds",
"=",
"Math",
".",
"sqrt",
"(",
"dc",
"*",
"(",
"2",
"-",
"dc",
")",
")",
",",
"c",
"=",
"_cstb",
"[",
"n4",
"]",
"=",
"1",
",",
"s",
"=",
"_cstb",
"[",
"0",
"]",
"=",
"0",
";",
"t",
"=",
"2",
"*",
"dc",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"n8",
";",
"i",
"++",
")",
"{",
"c",
"-=",
"dc",
";",
"dc",
"+=",
"t",
"*",
"c",
";",
"s",
"+=",
"ds",
";",
"ds",
"-=",
"t",
"*",
"s",
";",
"_cstb",
"[",
"i",
"]",
"=",
"s",
";",
"_cstb",
"[",
"n4",
"-",
"i",
"]",
"=",
"c",
";",
"}",
"if",
"(",
"n8",
"!==",
"0",
")",
"{",
"_cstb",
"[",
"n8",
"]",
"=",
"Math",
".",
"sqrt",
"(",
"0.5",
")",
";",
"}",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"n4",
";",
"j",
"++",
")",
"{",
"_cstb",
"[",
"n2",
"-",
"j",
"]",
"=",
"_cstb",
"[",
"j",
"]",
";",
"}",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"n2p4",
";",
"k",
"++",
")",
"{",
"_cstb",
"[",
"k",
"+",
"n2",
"]",
"=",
"-",
"_cstb",
"[",
"k",
"]",
";",
"}",
"}"
]
| make trigonometric function table | [
"make",
"trigonometric",
"function",
"table"
]
| 30b430aa091b271a884aae4211875777292304b2 | https://github.com/auduno/mosse/blob/30b430aa091b271a884aae4211875777292304b2/build/mosse.module.js#L179-L207 |
41,139 | tjanczuk/wns | lib/wns.js | function (name, imageCount, textCount) {
// contains placeholder for optional binding attributes
// contains placeholder for each text and image payload
var template = '<binding template="' + name + '"%s>';
for (var i = 0; i < imageCount; i++)
template += '<image id="' + (i + 1) + '" src="%s" alt="%s"/>';
for (var i = 0; i < textCount; i++)
template += '<text id="' + (i + 1) + '">%s</text>';
template += '</binding>';
return template;
} | javascript | function (name, imageCount, textCount) {
// contains placeholder for optional binding attributes
// contains placeholder for each text and image payload
var template = '<binding template="' + name + '"%s>';
for (var i = 0; i < imageCount; i++)
template += '<image id="' + (i + 1) + '" src="%s" alt="%s"/>';
for (var i = 0; i < textCount; i++)
template += '<text id="' + (i + 1) + '">%s</text>';
template += '</binding>';
return template;
} | [
"function",
"(",
"name",
",",
"imageCount",
",",
"textCount",
")",
"{",
"// contains placeholder for optional binding attributes",
"// contains placeholder for each text and image payload",
"var",
"template",
"=",
"'<binding template=\"'",
"+",
"name",
"+",
"'\"%s>'",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"imageCount",
";",
"i",
"++",
")",
"template",
"+=",
"'<image id=\"'",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'\" src=\"%s\" alt=\"%s\"/>'",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"textCount",
";",
"i",
"++",
")",
"template",
"+=",
"'<text id=\"'",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'\">%s</text>'",
";",
"template",
"+=",
"'</binding>'",
";",
"return",
"template",
";",
"}"
]
| creates a toast or tile binding template given the name and a specific number of text and image elements | [
"creates",
"a",
"toast",
"or",
"tile",
"binding",
"template",
"given",
"the",
"name",
"and",
"a",
"specific",
"number",
"of",
"text",
"and",
"image",
"elements"
]
| bc5228c5337941b9309d041231dbac9e85673491 | https://github.com/tjanczuk/wns/blob/bc5228c5337941b9309d041231dbac9e85673491/lib/wns.js#L116-L127 |
|
41,140 | yoshuawuyts/markdown-to-medium | bin/cli.js | usage | function usage (exitCode) {
const rs = fs.createReadStream(path.join(__dirname, '/usage.txt'))
const ws = process.stdout
rs.pipe(ws)
ws.on('finish', process.exit.bind(null, exitCode))
} | javascript | function usage (exitCode) {
const rs = fs.createReadStream(path.join(__dirname, '/usage.txt'))
const ws = process.stdout
rs.pipe(ws)
ws.on('finish', process.exit.bind(null, exitCode))
} | [
"function",
"usage",
"(",
"exitCode",
")",
"{",
"const",
"rs",
"=",
"fs",
".",
"createReadStream",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'/usage.txt'",
")",
")",
"const",
"ws",
"=",
"process",
".",
"stdout",
"rs",
".",
"pipe",
"(",
"ws",
")",
"ws",
".",
"on",
"(",
"'finish'",
",",
"process",
".",
"exit",
".",
"bind",
"(",
"null",
",",
"exitCode",
")",
")",
"}"
]
| print usage & exit num? -> null | [
"print",
"usage",
"&",
"exit",
"num?",
"-",
">",
"null"
]
| f03123b8e6a40ee164a6c10748c1155d3adc1848 | https://github.com/yoshuawuyts/markdown-to-medium/blob/f03123b8e6a40ee164a6c10748c1155d3adc1848/bin/cli.js#L59-L64 |
41,141 | talyssonoc/jsT9 | dist/jst9.js | predict | function predict(word, amount) {
if (!word) {
return [];
}
amount = amount || this.config.maxAmount;
var currentWord = false;
var initialBranchResult = this._findInitialBranch(word);
if(!initialBranchResult) {
return [];
}
if (initialBranchResult.currentBranch.$ === true) {
currentWord = initialBranchResult.baseWord;
}
var predictedList = this._exploreBranch(initialBranchResult.baseWord, initialBranchResult.currentBranch);
if (currentWord) {
predictedList.push(currentWord);
}
predictedList.sort(this.config.sort);
return predictedList.slice(0, amount);
} | javascript | function predict(word, amount) {
if (!word) {
return [];
}
amount = amount || this.config.maxAmount;
var currentWord = false;
var initialBranchResult = this._findInitialBranch(word);
if(!initialBranchResult) {
return [];
}
if (initialBranchResult.currentBranch.$ === true) {
currentWord = initialBranchResult.baseWord;
}
var predictedList = this._exploreBranch(initialBranchResult.baseWord, initialBranchResult.currentBranch);
if (currentWord) {
predictedList.push(currentWord);
}
predictedList.sort(this.config.sort);
return predictedList.slice(0, amount);
} | [
"function",
"predict",
"(",
"word",
",",
"amount",
")",
"{",
"if",
"(",
"!",
"word",
")",
"{",
"return",
"[",
"]",
";",
"}",
"amount",
"=",
"amount",
"||",
"this",
".",
"config",
".",
"maxAmount",
";",
"var",
"currentWord",
"=",
"false",
";",
"var",
"initialBranchResult",
"=",
"this",
".",
"_findInitialBranch",
"(",
"word",
")",
";",
"if",
"(",
"!",
"initialBranchResult",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"initialBranchResult",
".",
"currentBranch",
".",
"$",
"===",
"true",
")",
"{",
"currentWord",
"=",
"initialBranchResult",
".",
"baseWord",
";",
"}",
"var",
"predictedList",
"=",
"this",
".",
"_exploreBranch",
"(",
"initialBranchResult",
".",
"baseWord",
",",
"initialBranchResult",
".",
"currentBranch",
")",
";",
"if",
"(",
"currentWord",
")",
"{",
"predictedList",
".",
"push",
"(",
"currentWord",
")",
";",
"}",
"predictedList",
".",
"sort",
"(",
"this",
".",
"config",
".",
"sort",
")",
";",
"return",
"predictedList",
".",
"slice",
"(",
"0",
",",
"amount",
")",
";",
"}"
]
| Predict the words, given the initial word
@param {String} word The initial word
@return {Array} The array of Strings with the predicted words | [
"Predict",
"the",
"words",
"given",
"the",
"initial",
"word"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L92-L121 |
41,142 | talyssonoc/jsT9 | dist/jst9.js | addWord | function addWord(word) {
var branch = this.root;
var stopSearchOnCurrentBranch = false;
var newNode;
while (!stopSearchOnCurrentBranch) {
var wordContainsThePrefix = false;
var isCase3 = false;
var case2Result;
//Looks for how branch it should follow
for (var b in branch.branches) {
//Case 1: current node prefix == `word`
if(this._tryCase1(branch, word, b)) {
return;
}
//Case 2: `word` begins with current node prefix to add
//Cuts the word and goes to the next branch
case2Result = this._tryCase2(branch, word, b);
if(case2Result) {
word = case2Result.word;
branch = case2Result.branch;
wordContainsThePrefix = true;
break;
}
//Case 3: current node prefix begins with part of or whole `word`
if(this._tryCase3(branch, word, b)) {
isCase3 = stopSearchOnCurrentBranch = wordContainsThePrefix = true;
break;
}
}
//Case 4: current node prefix doesn't have intersection with `word`
if(this._tryCase4(branch, word, wordContainsThePrefix)) {
stopSearchOnCurrentBranch = true;
}
}
} | javascript | function addWord(word) {
var branch = this.root;
var stopSearchOnCurrentBranch = false;
var newNode;
while (!stopSearchOnCurrentBranch) {
var wordContainsThePrefix = false;
var isCase3 = false;
var case2Result;
//Looks for how branch it should follow
for (var b in branch.branches) {
//Case 1: current node prefix == `word`
if(this._tryCase1(branch, word, b)) {
return;
}
//Case 2: `word` begins with current node prefix to add
//Cuts the word and goes to the next branch
case2Result = this._tryCase2(branch, word, b);
if(case2Result) {
word = case2Result.word;
branch = case2Result.branch;
wordContainsThePrefix = true;
break;
}
//Case 3: current node prefix begins with part of or whole `word`
if(this._tryCase3(branch, word, b)) {
isCase3 = stopSearchOnCurrentBranch = wordContainsThePrefix = true;
break;
}
}
//Case 4: current node prefix doesn't have intersection with `word`
if(this._tryCase4(branch, word, wordContainsThePrefix)) {
stopSearchOnCurrentBranch = true;
}
}
} | [
"function",
"addWord",
"(",
"word",
")",
"{",
"var",
"branch",
"=",
"this",
".",
"root",
";",
"var",
"stopSearchOnCurrentBranch",
"=",
"false",
";",
"var",
"newNode",
";",
"while",
"(",
"!",
"stopSearchOnCurrentBranch",
")",
"{",
"var",
"wordContainsThePrefix",
"=",
"false",
";",
"var",
"isCase3",
"=",
"false",
";",
"var",
"case2Result",
";",
"//Looks for how branch it should follow",
"for",
"(",
"var",
"b",
"in",
"branch",
".",
"branches",
")",
"{",
"//Case 1: current node prefix == `word`",
"if",
"(",
"this",
".",
"_tryCase1",
"(",
"branch",
",",
"word",
",",
"b",
")",
")",
"{",
"return",
";",
"}",
"//Case 2: `word` begins with current node prefix to add",
"//Cuts the word and goes to the next branch",
"case2Result",
"=",
"this",
".",
"_tryCase2",
"(",
"branch",
",",
"word",
",",
"b",
")",
";",
"if",
"(",
"case2Result",
")",
"{",
"word",
"=",
"case2Result",
".",
"word",
";",
"branch",
"=",
"case2Result",
".",
"branch",
";",
"wordContainsThePrefix",
"=",
"true",
";",
"break",
";",
"}",
"//Case 3: current node prefix begins with part of or whole `word`",
"if",
"(",
"this",
".",
"_tryCase3",
"(",
"branch",
",",
"word",
",",
"b",
")",
")",
"{",
"isCase3",
"=",
"stopSearchOnCurrentBranch",
"=",
"wordContainsThePrefix",
"=",
"true",
";",
"break",
";",
"}",
"}",
"//Case 4: current node prefix doesn't have intersection with `word`",
"if",
"(",
"this",
".",
"_tryCase4",
"(",
"branch",
",",
"word",
",",
"wordContainsThePrefix",
")",
")",
"{",
"stopSearchOnCurrentBranch",
"=",
"true",
";",
"}",
"}",
"}"
]
| Add a new word to the tree
@param {String} word Word to be added to the tree | [
"Add",
"a",
"new",
"word",
"to",
"the",
"tree"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L227-L268 |
41,143 | talyssonoc/jsT9 | dist/jst9.js | _exploreBranch | function _exploreBranch(baseWord, currentBranch) {
var predictedList = [];
for (var b in currentBranch.branches) { //For each branch forking from the branch
var prefix = currentBranch.branches[b].prefix; //Get the leading character of the current branch
if (currentBranch.branches[b].$ === true) { //If the current leaf ends a word, puts the word on the list
predictedList.push(baseWord + prefix);
}
//Recursively calls the function, passing the forking branches as parameter
var predictedWords = this._exploreBranch(baseWord + prefix, currentBranch.branches[b]);
predictedList = predictedList.concat(predictedWords);
}
return predictedList;
} | javascript | function _exploreBranch(baseWord, currentBranch) {
var predictedList = [];
for (var b in currentBranch.branches) { //For each branch forking from the branch
var prefix = currentBranch.branches[b].prefix; //Get the leading character of the current branch
if (currentBranch.branches[b].$ === true) { //If the current leaf ends a word, puts the word on the list
predictedList.push(baseWord + prefix);
}
//Recursively calls the function, passing the forking branches as parameter
var predictedWords = this._exploreBranch(baseWord + prefix, currentBranch.branches[b]);
predictedList = predictedList.concat(predictedWords);
}
return predictedList;
} | [
"function",
"_exploreBranch",
"(",
"baseWord",
",",
"currentBranch",
")",
"{",
"var",
"predictedList",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"b",
"in",
"currentBranch",
".",
"branches",
")",
"{",
"//For each branch forking from the branch",
"var",
"prefix",
"=",
"currentBranch",
".",
"branches",
"[",
"b",
"]",
".",
"prefix",
";",
"//Get the leading character of the current branch",
"if",
"(",
"currentBranch",
".",
"branches",
"[",
"b",
"]",
".",
"$",
"===",
"true",
")",
"{",
"//If the current leaf ends a word, puts the word on the list",
"predictedList",
".",
"push",
"(",
"baseWord",
"+",
"prefix",
")",
";",
"}",
"//Recursively calls the function, passing the forking branches as parameter",
"var",
"predictedWords",
"=",
"this",
".",
"_exploreBranch",
"(",
"baseWord",
"+",
"prefix",
",",
"currentBranch",
".",
"branches",
"[",
"b",
"]",
")",
";",
"predictedList",
"=",
"predictedList",
".",
"concat",
"(",
"predictedWords",
")",
";",
"}",
"return",
"predictedList",
";",
"}"
]
| Looks for the words that contain the word passed as parameter
@param {String} baseWord The base to look for
@param {Object} currentBranch The begining branch
@return {Array} List of predicted words | [
"Looks",
"for",
"the",
"words",
"that",
"contain",
"the",
"word",
"passed",
"as",
"parameter"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L362-L379 |
41,144 | talyssonoc/jsT9 | dist/jst9.js | _getWordList | function _getWordList(_wordList, callback) {
if(Array.isArray(_wordList)) {
callback(_wordList);
} else if ((typeof _wordList) === 'string') {
this._fetchWordList(_wordList, callback);
} else {
console.error((typeof _wordList) + ' variable is not supported as data source');
callback([]);
}
} | javascript | function _getWordList(_wordList, callback) {
if(Array.isArray(_wordList)) {
callback(_wordList);
} else if ((typeof _wordList) === 'string') {
this._fetchWordList(_wordList, callback);
} else {
console.error((typeof _wordList) + ' variable is not supported as data source');
callback([]);
}
} | [
"function",
"_getWordList",
"(",
"_wordList",
",",
"callback",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"_wordList",
")",
")",
"{",
"callback",
"(",
"_wordList",
")",
";",
"}",
"else",
"if",
"(",
"(",
"typeof",
"_wordList",
")",
"===",
"'string'",
")",
"{",
"this",
".",
"_fetchWordList",
"(",
"_wordList",
",",
"callback",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"(",
"typeof",
"_wordList",
")",
"+",
"' variable is not supported as data source'",
")",
";",
"callback",
"(",
"[",
"]",
")",
";",
"}",
"}"
]
| Returns the word list base on config
@param {Array|String}
@param {Function}
@return {Array} | [
"Returns",
"the",
"word",
"list",
"base",
"on",
"config"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L387-L402 |
41,145 | talyssonoc/jsT9 | dist/jst9.js | _fetchWordList | function _fetchWordList(path, callback) {
var words = [];
axios.get(path)
.then(function(response) {
var jsonData = response.data;
if(response.responseType === 'text') {
jsonData = JSON.parse(jsonData);
}
if(Array.isArray(jsonData.words)) {
words = jsonData.words;
}
callback(words);
}.bind(this))
.catch(function(error) {
callback(words);
}.bind(this));
} | javascript | function _fetchWordList(path, callback) {
var words = [];
axios.get(path)
.then(function(response) {
var jsonData = response.data;
if(response.responseType === 'text') {
jsonData = JSON.parse(jsonData);
}
if(Array.isArray(jsonData.words)) {
words = jsonData.words;
}
callback(words);
}.bind(this))
.catch(function(error) {
callback(words);
}.bind(this));
} | [
"function",
"_fetchWordList",
"(",
"path",
",",
"callback",
")",
"{",
"var",
"words",
"=",
"[",
"]",
";",
"axios",
".",
"get",
"(",
"path",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"var",
"jsonData",
"=",
"response",
".",
"data",
";",
"if",
"(",
"response",
".",
"responseType",
"===",
"'text'",
")",
"{",
"jsonData",
"=",
"JSON",
".",
"parse",
"(",
"jsonData",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"jsonData",
".",
"words",
")",
")",
"{",
"words",
"=",
"jsonData",
".",
"words",
";",
"}",
"callback",
"(",
"words",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"words",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Fetches the word list from an address
@param {String} path Path of a JSON file with an array called 'words' with the word list
@return {Array} Word list extracted from the given path | [
"Fetches",
"the",
"word",
"list",
"from",
"an",
"address"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L409-L430 |
41,146 | yoshuawuyts/markdown-to-medium | index.js | main | function main (options, done) {
const token = options.token
const filename = options.filename
assert.equal(typeof token, 'string', 'markdown-to-medium: token should be a string')
const client = new medium.MediumClient({
clientId: token,
clientSecret: token
})
client.setAccessToken(token)
var src
try {
src = fs.readFileSync(filename, 'utf8')
} catch (e) {
throw new Error('Could not read file ' + filename)
}
const matter = frontMatter(src)
let title = options.title || matter.attributes.title
const tags = (options.tags && options.tags.split(',')) || matter.attributes.tags
const publication = options.publication || matter.attributes.publication
const canonicalUrl = options.canonicalUrl || matter.attributes.canonicalUrl || ''
const license = checkLicense(options.license || matter.attributes.license)
var content = `
# ${title}
${matter.body}
`
if (!title && getTitle(src)) {
title = getTitle(src).text
content = matter.body
}
if (canonicalUrl.length) {
content += `
*Cross-posted from [${canonicalUrl}](${canonicalUrl}).*
`
}
client.getUser((err, user) => {
if (err) {
throw new Error(err)
}
console.log(`Authenticated as ${user.username}`.blue)
const options = {
userId: user.id,
title,
tags,
content,
canonicalUrl,
license,
contentFormat: 'markdown',
publishStatus: 'draft'
}
const successMsg = `Draft post "${title}" published to Medium.com`.green
if (publication) {
client.getPublicationsForUser({userId: user.id}, (err, publications) => {
if (err) {
throw new Error(err)
}
const myPub = publications.filter((val) => { return val.name === publication })
if (myPub.length === 0) {
throw new Error('No publication by that name!')
}
client.createPostInPublication(Object.assign(options, {publicationId: myPub[0].id}), (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
})
} else {
client.createPost(options, (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
}
})
} | javascript | function main (options, done) {
const token = options.token
const filename = options.filename
assert.equal(typeof token, 'string', 'markdown-to-medium: token should be a string')
const client = new medium.MediumClient({
clientId: token,
clientSecret: token
})
client.setAccessToken(token)
var src
try {
src = fs.readFileSync(filename, 'utf8')
} catch (e) {
throw new Error('Could not read file ' + filename)
}
const matter = frontMatter(src)
let title = options.title || matter.attributes.title
const tags = (options.tags && options.tags.split(',')) || matter.attributes.tags
const publication = options.publication || matter.attributes.publication
const canonicalUrl = options.canonicalUrl || matter.attributes.canonicalUrl || ''
const license = checkLicense(options.license || matter.attributes.license)
var content = `
# ${title}
${matter.body}
`
if (!title && getTitle(src)) {
title = getTitle(src).text
content = matter.body
}
if (canonicalUrl.length) {
content += `
*Cross-posted from [${canonicalUrl}](${canonicalUrl}).*
`
}
client.getUser((err, user) => {
if (err) {
throw new Error(err)
}
console.log(`Authenticated as ${user.username}`.blue)
const options = {
userId: user.id,
title,
tags,
content,
canonicalUrl,
license,
contentFormat: 'markdown',
publishStatus: 'draft'
}
const successMsg = `Draft post "${title}" published to Medium.com`.green
if (publication) {
client.getPublicationsForUser({userId: user.id}, (err, publications) => {
if (err) {
throw new Error(err)
}
const myPub = publications.filter((val) => { return val.name === publication })
if (myPub.length === 0) {
throw new Error('No publication by that name!')
}
client.createPostInPublication(Object.assign(options, {publicationId: myPub[0].id}), (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
})
} else {
client.createPost(options, (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
}
})
} | [
"function",
"main",
"(",
"options",
",",
"done",
")",
"{",
"const",
"token",
"=",
"options",
".",
"token",
"const",
"filename",
"=",
"options",
".",
"filename",
"assert",
".",
"equal",
"(",
"typeof",
"token",
",",
"'string'",
",",
"'markdown-to-medium: token should be a string'",
")",
"const",
"client",
"=",
"new",
"medium",
".",
"MediumClient",
"(",
"{",
"clientId",
":",
"token",
",",
"clientSecret",
":",
"token",
"}",
")",
"client",
".",
"setAccessToken",
"(",
"token",
")",
"var",
"src",
"try",
"{",
"src",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
",",
"'utf8'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Could not read file '",
"+",
"filename",
")",
"}",
"const",
"matter",
"=",
"frontMatter",
"(",
"src",
")",
"let",
"title",
"=",
"options",
".",
"title",
"||",
"matter",
".",
"attributes",
".",
"title",
"const",
"tags",
"=",
"(",
"options",
".",
"tags",
"&&",
"options",
".",
"tags",
".",
"split",
"(",
"','",
")",
")",
"||",
"matter",
".",
"attributes",
".",
"tags",
"const",
"publication",
"=",
"options",
".",
"publication",
"||",
"matter",
".",
"attributes",
".",
"publication",
"const",
"canonicalUrl",
"=",
"options",
".",
"canonicalUrl",
"||",
"matter",
".",
"attributes",
".",
"canonicalUrl",
"||",
"''",
"const",
"license",
"=",
"checkLicense",
"(",
"options",
".",
"license",
"||",
"matter",
".",
"attributes",
".",
"license",
")",
"var",
"content",
"=",
"`",
"${",
"title",
"}",
"${",
"matter",
".",
"body",
"}",
"`",
"if",
"(",
"!",
"title",
"&&",
"getTitle",
"(",
"src",
")",
")",
"{",
"title",
"=",
"getTitle",
"(",
"src",
")",
".",
"text",
"content",
"=",
"matter",
".",
"body",
"}",
"if",
"(",
"canonicalUrl",
".",
"length",
")",
"{",
"content",
"+=",
"`",
"${",
"canonicalUrl",
"}",
"${",
"canonicalUrl",
"}",
"`",
"}",
"client",
".",
"getUser",
"(",
"(",
"err",
",",
"user",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"`",
"${",
"user",
".",
"username",
"}",
"`",
".",
"blue",
")",
"const",
"options",
"=",
"{",
"userId",
":",
"user",
".",
"id",
",",
"title",
",",
"tags",
",",
"content",
",",
"canonicalUrl",
",",
"license",
",",
"contentFormat",
":",
"'markdown'",
",",
"publishStatus",
":",
"'draft'",
"}",
"const",
"successMsg",
"=",
"`",
"${",
"title",
"}",
"`",
".",
"green",
"if",
"(",
"publication",
")",
"{",
"client",
".",
"getPublicationsForUser",
"(",
"{",
"userId",
":",
"user",
".",
"id",
"}",
",",
"(",
"err",
",",
"publications",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"const",
"myPub",
"=",
"publications",
".",
"filter",
"(",
"(",
"val",
")",
"=>",
"{",
"return",
"val",
".",
"name",
"===",
"publication",
"}",
")",
"if",
"(",
"myPub",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No publication by that name!'",
")",
"}",
"client",
".",
"createPostInPublication",
"(",
"Object",
".",
"assign",
"(",
"options",
",",
"{",
"publicationId",
":",
"myPub",
"[",
"0",
"]",
".",
"id",
"}",
")",
",",
"(",
"err",
",",
"post",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"successMsg",
")",
"open",
"(",
"post",
".",
"url",
")",
"}",
")",
"}",
")",
"}",
"else",
"{",
"client",
".",
"createPost",
"(",
"options",
",",
"(",
"err",
",",
"post",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"successMsg",
")",
"open",
"(",
"post",
".",
"url",
")",
"}",
")",
"}",
"}",
")",
"}"
]
| publish a markdown file to medium | [
"publish",
"a",
"markdown",
"file",
"to",
"medium"
]
| f03123b8e6a40ee164a6c10748c1155d3adc1848 | https://github.com/yoshuawuyts/markdown-to-medium/blob/f03123b8e6a40ee164a6c10748c1155d3adc1848/index.js#L40-L133 |
41,147 | meeDamian/country-emoji | src/lib.js | flag | function flag(input) {
if (!CODE_RE.test(input) || input === 'UK') {
input = nameToCode(input);
}
return codeToFlag(input);
} | javascript | function flag(input) {
if (!CODE_RE.test(input) || input === 'UK') {
input = nameToCode(input);
}
return codeToFlag(input);
} | [
"function",
"flag",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"CODE_RE",
".",
"test",
"(",
"input",
")",
"||",
"input",
"===",
"'UK'",
")",
"{",
"input",
"=",
"nameToCode",
"(",
"input",
")",
";",
"}",
"return",
"codeToFlag",
"(",
"input",
")",
";",
"}"
]
| Takes either code or full name | [
"Takes",
"either",
"code",
"or",
"full",
"name"
]
| 6e2c490c2c038882280ee17866ec689c05af3544 | https://github.com/meeDamian/country-emoji/blob/6e2c490c2c038882280ee17866ec689c05af3544/src/lib.js#L133-L139 |
41,148 | meeDamian/country-emoji | src/lib.js | name | function name(input) {
if (FLAG_RE.test(input)) {
input = flagToCode(input);
}
return codeToName(input);
} | javascript | function name(input) {
if (FLAG_RE.test(input)) {
input = flagToCode(input);
}
return codeToName(input);
} | [
"function",
"name",
"(",
"input",
")",
"{",
"if",
"(",
"FLAG_RE",
".",
"test",
"(",
"input",
")",
")",
"{",
"input",
"=",
"flagToCode",
"(",
"input",
")",
";",
"}",
"return",
"codeToName",
"(",
"input",
")",
";",
"}"
]
| Takes either emoji or code | [
"Takes",
"either",
"emoji",
"or",
"code"
]
| 6e2c490c2c038882280ee17866ec689c05af3544 | https://github.com/meeDamian/country-emoji/blob/6e2c490c2c038882280ee17866ec689c05af3544/src/lib.js#L142-L148 |
41,149 | mweststrate/nscript | lib/index.js | runScriptFile | function runScriptFile(scriptFile) {
//node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away!
scriptArgs = scriptArgs.slice(scriptArgs.indexOf(scriptFile) + 1);
if (shell.verbose())
console.warn("Starting nscript " + scriptFile + scriptArgs.join(" "));
runNscriptFunction(require(path.resolve(process.cwd(), scriptFile))); //nscript scripts should always export a single function that is the main
} | javascript | function runScriptFile(scriptFile) {
//node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away!
scriptArgs = scriptArgs.slice(scriptArgs.indexOf(scriptFile) + 1);
if (shell.verbose())
console.warn("Starting nscript " + scriptFile + scriptArgs.join(" "));
runNscriptFunction(require(path.resolve(process.cwd(), scriptFile))); //nscript scripts should always export a single function that is the main
} | [
"function",
"runScriptFile",
"(",
"scriptFile",
")",
"{",
"//node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away!",
"scriptArgs",
"=",
"scriptArgs",
".",
"slice",
"(",
"scriptArgs",
".",
"indexOf",
"(",
"scriptFile",
")",
"+",
"1",
")",
";",
"if",
"(",
"shell",
".",
"verbose",
"(",
")",
")",
"console",
".",
"warn",
"(",
"\"Starting nscript \"",
"+",
"scriptFile",
"+",
"scriptArgs",
".",
"join",
"(",
"\" \"",
")",
")",
";",
"runNscriptFunction",
"(",
"require",
"(",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"scriptFile",
")",
")",
")",
";",
"//nscript scripts should always export a single function that is the main",
"}"
]
| Runs a file that contains a nscript script
@param {string} scriptFile | [
"Runs",
"a",
"file",
"that",
"contains",
"a",
"nscript",
"script"
]
| 0a02d17bb3ab00d2d5830151ab20771f0366baba | https://github.com/mweststrate/nscript/blob/0a02d17bb3ab00d2d5830151ab20771f0366baba/lib/index.js#L147-L154 |
41,150 | julienetie/mimetic | src/initialize-mimetic-partial.js | initializeMimeticPartial | function initializeMimeticPartial(
document,
getRootREMValue,
// CSSUnitsToPixels,
setRootFontSize,
resizilla,
) {
// A resize object to store MIMETIC's resizilla's requirements.
const resize = {};
/**
* The intializeMimetic function.
* @param {object} config - The API parameters.
*/
function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
}
/**
* Remove both event listeners set via resizilla.
*/
initalizeMimeticFinal.prototype.kill = () => resize.resizilla.destroy();
/**
* Re-instate resizilla.
*/
initalizeMimeticFinal.prototype.revive = function revive() {
resize.resizilla = resizilla(() => {
setRootFontSize(resize.settings, resize.setRootFontSizeScope);
}, resize.scaleDelay, false);
};
return initalizeMimeticFinal;
} | javascript | function initializeMimeticPartial(
document,
getRootREMValue,
// CSSUnitsToPixels,
setRootFontSize,
resizilla,
) {
// A resize object to store MIMETIC's resizilla's requirements.
const resize = {};
/**
* The intializeMimetic function.
* @param {object} config - The API parameters.
*/
function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
}
/**
* Remove both event listeners set via resizilla.
*/
initalizeMimeticFinal.prototype.kill = () => resize.resizilla.destroy();
/**
* Re-instate resizilla.
*/
initalizeMimeticFinal.prototype.revive = function revive() {
resize.resizilla = resizilla(() => {
setRootFontSize(resize.settings, resize.setRootFontSizeScope);
}, resize.scaleDelay, false);
};
return initalizeMimeticFinal;
} | [
"function",
"initializeMimeticPartial",
"(",
"document",
",",
"getRootREMValue",
",",
"// CSSUnitsToPixels,",
"setRootFontSize",
",",
"resizilla",
",",
")",
"{",
"// A resize object to store MIMETIC's resizilla's requirements.",
"const",
"resize",
"=",
"{",
"}",
";",
"/**\n * The intializeMimetic function.\n * @param {object} config - The API parameters.\n */",
"function",
"initalizeMimeticFinal",
"(",
"config",
")",
"{",
"// Destructured API parameters.",
"const",
"{",
"scaleDelay",
",",
"}",
"=",
"config",
";",
"// Store the scaleDelay for kill and revive.",
"resize",
".",
"scaleDelay",
"=",
"scaleDelay",
";",
"// The intial root font size.",
"const",
"rootFontSize",
"=",
"getRootREMValue",
"(",
"document",
")",
";",
"// // mobileWidth in pixels.",
"// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);",
"// Cut off width in pixels.",
"// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);",
"// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.",
"const",
"settings",
"=",
"Object",
".",
"assign",
"(",
"{",
"initialOuterHeight",
":",
"window",
".",
"outerHeight",
",",
"initialOuterWidth",
":",
"window",
".",
"outerWidth",
",",
"rootFontSize",
",",
"// mobileWidthPX,",
"// cutOffWidthPX,",
"}",
",",
"config",
")",
";",
"// Store the settings for kill and revive.",
"resize",
".",
"settings",
"=",
"settings",
";",
"// Immediately set the root font size according to MIMETIC.",
"const",
"setRootFontSizeScope",
"=",
"(",
")",
"=>",
"setRootFontSize",
"(",
"settings",
")",
";",
"resize",
".",
"setRootFontSizeScope",
"=",
"setRootFontSizeScope",
";",
"setRootFontSizeScope",
"(",
")",
";",
"// On window resize set the root font size according to MIMETIC.",
"resize",
".",
"resizilla",
"=",
"resizilla",
"(",
"(",
")",
"=>",
"{",
"setRootFontSize",
"(",
"settings",
",",
"setRootFontSizeScope",
")",
";",
"}",
",",
"scaleDelay",
",",
"false",
")",
";",
"}",
"/**\n * Remove both event listeners set via resizilla.\n */",
"initalizeMimeticFinal",
".",
"prototype",
".",
"kill",
"=",
"(",
")",
"=>",
"resize",
".",
"resizilla",
".",
"destroy",
"(",
")",
";",
"/**\n * Re-instate resizilla.\n */",
"initalizeMimeticFinal",
".",
"prototype",
".",
"revive",
"=",
"function",
"revive",
"(",
")",
"{",
"resize",
".",
"resizilla",
"=",
"resizilla",
"(",
"(",
")",
"=>",
"{",
"setRootFontSize",
"(",
"resize",
".",
"settings",
",",
"resize",
".",
"setRootFontSizeScope",
")",
";",
"}",
",",
"resize",
".",
"scaleDelay",
",",
"false",
")",
";",
"}",
";",
"return",
"initalizeMimeticFinal",
";",
"}"
]
| Sets up intializeMimetic via partial application.
@param {Function} document.
@param {Function} getRootREMValue - Gets the root font-size in REM units.
@param {Function} CSSUnitsToPixels - Converts any CSS units to pixels.
@param {Function} setRootFontSize - Sets the new root font size.
@param {Function} resizilla - Calls handler on window resize and orientationchange events. | [
"Sets",
"up",
"intializeMimetic",
"via",
"partial",
"application",
"."
]
| fc4c794e8b5063aa0d9f5145c59a797adca0d984 | https://github.com/julienetie/mimetic/blob/fc4c794e8b5063aa0d9f5145c59a797adca0d984/src/initialize-mimetic-partial.js#L9-L90 |
41,151 | julienetie/mimetic | src/initialize-mimetic-partial.js | initalizeMimeticFinal | function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
} | javascript | function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
} | [
"function",
"initalizeMimeticFinal",
"(",
"config",
")",
"{",
"// Destructured API parameters.",
"const",
"{",
"scaleDelay",
",",
"}",
"=",
"config",
";",
"// Store the scaleDelay for kill and revive.",
"resize",
".",
"scaleDelay",
"=",
"scaleDelay",
";",
"// The intial root font size.",
"const",
"rootFontSize",
"=",
"getRootREMValue",
"(",
"document",
")",
";",
"// // mobileWidth in pixels.",
"// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);",
"// Cut off width in pixels.",
"// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);",
"// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.",
"const",
"settings",
"=",
"Object",
".",
"assign",
"(",
"{",
"initialOuterHeight",
":",
"window",
".",
"outerHeight",
",",
"initialOuterWidth",
":",
"window",
".",
"outerWidth",
",",
"rootFontSize",
",",
"// mobileWidthPX,",
"// cutOffWidthPX,",
"}",
",",
"config",
")",
";",
"// Store the settings for kill and revive.",
"resize",
".",
"settings",
"=",
"settings",
";",
"// Immediately set the root font size according to MIMETIC.",
"const",
"setRootFontSizeScope",
"=",
"(",
")",
"=>",
"setRootFontSize",
"(",
"settings",
")",
";",
"resize",
".",
"setRootFontSizeScope",
"=",
"setRootFontSizeScope",
";",
"setRootFontSizeScope",
"(",
")",
";",
"// On window resize set the root font size according to MIMETIC.",
"resize",
".",
"resizilla",
"=",
"resizilla",
"(",
"(",
")",
"=>",
"{",
"setRootFontSize",
"(",
"settings",
",",
"setRootFontSizeScope",
")",
";",
"}",
",",
"scaleDelay",
",",
"false",
")",
";",
"}"
]
| The intializeMimetic function.
@param {object} config - The API parameters. | [
"The",
"intializeMimetic",
"function",
"."
]
| fc4c794e8b5063aa0d9f5145c59a797adca0d984 | https://github.com/julienetie/mimetic/blob/fc4c794e8b5063aa0d9f5145c59a797adca0d984/src/initialize-mimetic-partial.js#L24-L71 |
41,152 | capaj/socket.io-rpc | main.js | RPCserver | function RPCserver () {
var server
if (typeof arguments[0] === 'number') {
server = require('http').createServer()
server.listen.apply(server, arguments)
} else {
server = arguments[0]
}
var io = socketIO(server, arguments[1])
var rpcServer = {
io: io.of('/rpc'),
/**
* @param toExtendWith {Object}
*/
expose: function (toExtendWith) {
if (typeof toExtendWith !== 'object') {
throw new TypeError('object expected as first argument')
}
Object.extend(tree, toExtendWith)
},
server: server
}
var tree = {}
rpcServer.io.on('connect', function (socket) {
socketEventHandlers(socket, tree, 'server')
})
return rpcServer
} | javascript | function RPCserver () {
var server
if (typeof arguments[0] === 'number') {
server = require('http').createServer()
server.listen.apply(server, arguments)
} else {
server = arguments[0]
}
var io = socketIO(server, arguments[1])
var rpcServer = {
io: io.of('/rpc'),
/**
* @param toExtendWith {Object}
*/
expose: function (toExtendWith) {
if (typeof toExtendWith !== 'object') {
throw new TypeError('object expected as first argument')
}
Object.extend(tree, toExtendWith)
},
server: server
}
var tree = {}
rpcServer.io.on('connect', function (socket) {
socketEventHandlers(socket, tree, 'server')
})
return rpcServer
} | [
"function",
"RPCserver",
"(",
")",
"{",
"var",
"server",
"if",
"(",
"typeof",
"arguments",
"[",
"0",
"]",
"===",
"'number'",
")",
"{",
"server",
"=",
"require",
"(",
"'http'",
")",
".",
"createServer",
"(",
")",
"server",
".",
"listen",
".",
"apply",
"(",
"server",
",",
"arguments",
")",
"}",
"else",
"{",
"server",
"=",
"arguments",
"[",
"0",
"]",
"}",
"var",
"io",
"=",
"socketIO",
"(",
"server",
",",
"arguments",
"[",
"1",
"]",
")",
"var",
"rpcServer",
"=",
"{",
"io",
":",
"io",
".",
"of",
"(",
"'/rpc'",
")",
",",
"/**\n * @param toExtendWith {Object}\n */",
"expose",
":",
"function",
"(",
"toExtendWith",
")",
"{",
"if",
"(",
"typeof",
"toExtendWith",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'object expected as first argument'",
")",
"}",
"Object",
".",
"extend",
"(",
"tree",
",",
"toExtendWith",
")",
"}",
",",
"server",
":",
"server",
"}",
"var",
"tree",
"=",
"{",
"}",
"rpcServer",
".",
"io",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
"socket",
")",
"{",
"socketEventHandlers",
"(",
"socket",
",",
"tree",
",",
"'server'",
")",
"}",
")",
"return",
"rpcServer",
"}"
]
| Shares the same signature as express.js listen method, because it passes arguments to it when first argument is number
@param {Number|Object} port or http server
@param {String} [hostname]
@param {Function} [Callback]
@returns {{expose: Function, loadClientChannel: Function, channel: Object}} rpc backend instance | [
"Shares",
"the",
"same",
"signature",
"as",
"express",
".",
"js",
"listen",
"method",
"because",
"it",
"passes",
"arguments",
"to",
"it",
"when",
"first",
"argument",
"is",
"number"
]
| 1474b50beb2b8d8ed5b5c09f87b971bf0e00f874 | https://github.com/capaj/socket.io-rpc/blob/1474b50beb2b8d8ed5b5c09f87b971bf0e00f874/main.js#L12-L42 |
41,153 | basarevych/dynamic-table | node/adapter/array.js | checkFilter | function checkFilter(filter, type, test, real) {
if (type == Table.TYPE_DATETIME) {
if (typeof real != 'object')
real = new Date(real * 1000);
if (filter == Table.FILTER_BETWEEN
&& Array.isArray(test) && test.length == 2) {
test = [
test[0] ? moment.unix(test[0]) : null,
test[1] ? moment.unix(test[1]) : null,
];
} else if (filter != Table.FILTER_BETWEEN) {
test = moment.unix(test);
} else {
return null;
}
} else {
if (filter == Table.FILTER_BETWEEN) {
if (!Array.isArray(test) || test.length != 2)
return null;
}
}
switch (filter) {
case Table.FILTER_LIKE:
return real !== null && real.indexOf(test) != -1;
case Table.FILTER_EQUAL:
return real !== null && test == real;
case Table.FILTER_BETWEEN:
if (real === null)
return false;
if (test[0] !== null && real < test[0])
return false;
if (test[1] !== null && real > test[1])
return false;
return true;
case Table.FILTER_NULL:
return real === null;
default:
throw new Error("Unknown filter: " + filter);
}
return false;
} | javascript | function checkFilter(filter, type, test, real) {
if (type == Table.TYPE_DATETIME) {
if (typeof real != 'object')
real = new Date(real * 1000);
if (filter == Table.FILTER_BETWEEN
&& Array.isArray(test) && test.length == 2) {
test = [
test[0] ? moment.unix(test[0]) : null,
test[1] ? moment.unix(test[1]) : null,
];
} else if (filter != Table.FILTER_BETWEEN) {
test = moment.unix(test);
} else {
return null;
}
} else {
if (filter == Table.FILTER_BETWEEN) {
if (!Array.isArray(test) || test.length != 2)
return null;
}
}
switch (filter) {
case Table.FILTER_LIKE:
return real !== null && real.indexOf(test) != -1;
case Table.FILTER_EQUAL:
return real !== null && test == real;
case Table.FILTER_BETWEEN:
if (real === null)
return false;
if (test[0] !== null && real < test[0])
return false;
if (test[1] !== null && real > test[1])
return false;
return true;
case Table.FILTER_NULL:
return real === null;
default:
throw new Error("Unknown filter: " + filter);
}
return false;
} | [
"function",
"checkFilter",
"(",
"filter",
",",
"type",
",",
"test",
",",
"real",
")",
"{",
"if",
"(",
"type",
"==",
"Table",
".",
"TYPE_DATETIME",
")",
"{",
"if",
"(",
"typeof",
"real",
"!=",
"'object'",
")",
"real",
"=",
"new",
"Date",
"(",
"real",
"*",
"1000",
")",
";",
"if",
"(",
"filter",
"==",
"Table",
".",
"FILTER_BETWEEN",
"&&",
"Array",
".",
"isArray",
"(",
"test",
")",
"&&",
"test",
".",
"length",
"==",
"2",
")",
"{",
"test",
"=",
"[",
"test",
"[",
"0",
"]",
"?",
"moment",
".",
"unix",
"(",
"test",
"[",
"0",
"]",
")",
":",
"null",
",",
"test",
"[",
"1",
"]",
"?",
"moment",
".",
"unix",
"(",
"test",
"[",
"1",
"]",
")",
":",
"null",
",",
"]",
";",
"}",
"else",
"if",
"(",
"filter",
"!=",
"Table",
".",
"FILTER_BETWEEN",
")",
"{",
"test",
"=",
"moment",
".",
"unix",
"(",
"test",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"filter",
"==",
"Table",
".",
"FILTER_BETWEEN",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"test",
")",
"||",
"test",
".",
"length",
"!=",
"2",
")",
"return",
"null",
";",
"}",
"}",
"switch",
"(",
"filter",
")",
"{",
"case",
"Table",
".",
"FILTER_LIKE",
":",
"return",
"real",
"!==",
"null",
"&&",
"real",
".",
"indexOf",
"(",
"test",
")",
"!=",
"-",
"1",
";",
"case",
"Table",
".",
"FILTER_EQUAL",
":",
"return",
"real",
"!==",
"null",
"&&",
"test",
"==",
"real",
";",
"case",
"Table",
".",
"FILTER_BETWEEN",
":",
"if",
"(",
"real",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"test",
"[",
"0",
"]",
"!==",
"null",
"&&",
"real",
"<",
"test",
"[",
"0",
"]",
")",
"return",
"false",
";",
"if",
"(",
"test",
"[",
"1",
"]",
"!==",
"null",
"&&",
"real",
">",
"test",
"[",
"1",
"]",
")",
"return",
"false",
";",
"return",
"true",
";",
"case",
"Table",
".",
"FILTER_NULL",
":",
"return",
"real",
"===",
"null",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Unknown filter: \"",
"+",
"filter",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Check and apply filter
@param {string} filter
@param {string} type
@param {*} test
@param {*} real | [
"Check",
"and",
"apply",
"filter"
]
| 227eafab0d4dafabe0d2ceaa881ab3befe994d9c | https://github.com/basarevych/dynamic-table/blob/227eafab0d4dafabe0d2ceaa881ab3befe994d9c/node/adapter/array.js#L239-L281 |
41,154 | hareko/js-merge-xml | example.js | function(evt, id, fnc) {
var elem = $(id);
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evt, fnc, false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent('on' + evt, fnc);
}
else { // No much to do
elem[evt] = fnc;
}
} | javascript | function(evt, id, fnc) {
var elem = $(id);
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evt, fnc, false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent('on' + evt, fnc);
}
else { // No much to do
elem[evt] = fnc;
}
} | [
"function",
"(",
"evt",
",",
"id",
",",
"fnc",
")",
"{",
"var",
"elem",
"=",
"$",
"(",
"id",
")",
";",
"if",
"(",
"elem",
".",
"addEventListener",
")",
"// W3C DOM",
"elem",
".",
"addEventListener",
"(",
"evt",
",",
"fnc",
",",
"false",
")",
";",
"else",
"if",
"(",
"elem",
".",
"attachEvent",
")",
"{",
"// IE DOM",
"elem",
".",
"attachEvent",
"(",
"'on'",
"+",
"evt",
",",
"fnc",
")",
";",
"}",
"else",
"{",
"// No much to do",
"elem",
"[",
"evt",
"]",
"=",
"fnc",
";",
"}",
"}"
]
| add event handler
@param {string} evt
@param {string} id
@param {function} fnc | [
"add",
"event",
"handler"
]
| 65d42764daeac152bda5a4a389a9ba108e4d26cd | https://github.com/hareko/js-merge-xml/blob/65d42764daeac152bda5a4a389a9ba108e4d26cd/example.js#L28-L38 |
|
41,155 | hareko/js-merge-xml | example.js | function(evt) {
$('output').innerHTML = '';
$('result').innerHTML = '';
oMX.Init(); /* begin with new objects */
fls = [];
var cnt = 0;
var files = evt.target.files; /* FileList object */
for (var i = 0; i < files.length; i++) { /* loop the selected files */
var reader = new FileReader();
reader.onload = function(file) {
fls[cnt + 1] = oMX.AddFile(file) ? true : false; /* get a file */
var c = $('result').innerHTML;
if (c !== '') {
c += ', ';
}
$('result').innerHTML = c + fls[cnt];
cnt += 2;
};
fls.push(files[i].name, null);
reader.readAsText(files[i]);
}
} | javascript | function(evt) {
$('output').innerHTML = '';
$('result').innerHTML = '';
oMX.Init(); /* begin with new objects */
fls = [];
var cnt = 0;
var files = evt.target.files; /* FileList object */
for (var i = 0; i < files.length; i++) { /* loop the selected files */
var reader = new FileReader();
reader.onload = function(file) {
fls[cnt + 1] = oMX.AddFile(file) ? true : false; /* get a file */
var c = $('result').innerHTML;
if (c !== '') {
c += ', ';
}
$('result').innerHTML = c + fls[cnt];
cnt += 2;
};
fls.push(files[i].name, null);
reader.readAsText(files[i]);
}
} | [
"function",
"(",
"evt",
")",
"{",
"$",
"(",
"'output'",
")",
".",
"innerHTML",
"=",
"''",
";",
"$",
"(",
"'result'",
")",
".",
"innerHTML",
"=",
"''",
";",
"oMX",
".",
"Init",
"(",
")",
";",
"/* begin with new objects */",
"fls",
"=",
"[",
"]",
";",
"var",
"cnt",
"=",
"0",
";",
"var",
"files",
"=",
"evt",
".",
"target",
".",
"files",
";",
"/* FileList object */",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"/* loop the selected files */",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onload",
"=",
"function",
"(",
"file",
")",
"{",
"fls",
"[",
"cnt",
"+",
"1",
"]",
"=",
"oMX",
".",
"AddFile",
"(",
"file",
")",
"?",
"true",
":",
"false",
";",
"/* get a file */",
"var",
"c",
"=",
"$",
"(",
"'result'",
")",
".",
"innerHTML",
";",
"if",
"(",
"c",
"!==",
"''",
")",
"{",
"c",
"+=",
"', '",
";",
"}",
"$",
"(",
"'result'",
")",
".",
"innerHTML",
"=",
"c",
"+",
"fls",
"[",
"cnt",
"]",
";",
"cnt",
"+=",
"2",
";",
"}",
";",
"fls",
".",
"push",
"(",
"files",
"[",
"i",
"]",
".",
"name",
",",
"null",
")",
";",
"reader",
".",
"readAsText",
"(",
"files",
"[",
"i",
"]",
")",
";",
"}",
"}"
]
| FileList objects handler
@param {object} evt | [
"FileList",
"objects",
"handler"
]
| 65d42764daeac152bda5a4a389a9ba108e4d26cd | https://github.com/hareko/js-merge-xml/blob/65d42764daeac152bda5a4a389a9ba108e4d26cd/example.js#L44-L65 |
|
41,156 | ryanhornberger/nunjucks-html-loader | index.js | function(searchPaths, sourceFoundCallback) {
this.sourceFoundCallback = sourceFoundCallback;
if(searchPaths) {
searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
// For windows, convert to forward slashes
this.searchPaths = searchPaths.map(path.normalize);
}
else {
this.searchPaths = ['.'];
}
} | javascript | function(searchPaths, sourceFoundCallback) {
this.sourceFoundCallback = sourceFoundCallback;
if(searchPaths) {
searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
// For windows, convert to forward slashes
this.searchPaths = searchPaths.map(path.normalize);
}
else {
this.searchPaths = ['.'];
}
} | [
"function",
"(",
"searchPaths",
",",
"sourceFoundCallback",
")",
"{",
"this",
".",
"sourceFoundCallback",
"=",
"sourceFoundCallback",
";",
"if",
"(",
"searchPaths",
")",
"{",
"searchPaths",
"=",
"Array",
".",
"isArray",
"(",
"searchPaths",
")",
"?",
"searchPaths",
":",
"[",
"searchPaths",
"]",
";",
"// For windows, convert to forward slashes",
"this",
".",
"searchPaths",
"=",
"searchPaths",
".",
"map",
"(",
"path",
".",
"normalize",
")",
";",
"}",
"else",
"{",
"this",
".",
"searchPaths",
"=",
"[",
"'.'",
"]",
";",
"}",
"}"
]
| Based off of the Nunjucks 'FileSystemLoader' | [
"Based",
"off",
"of",
"the",
"Nunjucks",
"FileSystemLoader"
]
| df04de862aa86c6d590fa93174a0fa58eaaf06a0 | https://github.com/ryanhornberger/nunjucks-html-loader/blob/df04de862aa86c6d590fa93174a0fa58eaaf06a0/index.js#L9-L19 |
|
41,157 | jasontbradshaw/tailing-stream | tailing-stream.js | function (preserveExistingProperties) {
var result = undefined;
for (var i = 1; i < arguments.length; i++) {
obj = arguments[i];
// set initial result object to the first argument given
if (!result) {
result = obj;
continue;
}
for (prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// preserve preexisting child properties if specified
if (preserveExistingProperties &&
Object.prototype.hasOwnProperty.call(result, prop)) {
continue;
}
result[prop] = obj[prop];
}
}
}
return result;
} | javascript | function (preserveExistingProperties) {
var result = undefined;
for (var i = 1; i < arguments.length; i++) {
obj = arguments[i];
// set initial result object to the first argument given
if (!result) {
result = obj;
continue;
}
for (prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// preserve preexisting child properties if specified
if (preserveExistingProperties &&
Object.prototype.hasOwnProperty.call(result, prop)) {
continue;
}
result[prop] = obj[prop];
}
}
}
return result;
} | [
"function",
"(",
"preserveExistingProperties",
")",
"{",
"var",
"result",
"=",
"undefined",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"obj",
"=",
"arguments",
"[",
"i",
"]",
";",
"// set initial result object to the first argument given",
"if",
"(",
"!",
"result",
")",
"{",
"result",
"=",
"obj",
";",
"continue",
";",
"}",
"for",
"(",
"prop",
"in",
"obj",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"obj",
",",
"prop",
")",
")",
"{",
"// preserve preexisting child properties if specified",
"if",
"(",
"preserveExistingProperties",
"&&",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"result",
",",
"prop",
")",
")",
"{",
"continue",
";",
"}",
"result",
"[",
"prop",
"]",
"=",
"obj",
"[",
"prop",
"]",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
]
| copy properties from right-most args to left-most | [
"copy",
"properties",
"from",
"right",
"-",
"most",
"args",
"to",
"left",
"-",
"most"
]
| c4f30353718efb86d6539ce5a142dfa9cf72c27b | https://github.com/jasontbradshaw/tailing-stream/blob/c4f30353718efb86d6539ce5a142dfa9cf72c27b/tailing-stream.js#L5-L29 |
|
41,158 | liamcurry/gql | packages/gql-merge/dist/index.js | mergeAst | function mergeAst(schemaAst) {
var typeDefs = {};
// Go through the AST and extract/merge type definitions.
var editedAst = (0, _language.visit)(schemaAst, {
enter: function enter(node) {
var nodeName = node.name ? node.name.value : null;
// Don't transform TypeDefinitions directly
if (!nodeName || !node.kind.endsWith('TypeDefinition')) {
return;
}
var oldNode = typeDefs[nodeName];
if (!oldNode) {
// First time seeing this type so just store the value.
typeDefs[nodeName] = node;
return null;
}
// This type is defined multiple times, so merge the fields and values.
var concatProps = ['fields', 'values', 'types'];
concatProps.forEach(function (propName) {
if (node[propName] && oldNode[propName]) {
node[propName] = oldNode[propName].concat(node[propName]);
}
});
typeDefs[nodeName] = node;
return null;
}
});
var remainingNodesStr = (0, _gqlFormat.formatAst)(editedAst);
var typeDefsStr = (0, _values2.default)(typeDefs).map(_gqlFormat.formatAst).join('\n');
var fullSchemaStr = remainingNodesStr + '\n\n' + typeDefsStr;
return (0, _gqlFormat.formatString)(fullSchemaStr);
} | javascript | function mergeAst(schemaAst) {
var typeDefs = {};
// Go through the AST and extract/merge type definitions.
var editedAst = (0, _language.visit)(schemaAst, {
enter: function enter(node) {
var nodeName = node.name ? node.name.value : null;
// Don't transform TypeDefinitions directly
if (!nodeName || !node.kind.endsWith('TypeDefinition')) {
return;
}
var oldNode = typeDefs[nodeName];
if (!oldNode) {
// First time seeing this type so just store the value.
typeDefs[nodeName] = node;
return null;
}
// This type is defined multiple times, so merge the fields and values.
var concatProps = ['fields', 'values', 'types'];
concatProps.forEach(function (propName) {
if (node[propName] && oldNode[propName]) {
node[propName] = oldNode[propName].concat(node[propName]);
}
});
typeDefs[nodeName] = node;
return null;
}
});
var remainingNodesStr = (0, _gqlFormat.formatAst)(editedAst);
var typeDefsStr = (0, _values2.default)(typeDefs).map(_gqlFormat.formatAst).join('\n');
var fullSchemaStr = remainingNodesStr + '\n\n' + typeDefsStr;
return (0, _gqlFormat.formatString)(fullSchemaStr);
} | [
"function",
"mergeAst",
"(",
"schemaAst",
")",
"{",
"var",
"typeDefs",
"=",
"{",
"}",
";",
"// Go through the AST and extract/merge type definitions.",
"var",
"editedAst",
"=",
"(",
"0",
",",
"_language",
".",
"visit",
")",
"(",
"schemaAst",
",",
"{",
"enter",
":",
"function",
"enter",
"(",
"node",
")",
"{",
"var",
"nodeName",
"=",
"node",
".",
"name",
"?",
"node",
".",
"name",
".",
"value",
":",
"null",
";",
"// Don't transform TypeDefinitions directly",
"if",
"(",
"!",
"nodeName",
"||",
"!",
"node",
".",
"kind",
".",
"endsWith",
"(",
"'TypeDefinition'",
")",
")",
"{",
"return",
";",
"}",
"var",
"oldNode",
"=",
"typeDefs",
"[",
"nodeName",
"]",
";",
"if",
"(",
"!",
"oldNode",
")",
"{",
"// First time seeing this type so just store the value.",
"typeDefs",
"[",
"nodeName",
"]",
"=",
"node",
";",
"return",
"null",
";",
"}",
"// This type is defined multiple times, so merge the fields and values.",
"var",
"concatProps",
"=",
"[",
"'fields'",
",",
"'values'",
",",
"'types'",
"]",
";",
"concatProps",
".",
"forEach",
"(",
"function",
"(",
"propName",
")",
"{",
"if",
"(",
"node",
"[",
"propName",
"]",
"&&",
"oldNode",
"[",
"propName",
"]",
")",
"{",
"node",
"[",
"propName",
"]",
"=",
"oldNode",
"[",
"propName",
"]",
".",
"concat",
"(",
"node",
"[",
"propName",
"]",
")",
";",
"}",
"}",
")",
";",
"typeDefs",
"[",
"nodeName",
"]",
"=",
"node",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"var",
"remainingNodesStr",
"=",
"(",
"0",
",",
"_gqlFormat",
".",
"formatAst",
")",
"(",
"editedAst",
")",
";",
"var",
"typeDefsStr",
"=",
"(",
"0",
",",
"_values2",
".",
"default",
")",
"(",
"typeDefs",
")",
".",
"map",
"(",
"_gqlFormat",
".",
"formatAst",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"var",
"fullSchemaStr",
"=",
"remainingNodesStr",
"+",
"'\\n\\n'",
"+",
"typeDefsStr",
";",
"return",
"(",
"0",
",",
"_gqlFormat",
".",
"formatString",
")",
"(",
"fullSchemaStr",
")",
";",
"}"
]
| Merges duplicate definitions in a single GraphQL abstract-syntax tree
@param {Document} schemaAst - The GraphQL AST.
@return {string} The resulting merged GraphQL string. | [
"Merges",
"duplicate",
"definitions",
"in",
"a",
"single",
"GraphQL",
"abstract",
"-",
"syntax",
"tree"
]
| 0a28f69cc80084d648a95d1ea24a834d737235f6 | https://github.com/liamcurry/gql/blob/0a28f69cc80084d648a95d1ea24a834d737235f6/packages/gql-merge/dist/index.js#L272-L311 |
41,159 | gribnoysup/setup-polly-jest | src/setupJasmine.js | getRecordingName | function getRecordingName(spec, suite) {
const descriptions = [spec.description];
while (suite) {
suite.description && descriptions.push(suite.description);
suite = suite.parentSuite;
}
return descriptions.reverse().join('/');
} | javascript | function getRecordingName(spec, suite) {
const descriptions = [spec.description];
while (suite) {
suite.description && descriptions.push(suite.description);
suite = suite.parentSuite;
}
return descriptions.reverse().join('/');
} | [
"function",
"getRecordingName",
"(",
"spec",
",",
"suite",
")",
"{",
"const",
"descriptions",
"=",
"[",
"spec",
".",
"description",
"]",
";",
"while",
"(",
"suite",
")",
"{",
"suite",
".",
"description",
"&&",
"descriptions",
".",
"push",
"(",
"suite",
".",
"description",
")",
";",
"suite",
"=",
"suite",
".",
"parentSuite",
";",
"}",
"return",
"descriptions",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}"
]
| Get full spec description, starting from the top
suite
@param {Object} spec Current spec
@param {Object} suite Current spec parent suite
@returns {string} Full spec description (e.g. "suite/should do something") | [
"Get",
"full",
"spec",
"description",
"starting",
"from",
"the",
"top",
"suite"
]
| 8c0acedca7f84a788f80974460893605f335a946 | https://github.com/gribnoysup/setup-polly-jest/blob/8c0acedca7f84a788f80974460893605f335a946/src/setupJasmine.js#L29-L38 |
41,160 | gribnoysup/setup-polly-jest | src/setupJasmine.js | findSuiteRec | function findSuiteRec(suite, findFn) {
if (findFn(suite)) return suite;
for (const child of suite.children || []) {
const result = findSuiteRec(child, findFn);
if (result !== null) {
return result;
}
}
return null;
} | javascript | function findSuiteRec(suite, findFn) {
if (findFn(suite)) return suite;
for (const child of suite.children || []) {
const result = findSuiteRec(child, findFn);
if (result !== null) {
return result;
}
}
return null;
} | [
"function",
"findSuiteRec",
"(",
"suite",
",",
"findFn",
")",
"{",
"if",
"(",
"findFn",
"(",
"suite",
")",
")",
"return",
"suite",
";",
"for",
"(",
"const",
"child",
"of",
"suite",
".",
"children",
"||",
"[",
"]",
")",
"{",
"const",
"result",
"=",
"findSuiteRec",
"(",
"child",
",",
"findFn",
")",
";",
"if",
"(",
"result",
"!==",
"null",
")",
"{",
"return",
"result",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Recursively go through suite and its children
and return the first that matches the findFn
condition
@param {Object} suite Starting point
@param {Function} findFn Find function
@returns {?Object} Matching suite or null | [
"Recursively",
"go",
"through",
"suite",
"and",
"its",
"children",
"and",
"return",
"the",
"first",
"that",
"matches",
"the",
"findFn",
"condition"
]
| 8c0acedca7f84a788f80974460893605f335a946 | https://github.com/gribnoysup/setup-polly-jest/blob/8c0acedca7f84a788f80974460893605f335a946/src/setupJasmine.js#L50-L62 |
41,161 | fex-team/fis3-hook-amd | amd.js | strSplice | function strSplice(str, index, count, add) {
return str.slice(0, index) + add + str.slice(index + count);
} | javascript | function strSplice(str, index, count, add) {
return str.slice(0, index) + add + str.slice(index + count);
} | [
"function",
"strSplice",
"(",
"str",
",",
"index",
",",
"count",
",",
"add",
")",
"{",
"return",
"str",
".",
"slice",
"(",
"0",
",",
"index",
")",
"+",
"add",
"+",
"str",
".",
"slice",
"(",
"index",
"+",
"count",
")",
";",
"}"
]
| like array.splice | [
"like",
"array",
".",
"splice"
]
| 2edda3eab5e14a8720f36255cecefe813404e5e9 | https://github.com/fex-team/fis3-hook-amd/blob/2edda3eab5e14a8720f36255cecefe813404e5e9/amd.js#L818-L820 |
41,162 | liamcurry/gql | packages/gql-format/dist/index.js | SchemaDefinition | function SchemaDefinition(_ref24) {
var directives = _ref24.directives,
operationTypes = _ref24.operationTypes;
return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
} | javascript | function SchemaDefinition(_ref24) {
var directives = _ref24.directives,
operationTypes = _ref24.operationTypes;
return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
} | [
"function",
"SchemaDefinition",
"(",
"_ref24",
")",
"{",
"var",
"directives",
"=",
"_ref24",
".",
"directives",
",",
"operationTypes",
"=",
"_ref24",
".",
"operationTypes",
";",
"return",
"join",
"(",
"[",
"'schema'",
",",
"join",
"(",
"directives",
",",
"' '",
")",
",",
"block",
"(",
"operationTypes",
")",
"]",
",",
"' '",
")",
";",
"}"
]
| Type System Definitions | [
"Type",
"System",
"Definitions"
]
| 0a28f69cc80084d648a95d1ea24a834d737235f6 | https://github.com/liamcurry/gql/blob/0a28f69cc80084d648a95d1ea24a834d737235f6/packages/gql-format/dist/index.js#L438-L442 |
41,163 | liamcurry/gql | packages/gql-format/dist/index.js | join | function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
} | javascript | function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
} | [
"function",
"join",
"(",
"maybeArray",
",",
"separator",
")",
"{",
"return",
"maybeArray",
"?",
"maybeArray",
".",
"filter",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"x",
";",
"}",
")",
".",
"join",
"(",
"separator",
"||",
"''",
")",
":",
"''",
";",
"}"
]
| Given maybeArray, print an empty string if it is null or empty, otherwise
print all items together separated by separator if provided | [
"Given",
"maybeArray",
"print",
"an",
"empty",
"string",
"if",
"it",
"is",
"null",
"or",
"empty",
"otherwise",
"print",
"all",
"items",
"together",
"separated",
"by",
"separator",
"if",
"provided"
]
| 0a28f69cc80084d648a95d1ea24a834d737235f6 | https://github.com/liamcurry/gql/blob/0a28f69cc80084d648a95d1ea24a834d737235f6/packages/gql-format/dist/index.js#L546-L550 |
41,164 | FamilySearch/fs-js-lite | src/xhrHandler.js | createResponse | function createResponse(xhr, request){
// XHR header processing borrowed from jQuery
var responseHeaders = {}, match;
while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
return {
statusCode: xhr.status,
statusText: xhr.statusText,
headers: responseHeaders,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: xhr.responseText,
retries: 0,
throttled: false
};
} | javascript | function createResponse(xhr, request){
// XHR header processing borrowed from jQuery
var responseHeaders = {}, match;
while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
return {
statusCode: xhr.status,
statusText: xhr.statusText,
headers: responseHeaders,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: xhr.responseText,
retries: 0,
throttled: false
};
} | [
"function",
"createResponse",
"(",
"xhr",
",",
"request",
")",
"{",
"// XHR header processing borrowed from jQuery",
"var",
"responseHeaders",
"=",
"{",
"}",
",",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"headersRegex",
".",
"exec",
"(",
"xhr",
".",
"getAllResponseHeaders",
"(",
")",
")",
")",
")",
"{",
"responseHeaders",
"[",
"match",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"match",
"[",
"2",
"]",
";",
"}",
"return",
"{",
"statusCode",
":",
"xhr",
".",
"status",
",",
"statusText",
":",
"xhr",
".",
"statusText",
",",
"headers",
":",
"responseHeaders",
",",
"originalUrl",
":",
"request",
".",
"url",
",",
"effectiveUrl",
":",
"request",
".",
"url",
",",
"redirected",
":",
"false",
",",
"requestMethod",
":",
"request",
".",
"method",
",",
"requestHeaders",
":",
"request",
".",
"headers",
",",
"body",
":",
"xhr",
".",
"responseText",
",",
"retries",
":",
"0",
",",
"throttled",
":",
"false",
"}",
";",
"}"
]
| Convert an XHR response to a standard response object
@param {XMLHttpRequest} xhr
@param {Object} request {url, method, headers, retries}
@return {Object} response | [
"Convert",
"an",
"XHR",
"response",
"to",
"a",
"standard",
"response",
"object"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/xhrHandler.js#L51-L72 |
41,165 | FamilySearch/fs-js-lite | src/FamilySearch.js | function(options){
// Set the default options
this.appKey = '';
this.environment = 'integration';
this.redirectUri = '';
this.tokenCookie = 'FS_AUTH_TOKEN';
this.maxThrottledRetries = 10;
this.saveAccessToken = false;
this.accessToken = '';
this.jwt = '';
this.middleware = {
request: [
requestMiddleware.url,
requestMiddleware.defaultAcceptHeader,
requestMiddleware.authorizationHeader,
requestMiddleware.disableAutomaticRedirects,
requestMiddleware.body
],
response: [
responseMiddleware.redirect,
responseMiddleware.throttling,
responseMiddleware.json
]
};
// Process options
this.config(options);
} | javascript | function(options){
// Set the default options
this.appKey = '';
this.environment = 'integration';
this.redirectUri = '';
this.tokenCookie = 'FS_AUTH_TOKEN';
this.maxThrottledRetries = 10;
this.saveAccessToken = false;
this.accessToken = '';
this.jwt = '';
this.middleware = {
request: [
requestMiddleware.url,
requestMiddleware.defaultAcceptHeader,
requestMiddleware.authorizationHeader,
requestMiddleware.disableAutomaticRedirects,
requestMiddleware.body
],
response: [
responseMiddleware.redirect,
responseMiddleware.throttling,
responseMiddleware.json
]
};
// Process options
this.config(options);
} | [
"function",
"(",
"options",
")",
"{",
"// Set the default options",
"this",
".",
"appKey",
"=",
"''",
";",
"this",
".",
"environment",
"=",
"'integration'",
";",
"this",
".",
"redirectUri",
"=",
"''",
";",
"this",
".",
"tokenCookie",
"=",
"'FS_AUTH_TOKEN'",
";",
"this",
".",
"maxThrottledRetries",
"=",
"10",
";",
"this",
".",
"saveAccessToken",
"=",
"false",
";",
"this",
".",
"accessToken",
"=",
"''",
";",
"this",
".",
"jwt",
"=",
"''",
";",
"this",
".",
"middleware",
"=",
"{",
"request",
":",
"[",
"requestMiddleware",
".",
"url",
",",
"requestMiddleware",
".",
"defaultAcceptHeader",
",",
"requestMiddleware",
".",
"authorizationHeader",
",",
"requestMiddleware",
".",
"disableAutomaticRedirects",
",",
"requestMiddleware",
".",
"body",
"]",
",",
"response",
":",
"[",
"responseMiddleware",
".",
"redirect",
",",
"responseMiddleware",
".",
"throttling",
",",
"responseMiddleware",
".",
"json",
"]",
"}",
";",
"// Process options",
"this",
".",
"config",
"(",
"options",
")",
";",
"}"
]
| Create an instance of the FamilySearch SDK Client
@param {Object} options See a description of the possible options in the docs for config(). | [
"Create",
"an",
"instance",
"of",
"the",
"FamilySearch",
"SDK",
"Client"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/FamilySearch.js#L13-L41 |
|
41,166 | philipwalton/private-parts | index.js | createKey | function createKey(factory){
// Create the factory based on the type of object passed.
factory = typeof factory == 'function'
? factory
: createBound(factory);
// Store is used to map public objects to private objects.
var store = new WeakMap();
// Seen is used to track existing private objects.
var seen = new WeakMap();
/**
* An accessor function to get private instances from the store.
* @param {Object} key The public object that is associated with a private
* object in the store.
*/
return function(key) {
if (typeof key != 'object') return;
var value = store.get(key);
if (!value) {
// Make sure key isn't already the private instance of some existing key.
// This check helps prevent accidental double privatizing.
if (seen.has(key)) {
value = key;
} else {
value = factory(key);
store.set(key, value);
seen.set(value, true);
}
}
return value;
};
} | javascript | function createKey(factory){
// Create the factory based on the type of object passed.
factory = typeof factory == 'function'
? factory
: createBound(factory);
// Store is used to map public objects to private objects.
var store = new WeakMap();
// Seen is used to track existing private objects.
var seen = new WeakMap();
/**
* An accessor function to get private instances from the store.
* @param {Object} key The public object that is associated with a private
* object in the store.
*/
return function(key) {
if (typeof key != 'object') return;
var value = store.get(key);
if (!value) {
// Make sure key isn't already the private instance of some existing key.
// This check helps prevent accidental double privatizing.
if (seen.has(key)) {
value = key;
} else {
value = factory(key);
store.set(key, value);
seen.set(value, true);
}
}
return value;
};
} | [
"function",
"createKey",
"(",
"factory",
")",
"{",
"// Create the factory based on the type of object passed.",
"factory",
"=",
"typeof",
"factory",
"==",
"'function'",
"?",
"factory",
":",
"createBound",
"(",
"factory",
")",
";",
"// Store is used to map public objects to private objects.",
"var",
"store",
"=",
"new",
"WeakMap",
"(",
")",
";",
"// Seen is used to track existing private objects.",
"var",
"seen",
"=",
"new",
"WeakMap",
"(",
")",
";",
"/**\n * An accessor function to get private instances from the store.\n * @param {Object} key The public object that is associated with a private\n * object in the store.\n */",
"return",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"typeof",
"key",
"!=",
"'object'",
")",
"return",
";",
"var",
"value",
"=",
"store",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"!",
"value",
")",
"{",
"// Make sure key isn't already the private instance of some existing key.",
"// This check helps prevent accidental double privatizing.",
"if",
"(",
"seen",
".",
"has",
"(",
"key",
")",
")",
"{",
"value",
"=",
"key",
";",
"}",
"else",
"{",
"value",
"=",
"factory",
"(",
"key",
")",
";",
"store",
".",
"set",
"(",
"key",
",",
"value",
")",
";",
"seen",
".",
"set",
"(",
"value",
",",
"true",
")",
";",
"}",
"}",
"return",
"value",
";",
"}",
";",
"}"
]
| A function that returns a function that allows you to associate
a public object with its private counterpart.
@param {Function|Object} factory An optional argument that, is present, will
be used to create new objects in the store.
If factory is a function, it will be invoked with the key as an argument
and the return value will be the private instance.
If factory is an object, the private instance will be a new object with
factory as it's prototype. | [
"A",
"function",
"that",
"returns",
"a",
"function",
"that",
"allows",
"you",
"to",
"associate",
"a",
"public",
"object",
"with",
"its",
"private",
"counterpart",
"."
]
| 710d42f35c6c31267ba865af3470b4a08ce1fdd9 | https://github.com/philipwalton/private-parts/blob/710d42f35c6c31267ba865af3470b4a08ce1fdd9/index.js#L11-L46 |
41,167 | FamilySearch/fs-js-lite | docs/console.js | makeRequest | function makeRequest(){
output('Sending the request...');
var options = {
method: $method.value,
headers: {
Accept: document.getElementById('accept').value
},
followRedirect: $followRedirect.checked
};
if(options.method === 'POST'){
options.body = $requestBody.value;
}
client.request($url.value, options, function(error, response){
if(error){
genericError();
} else {
displayResponse(response);
if(response.statusCode === 401){
$authStatus.classList.remove('loggedin');
$tokenDisplay.value = '';
} else {
$authStatus.classList.add('loggedin');
$tokenDisplay.value = 'Bearer ' + client.getAccessToken();
}
}
});
} | javascript | function makeRequest(){
output('Sending the request...');
var options = {
method: $method.value,
headers: {
Accept: document.getElementById('accept').value
},
followRedirect: $followRedirect.checked
};
if(options.method === 'POST'){
options.body = $requestBody.value;
}
client.request($url.value, options, function(error, response){
if(error){
genericError();
} else {
displayResponse(response);
if(response.statusCode === 401){
$authStatus.classList.remove('loggedin');
$tokenDisplay.value = '';
} else {
$authStatus.classList.add('loggedin');
$tokenDisplay.value = 'Bearer ' + client.getAccessToken();
}
}
});
} | [
"function",
"makeRequest",
"(",
")",
"{",
"output",
"(",
"'Sending the request...'",
")",
";",
"var",
"options",
"=",
"{",
"method",
":",
"$method",
".",
"value",
",",
"headers",
":",
"{",
"Accept",
":",
"document",
".",
"getElementById",
"(",
"'accept'",
")",
".",
"value",
"}",
",",
"followRedirect",
":",
"$followRedirect",
".",
"checked",
"}",
";",
"if",
"(",
"options",
".",
"method",
"===",
"'POST'",
")",
"{",
"options",
".",
"body",
"=",
"$requestBody",
".",
"value",
";",
"}",
"client",
".",
"request",
"(",
"$url",
".",
"value",
",",
"options",
",",
"function",
"(",
"error",
",",
"response",
")",
"{",
"if",
"(",
"error",
")",
"{",
"genericError",
"(",
")",
";",
"}",
"else",
"{",
"displayResponse",
"(",
"response",
")",
";",
"if",
"(",
"response",
".",
"statusCode",
"===",
"401",
")",
"{",
"$authStatus",
".",
"classList",
".",
"remove",
"(",
"'loggedin'",
")",
";",
"$tokenDisplay",
".",
"value",
"=",
"''",
";",
"}",
"else",
"{",
"$authStatus",
".",
"classList",
".",
"add",
"(",
"'loggedin'",
")",
";",
"$tokenDisplay",
".",
"value",
"=",
"'Bearer '",
"+",
"client",
".",
"getAccessToken",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Send a request to the API and display the response | [
"Send",
"a",
"request",
"to",
"the",
"API",
"and",
"display",
"the",
"response"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L63-L91 |
41,168 | FamilySearch/fs-js-lite | docs/console.js | displayResponse | function displayResponse(response){
// Gather and display HTTP response data
var lines = [
response.statusCode + ' ' + response.statusText,
headersToString(response.headers)
];
if(response.data){
lines.push('');
lines.push(prettyPrint(response.data));
}
output(lines.join('\n'));
// Attach listeners to links so that clicking a link will auto-populate
// the url field
Array.from($output.querySelectorAll('.link')).forEach(function(link){
link.addEventListener('click', function(){
// Remove leading and trailing "
$url.value = link.innerHTML.slice(1,-1);
window.scrollTo(0, 0);
});
});
} | javascript | function displayResponse(response){
// Gather and display HTTP response data
var lines = [
response.statusCode + ' ' + response.statusText,
headersToString(response.headers)
];
if(response.data){
lines.push('');
lines.push(prettyPrint(response.data));
}
output(lines.join('\n'));
// Attach listeners to links so that clicking a link will auto-populate
// the url field
Array.from($output.querySelectorAll('.link')).forEach(function(link){
link.addEventListener('click', function(){
// Remove leading and trailing "
$url.value = link.innerHTML.slice(1,-1);
window.scrollTo(0, 0);
});
});
} | [
"function",
"displayResponse",
"(",
"response",
")",
"{",
"// Gather and display HTTP response data",
"var",
"lines",
"=",
"[",
"response",
".",
"statusCode",
"+",
"' '",
"+",
"response",
".",
"statusText",
",",
"headersToString",
"(",
"response",
".",
"headers",
")",
"]",
";",
"if",
"(",
"response",
".",
"data",
")",
"{",
"lines",
".",
"push",
"(",
"''",
")",
";",
"lines",
".",
"push",
"(",
"prettyPrint",
"(",
"response",
".",
"data",
")",
")",
";",
"}",
"output",
"(",
"lines",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"// Attach listeners to links so that clicking a link will auto-populate",
"// the url field",
"Array",
".",
"from",
"(",
"$output",
".",
"querySelectorAll",
"(",
"'.link'",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"link",
")",
"{",
"link",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"// Remove leading and trailing \"",
"$url",
".",
"value",
"=",
"link",
".",
"innerHTML",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
";",
"window",
".",
"scrollTo",
"(",
"0",
",",
"0",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Display an API response
@param {Object} response | [
"Display",
"an",
"API",
"response"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L105-L127 |
41,169 | FamilySearch/fs-js-lite | docs/console.js | headersToString | function headersToString(headers){
var lines = [];
for(var name in headers){
lines.push(name + ': ' + headers[name]);
}
return lines.join('\n');
} | javascript | function headersToString(headers){
var lines = [];
for(var name in headers){
lines.push(name + ': ' + headers[name]);
}
return lines.join('\n');
} | [
"function",
"headersToString",
"(",
"headers",
")",
"{",
"var",
"lines",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"name",
"in",
"headers",
")",
"{",
"lines",
".",
"push",
"(",
"name",
"+",
"': '",
"+",
"headers",
"[",
"name",
"]",
")",
";",
"}",
"return",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
]
| Convert a headers map into a multi-line string
@param {Object} headers
@return {String} | [
"Convert",
"a",
"headers",
"map",
"into",
"a",
"multi",
"-",
"line",
"string"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L135-L141 |
41,170 | FamilySearch/fs-js-lite | docs/console.js | syntaxHighlight | function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number',
url = false;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
if(match.indexOf('"https://') === 0){
// url = true;
cls += ' link';
}
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
var html = '<span class="' + cls + '">' + match + '</span>';
if(url){
html = '<a href>' + html + '</a>';
}
return html;
});
} | javascript | function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number',
url = false;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
if(match.indexOf('"https://') === 0){
// url = true;
cls += ' link';
}
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
var html = '<span class="' + cls + '">' + match + '</span>';
if(url){
html = '<a href>' + html + '</a>';
}
return html;
});
} | [
"function",
"syntaxHighlight",
"(",
"json",
")",
"{",
"json",
"=",
"json",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"'&'",
")",
".",
"replace",
"(",
"/",
"<",
"/",
"g",
",",
"'<'",
")",
".",
"replace",
"(",
"/",
">",
"/",
"g",
",",
"'>'",
")",
";",
"return",
"json",
".",
"replace",
"(",
"/",
"(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)",
"/",
"g",
",",
"function",
"(",
"match",
")",
"{",
"var",
"cls",
"=",
"'number'",
",",
"url",
"=",
"false",
";",
"if",
"(",
"/",
"^\"",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"if",
"(",
"/",
":$",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"cls",
"=",
"'key'",
";",
"}",
"else",
"{",
"cls",
"=",
"'string'",
";",
"if",
"(",
"match",
".",
"indexOf",
"(",
"'\"https://'",
")",
"===",
"0",
")",
"{",
"// url = true;",
"cls",
"+=",
"' link'",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"/",
"true|false",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"cls",
"=",
"'boolean'",
";",
"}",
"else",
"if",
"(",
"/",
"null",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"cls",
"=",
"'null'",
";",
"}",
"var",
"html",
"=",
"'<span class=\"'",
"+",
"cls",
"+",
"'\">'",
"+",
"match",
"+",
"'</span>'",
";",
"if",
"(",
"url",
")",
"{",
"html",
"=",
"'<a href>'",
"+",
"html",
"+",
"'</a>'",
";",
"}",
"return",
"html",
";",
"}",
")",
";",
"}"
]
| Parse a JSON string and wrap data in spans to enable syntax highlighting.
http://stackoverflow.com/a/7220510
@param {String} JSON string
@returns {String} | [
"Parse",
"a",
"JSON",
"string",
"and",
"wrap",
"data",
"in",
"spans",
"to",
"enable",
"syntax",
"highlighting",
"."
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L170-L196 |
41,171 | JamesMGreene/currentExecutingScript | src/main.js | getScriptFromUrl | function getScriptFromUrl(url, eligibleScripts) {
var i,
script = null;
eligibleScripts = eligibleScripts || scripts;
if (typeof url === "string" && url) {
for (i = eligibleScripts.length; i--; ) {
if (eligibleScripts[i].src === url) {
// NOTE: Could check if the same script URL is used by more than one `script` element
// here... but let's not. That would yield less useful results in "loose" detection. ;)
script = eligibleScripts[i];
break;
}
}
}
return script;
} | javascript | function getScriptFromUrl(url, eligibleScripts) {
var i,
script = null;
eligibleScripts = eligibleScripts || scripts;
if (typeof url === "string" && url) {
for (i = eligibleScripts.length; i--; ) {
if (eligibleScripts[i].src === url) {
// NOTE: Could check if the same script URL is used by more than one `script` element
// here... but let's not. That would yield less useful results in "loose" detection. ;)
script = eligibleScripts[i];
break;
}
}
}
return script;
} | [
"function",
"getScriptFromUrl",
"(",
"url",
",",
"eligibleScripts",
")",
"{",
"var",
"i",
",",
"script",
"=",
"null",
";",
"eligibleScripts",
"=",
"eligibleScripts",
"||",
"scripts",
";",
"if",
"(",
"typeof",
"url",
"===",
"\"string\"",
"&&",
"url",
")",
"{",
"for",
"(",
"i",
"=",
"eligibleScripts",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"if",
"(",
"eligibleScripts",
"[",
"i",
"]",
".",
"src",
"===",
"url",
")",
"{",
"// NOTE: Could check if the same script URL is used by more than one `script` element",
"// here... but let's not. That would yield less useful results in \"loose\" detection. ;)",
"script",
"=",
"eligibleScripts",
"[",
"i",
"]",
";",
"break",
";",
"}",
"}",
"}",
"return",
"script",
";",
"}"
]
| Get script object based on the `src` URL | [
"Get",
"script",
"object",
"based",
"on",
"the",
"src",
"URL"
]
| cfb5905463a6cc80f95d0d64721db269524c2ac9 | https://github.com/JamesMGreene/currentExecutingScript/blob/cfb5905463a6cc80f95d0d64721db269524c2ac9/src/main.js#L52-L69 |
41,172 | JamesMGreene/currentExecutingScript | src/main.js | getSoleInlineScript | function getSoleInlineScript(eligibleScripts) {
var i, len,
script = null;
eligibleScripts = eligibleScripts || scripts;
for (i = 0, len = eligibleScripts.length; i < len; i++) {
if (!eligibleScripts[i].hasAttribute("src")) {
if (script) {
script = null;
break;
}
script = eligibleScripts[i];
}
}
return script;
} | javascript | function getSoleInlineScript(eligibleScripts) {
var i, len,
script = null;
eligibleScripts = eligibleScripts || scripts;
for (i = 0, len = eligibleScripts.length; i < len; i++) {
if (!eligibleScripts[i].hasAttribute("src")) {
if (script) {
script = null;
break;
}
script = eligibleScripts[i];
}
}
return script;
} | [
"function",
"getSoleInlineScript",
"(",
"eligibleScripts",
")",
"{",
"var",
"i",
",",
"len",
",",
"script",
"=",
"null",
";",
"eligibleScripts",
"=",
"eligibleScripts",
"||",
"scripts",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"eligibleScripts",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"eligibleScripts",
"[",
"i",
"]",
".",
"hasAttribute",
"(",
"\"src\"",
")",
")",
"{",
"if",
"(",
"script",
")",
"{",
"script",
"=",
"null",
";",
"break",
";",
"}",
"script",
"=",
"eligibleScripts",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"script",
";",
"}"
]
| If there is only a single inline script on the page, return it; otherwise `null` | [
"If",
"there",
"is",
"only",
"a",
"single",
"inline",
"script",
"on",
"the",
"page",
"return",
"it",
";",
"otherwise",
"null"
]
| cfb5905463a6cc80f95d0d64721db269524c2ac9 | https://github.com/JamesMGreene/currentExecutingScript/blob/cfb5905463a6cc80f95d0d64721db269524c2ac9/src/main.js#L100-L114 |
41,173 | JamesMGreene/currentExecutingScript | src/main.js | getScriptUrlFromStack | function getScriptUrlFromStack(stack, skipStackDepth) {
var matches, remainingStack,
url = null,
ignoreMessage = typeof skipStackDepth === "number";
skipStackDepth = ignoreMessage ? Math.round(skipStackDepth) : 0;
if (typeof stack === "string" && stack) {
if (ignoreMessage) {
matches = stack.match(/(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
else {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=data:text\/javascript|blob|http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (!(matches && matches[1])) {
matches = stack.match(/\)@(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
}
if (matches && matches[1]) {
if (skipStackDepth > 0) {
remainingStack = stack.slice(stack.indexOf(matches[0]) + matches[0].length);
url = getScriptUrlFromStack(remainingStack, (skipStackDepth - 1));
}
else {
url = matches[1];
}
}
// TODO: Handle more edge cases!
// Fixes #1
// See https://github.com/JamesMGreene/currentExecutingScript/issues/1
// ???
}
return url;
} | javascript | function getScriptUrlFromStack(stack, skipStackDepth) {
var matches, remainingStack,
url = null,
ignoreMessage = typeof skipStackDepth === "number";
skipStackDepth = ignoreMessage ? Math.round(skipStackDepth) : 0;
if (typeof stack === "string" && stack) {
if (ignoreMessage) {
matches = stack.match(/(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
else {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=data:text\/javascript|blob|http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (!(matches && matches[1])) {
matches = stack.match(/\)@(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
}
if (matches && matches[1]) {
if (skipStackDepth > 0) {
remainingStack = stack.slice(stack.indexOf(matches[0]) + matches[0].length);
url = getScriptUrlFromStack(remainingStack, (skipStackDepth - 1));
}
else {
url = matches[1];
}
}
// TODO: Handle more edge cases!
// Fixes #1
// See https://github.com/JamesMGreene/currentExecutingScript/issues/1
// ???
}
return url;
} | [
"function",
"getScriptUrlFromStack",
"(",
"stack",
",",
"skipStackDepth",
")",
"{",
"var",
"matches",
",",
"remainingStack",
",",
"url",
"=",
"null",
",",
"ignoreMessage",
"=",
"typeof",
"skipStackDepth",
"===",
"\"number\"",
";",
"skipStackDepth",
"=",
"ignoreMessage",
"?",
"Math",
".",
"round",
"(",
"skipStackDepth",
")",
":",
"0",
";",
"if",
"(",
"typeof",
"stack",
"===",
"\"string\"",
"&&",
"stack",
")",
"{",
"if",
"(",
"ignoreMessage",
")",
"{",
"matches",
"=",
"stack",
".",
"match",
"(",
"/",
"(data:text\\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\\/\\/[\\/]?.+?\\/[^:\\)]*?)(?::\\d+)(?::\\d+)?",
"/",
")",
";",
"}",
"else",
"{",
"matches",
"=",
"stack",
".",
"match",
"(",
"/",
"^(?:|[^:@]*@|.+\\)@(?=data:text\\/javascript|blob|http[s]?|file)|.+?\\s+(?: at |@)(?:[^:\\(]+ )*[\\(]?)(data:text\\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\\/\\/[\\/]?.+?\\/[^:\\)]*?)(?::\\d+)(?::\\d+)?",
"/",
")",
";",
"if",
"(",
"!",
"(",
"matches",
"&&",
"matches",
"[",
"1",
"]",
")",
")",
"{",
"matches",
"=",
"stack",
".",
"match",
"(",
"/",
"\\)@(data:text\\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\\/\\/[\\/]?.+?\\/[^:\\)]*?)(?::\\d+)(?::\\d+)?",
"/",
")",
";",
"}",
"}",
"if",
"(",
"matches",
"&&",
"matches",
"[",
"1",
"]",
")",
"{",
"if",
"(",
"skipStackDepth",
">",
"0",
")",
"{",
"remainingStack",
"=",
"stack",
".",
"slice",
"(",
"stack",
".",
"indexOf",
"(",
"matches",
"[",
"0",
"]",
")",
"+",
"matches",
"[",
"0",
"]",
".",
"length",
")",
";",
"url",
"=",
"getScriptUrlFromStack",
"(",
"remainingStack",
",",
"(",
"skipStackDepth",
"-",
"1",
")",
")",
";",
"}",
"else",
"{",
"url",
"=",
"matches",
"[",
"1",
"]",
";",
"}",
"}",
"// TODO: Handle more edge cases!",
"// Fixes #1",
"// See https://github.com/JamesMGreene/currentExecutingScript/issues/1",
"// ???",
"}",
"return",
"url",
";",
"}"
]
| Get the currently executing script URL from an Error stack trace | [
"Get",
"the",
"currently",
"executing",
"script",
"URL",
"from",
"an",
"Error",
"stack",
"trace"
]
| cfb5905463a6cc80f95d0d64721db269524c2ac9 | https://github.com/JamesMGreene/currentExecutingScript/blob/cfb5905463a6cc80f95d0d64721db269524c2ac9/src/main.js#L117-L152 |
41,174 | FamilySearch/fs-js-lite | src/nodeHandler.js | createResponse | function createResponse(request, response, body){
return {
statusCode: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: body,
retries: 0,
throttled: false
};
} | javascript | function createResponse(request, response, body){
return {
statusCode: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: body,
retries: 0,
throttled: false
};
} | [
"function",
"createResponse",
"(",
"request",
",",
"response",
",",
"body",
")",
"{",
"return",
"{",
"statusCode",
":",
"response",
".",
"statusCode",
",",
"statusText",
":",
"response",
".",
"statusMessage",
",",
"headers",
":",
"response",
".",
"headers",
",",
"originalUrl",
":",
"request",
".",
"url",
",",
"effectiveUrl",
":",
"request",
".",
"url",
",",
"redirected",
":",
"false",
",",
"requestMethod",
":",
"request",
".",
"method",
",",
"requestHeaders",
":",
"request",
".",
"headers",
",",
"body",
":",
"body",
",",
"retries",
":",
"0",
",",
"throttled",
":",
"false",
"}",
";",
"}"
]
| Convert an node response to a standard sdk response object
@param {Object} request {url, method, headers, retries}
@param {http.IncomingMessage} response
@param {String} body
@return {Object} response | [
"Convert",
"an",
"node",
"response",
"to",
"a",
"standard",
"sdk",
"response",
"object"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/nodeHandler.js#L33-L47 |
41,175 | Soreine/draft-js-simpledecorator | index.js | callback | function callback (start, end, props) {
if (props === undefined) {
props = {};
}
key = blockKey + KEY_SEPARATOR + decorationId;
decorated[blockKey][decorationId] = props;
decorateRange(decorations, start, end, key);
decorationId++;
} | javascript | function callback (start, end, props) {
if (props === undefined) {
props = {};
}
key = blockKey + KEY_SEPARATOR + decorationId;
decorated[blockKey][decorationId] = props;
decorateRange(decorations, start, end, key);
decorationId++;
} | [
"function",
"callback",
"(",
"start",
",",
"end",
",",
"props",
")",
"{",
"if",
"(",
"props",
"===",
"undefined",
")",
"{",
"props",
"=",
"{",
"}",
";",
"}",
"key",
"=",
"blockKey",
"+",
"KEY_SEPARATOR",
"+",
"decorationId",
";",
"decorated",
"[",
"blockKey",
"]",
"[",
"decorationId",
"]",
"=",
"props",
";",
"decorateRange",
"(",
"decorations",
",",
"start",
",",
"end",
",",
"key",
")",
";",
"decorationId",
"++",
";",
"}"
]
| Apply a decoration to given range, with given props | [
"Apply",
"a",
"decoration",
"to",
"given",
"range",
"with",
"given",
"props"
]
| 436fe513f7d97322cfbf7c779050d539948ab65d | https://github.com/Soreine/draft-js-simpledecorator/blob/436fe513f7d97322cfbf7c779050d539948ab65d/index.js#L24-L32 |
41,176 | mrbar42/trixion | src/polyfill/promise.js | handleThenable | function handleThenable(promise, value) {
var done, then;
// Attempt to get the `then` method from the thenable (if it is a thenable)
try {
if (! (then = utils.thenable(value))) {
return false;
}
} catch (err) {
rejectPromise(promise, err);
return true;
}
// Ensure that the promise did not attempt to fulfill with itself
if (promise === value) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return true;
}
try {
// Wait for the thenable to fulfill/reject before moving on
then.call(value,
function(subValue) {
if (! done) {
done = true;
// Once again look for circular promise resolution
if (value === subValue) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return;
}
resolvePromise(promise, subValue);
}
},
function(subValue) {
if (! done) {
done = true;
rejectPromise(promise, subValue);
}
}
);
} catch (err) {
if (! done) {
done = true;
rejectPromise(promise, err);
}
}
return true;
} | javascript | function handleThenable(promise, value) {
var done, then;
// Attempt to get the `then` method from the thenable (if it is a thenable)
try {
if (! (then = utils.thenable(value))) {
return false;
}
} catch (err) {
rejectPromise(promise, err);
return true;
}
// Ensure that the promise did not attempt to fulfill with itself
if (promise === value) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return true;
}
try {
// Wait for the thenable to fulfill/reject before moving on
then.call(value,
function(subValue) {
if (! done) {
done = true;
// Once again look for circular promise resolution
if (value === subValue) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return;
}
resolvePromise(promise, subValue);
}
},
function(subValue) {
if (! done) {
done = true;
rejectPromise(promise, subValue);
}
}
);
} catch (err) {
if (! done) {
done = true;
rejectPromise(promise, err);
}
}
return true;
} | [
"function",
"handleThenable",
"(",
"promise",
",",
"value",
")",
"{",
"var",
"done",
",",
"then",
";",
"// Attempt to get the `then` method from the thenable (if it is a thenable)",
"try",
"{",
"if",
"(",
"!",
"(",
"then",
"=",
"utils",
".",
"thenable",
"(",
"value",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"rejectPromise",
"(",
"promise",
",",
"err",
")",
";",
"return",
"true",
";",
"}",
"// Ensure that the promise did not attempt to fulfill with itself",
"if",
"(",
"promise",
"===",
"value",
")",
"{",
"rejectPromise",
"(",
"promise",
",",
"new",
"TypeError",
"(",
"'Circular resolution of promises'",
")",
")",
";",
"return",
"true",
";",
"}",
"try",
"{",
"// Wait for the thenable to fulfill/reject before moving on",
"then",
".",
"call",
"(",
"value",
",",
"function",
"(",
"subValue",
")",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"done",
"=",
"true",
";",
"// Once again look for circular promise resolution",
"if",
"(",
"value",
"===",
"subValue",
")",
"{",
"rejectPromise",
"(",
"promise",
",",
"new",
"TypeError",
"(",
"'Circular resolution of promises'",
")",
")",
";",
"return",
";",
"}",
"resolvePromise",
"(",
"promise",
",",
"subValue",
")",
";",
"}",
"}",
",",
"function",
"(",
"subValue",
")",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"done",
"=",
"true",
";",
"rejectPromise",
"(",
"promise",
",",
"subValue",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"done",
"=",
"true",
";",
"rejectPromise",
"(",
"promise",
",",
"err",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| When a promise resolves with another thenable, this function handles delegating control and passing around values @param {child} the child promise that values will be passed to @param {value} the thenable value from the previous promise @return boolean | [
"When",
"a",
"promise",
"resolves",
"with",
"another",
"thenable",
"this",
"function",
"handles",
"delegating",
"control",
"and",
"passing",
"around",
"values"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L246-L298 |
41,177 | mrbar42/trixion | src/polyfill/promise.js | fulfillPromise | function fulfillPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FULFILLED);
invokeFunctions(promise);
});
} | javascript | function fulfillPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FULFILLED);
invokeFunctions(promise);
});
} | [
"function",
"fulfillPromise",
"(",
"promise",
",",
"value",
")",
"{",
"if",
"(",
"promise",
".",
"state",
"!==",
"PENDING",
")",
"{",
"return",
";",
"}",
"setValue",
"(",
"promise",
",",
"value",
")",
";",
"setState",
"(",
"promise",
",",
"UNFULFILLED",
")",
";",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"setState",
"(",
"promise",
",",
"FULFILLED",
")",
";",
"invokeFunctions",
"(",
"promise",
")",
";",
"}",
")",
";",
"}"
]
| Fulfill the given promise @param {promise} the promise to resolve @param {value} the value of the promise @return void | [
"Fulfill",
"the",
"given",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L307-L317 |
41,178 | mrbar42/trixion | src/polyfill/promise.js | rejectPromise | function rejectPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FAILED);
invokeFunctions(promise);
});
} | javascript | function rejectPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FAILED);
invokeFunctions(promise);
});
} | [
"function",
"rejectPromise",
"(",
"promise",
",",
"value",
")",
"{",
"if",
"(",
"promise",
".",
"state",
"!==",
"PENDING",
")",
"{",
"return",
";",
"}",
"setValue",
"(",
"promise",
",",
"value",
")",
";",
"setState",
"(",
"promise",
",",
"UNFULFILLED",
")",
";",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"setState",
"(",
"promise",
",",
"FAILED",
")",
";",
"invokeFunctions",
"(",
"promise",
")",
";",
"}",
")",
";",
"}"
]
| Reject the given promise @param {promise} the promise to reject @param {value} the value of the promise @return void | [
"Reject",
"the",
"given",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L326-L336 |
41,179 | mrbar42/trixion | src/polyfill/promise.js | setState | function setState(promise, state) {
utils.defineProperty(promise, 'state', {
enumerable: false,
// According to the spec: If the state is UNFULFILLED (0), the state can be changed;
// If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we
// lock the property
configurable: (! state),
writable: false,
value: state
});
} | javascript | function setState(promise, state) {
utils.defineProperty(promise, 'state', {
enumerable: false,
// According to the spec: If the state is UNFULFILLED (0), the state can be changed;
// If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we
// lock the property
configurable: (! state),
writable: false,
value: state
});
} | [
"function",
"setState",
"(",
"promise",
",",
"state",
")",
"{",
"utils",
".",
"defineProperty",
"(",
"promise",
",",
"'state'",
",",
"{",
"enumerable",
":",
"false",
",",
"// According to the spec: If the state is UNFULFILLED (0), the state can be changed;",
"// If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we",
"// lock the property",
"configurable",
":",
"(",
"!",
"state",
")",
",",
"writable",
":",
"false",
",",
"value",
":",
"state",
"}",
")",
";",
"}"
]
| Set the state of a promise @param {promise} the promise to modify @param {state} the new state @return void | [
"Set",
"the",
"state",
"of",
"a",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L345-L355 |
41,180 | mrbar42/trixion | src/polyfill/promise.js | setValue | function setValue(promise, value) {
utils.defineProperty(promise, 'value', {
enumerable: false,
configurable: false,
writable: false,
value: value
});
} | javascript | function setValue(promise, value) {
utils.defineProperty(promise, 'value', {
enumerable: false,
configurable: false,
writable: false,
value: value
});
} | [
"function",
"setValue",
"(",
"promise",
",",
"value",
")",
"{",
"utils",
".",
"defineProperty",
"(",
"promise",
",",
"'value'",
",",
"{",
"enumerable",
":",
"false",
",",
"configurable",
":",
"false",
",",
"writable",
":",
"false",
",",
"value",
":",
"value",
"}",
")",
";",
"}"
]
| Set the value of a promise @param {promise} the promise to modify @param {value} the value to store @return void | [
"Set",
"the",
"value",
"of",
"a",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L364-L371 |
41,181 | mrbar42/trixion | src/polyfill/promise.js | invokeFunctions | function invokeFunctions(promise) {
var funcs = promise.funcs;
for (var i = 0, c = funcs.length; i < c; i += 3) {
invokeFunction(promise, funcs[i], funcs[i + promise.state]);
}
// Empty out this list of functions as no one function will be called
// more than once, and we don't want to hold them in memory longer than needed
promise.funcs.length = 0;
} | javascript | function invokeFunctions(promise) {
var funcs = promise.funcs;
for (var i = 0, c = funcs.length; i < c; i += 3) {
invokeFunction(promise, funcs[i], funcs[i + promise.state]);
}
// Empty out this list of functions as no one function will be called
// more than once, and we don't want to hold them in memory longer than needed
promise.funcs.length = 0;
} | [
"function",
"invokeFunctions",
"(",
"promise",
")",
"{",
"var",
"funcs",
"=",
"promise",
".",
"funcs",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"c",
"=",
"funcs",
".",
"length",
";",
"i",
"<",
"c",
";",
"i",
"+=",
"3",
")",
"{",
"invokeFunction",
"(",
"promise",
",",
"funcs",
"[",
"i",
"]",
",",
"funcs",
"[",
"i",
"+",
"promise",
".",
"state",
"]",
")",
";",
"}",
"// Empty out this list of functions as no one function will be called",
"// more than once, and we don't want to hold them in memory longer than needed",
"promise",
".",
"funcs",
".",
"length",
"=",
"0",
";",
"}"
]
| Invoke all existing functions queued up on the promise @param {promise} the promise to run functions for @return void | [
"Invoke",
"all",
"existing",
"functions",
"queued",
"up",
"on",
"the",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L379-L389 |
41,182 | mrbar42/trixion | src/polyfill/promise.js | invokeFunction | function invokeFunction(promise, child, func) {
var value = promise.value;
var state = promise.state;
// If we have a function to run, run it
if (typeof func === 'function') {
try {
value = func(value);
} catch (err) {
rejectPromise(child, err);
return;
}
resolvePromise(child, value);
}
else if (state === FULFILLED) {
resolvePromise(child, value);
}
else if (state === FAILED) {
rejectPromise(child, value);
}
} | javascript | function invokeFunction(promise, child, func) {
var value = promise.value;
var state = promise.state;
// If we have a function to run, run it
if (typeof func === 'function') {
try {
value = func(value);
} catch (err) {
rejectPromise(child, err);
return;
}
resolvePromise(child, value);
}
else if (state === FULFILLED) {
resolvePromise(child, value);
}
else if (state === FAILED) {
rejectPromise(child, value);
}
} | [
"function",
"invokeFunction",
"(",
"promise",
",",
"child",
",",
"func",
")",
"{",
"var",
"value",
"=",
"promise",
".",
"value",
";",
"var",
"state",
"=",
"promise",
".",
"state",
";",
"// If we have a function to run, run it",
"if",
"(",
"typeof",
"func",
"===",
"'function'",
")",
"{",
"try",
"{",
"value",
"=",
"func",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"rejectPromise",
"(",
"child",
",",
"err",
")",
";",
"return",
";",
"}",
"resolvePromise",
"(",
"child",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"state",
"===",
"FULFILLED",
")",
"{",
"resolvePromise",
"(",
"child",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"state",
"===",
"FAILED",
")",
"{",
"rejectPromise",
"(",
"child",
",",
"value",
")",
";",
"}",
"}"
]
| Invoke one specific function for the promise @param {promise} the promise the function belongs too (that .then was called on) @param {child} the promise return from the .then call; the next in line @param {func} the function to call @return void | [
"Invoke",
"one",
"specific",
"function",
"for",
"the",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L399-L422 |
41,183 | savantly-net/ngx-graphexp | examples/app/main.bundle.js | function () {
// Existing active nodes
var allNodes = this.graphRoot.selectAll('g').filter('.active_node')
.data(this.nodeModels, function (n) {
return n.id;
});
return allNodes;
} | javascript | function () {
// Existing active nodes
var allNodes = this.graphRoot.selectAll('g').filter('.active_node')
.data(this.nodeModels, function (n) {
return n.id;
});
return allNodes;
} | [
"function",
"(",
")",
"{",
"// Existing active nodes\r",
"var",
"allNodes",
"=",
"this",
".",
"graphRoot",
".",
"selectAll",
"(",
"'g'",
")",
".",
"filter",
"(",
"'.active_node'",
")",
".",
"data",
"(",
"this",
".",
"nodeModels",
",",
"function",
"(",
"n",
")",
"{",
"return",
"n",
".",
"id",
";",
"}",
")",
";",
"return",
"allNodes",
";",
"}"
]
| get all active nodes in the graph | [
"get",
"all",
"active",
"nodes",
"in",
"the",
"graph"
]
| f992861965dd935b45f78cb0c80c574a2cee5b13 | https://github.com/savantly-net/ngx-graphexp/blob/f992861965dd935b45f78cb0c80c574a2cee5b13/examples/app/main.bundle.js#L1250-L1257 |
|
41,184 | FamilySearch/fs-js-lite | src/middleware/request/requestInterval.js | checkQueue | function checkQueue() {
if(!inInterval()) {
if(requestQueue.length) {
var next = requestQueue.shift();
sendRequest(next);
} else if(timer) {
clearInterval(timer); // No need to leave the timer running if we don't have any requests.
}
}
} | javascript | function checkQueue() {
if(!inInterval()) {
if(requestQueue.length) {
var next = requestQueue.shift();
sendRequest(next);
} else if(timer) {
clearInterval(timer); // No need to leave the timer running if we don't have any requests.
}
}
} | [
"function",
"checkQueue",
"(",
")",
"{",
"if",
"(",
"!",
"inInterval",
"(",
")",
")",
"{",
"if",
"(",
"requestQueue",
".",
"length",
")",
"{",
"var",
"next",
"=",
"requestQueue",
".",
"shift",
"(",
")",
";",
"sendRequest",
"(",
"next",
")",
";",
"}",
"else",
"if",
"(",
"timer",
")",
"{",
"clearInterval",
"(",
"timer",
")",
";",
"// No need to leave the timer running if we don't have any requests.",
"}",
"}",
"}"
]
| Check to see if we're ready to send any requests. | [
"Check",
"to",
"see",
"if",
"we",
"re",
"ready",
"to",
"send",
"any",
"requests",
"."
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/middleware/request/requestInterval.js#L38-L47 |
41,185 | pazams/vivalid | lib/input.js | Input | function Input(el, validatorsNameOptionsTuples, onInputValidationResult, isBlurOnly) {
if (validInputTagNames.indexOf(el.nodeName.toLowerCase()) === -1) {
throw 'only operates on the following html tags: ' + validInputTagNames.toString();
}
this._el = el;
this._validatorsNameOptionsTuples = validatorsNameOptionsTuples;
this._onInputValidationResult = onInputValidationResult || defaultOnInputValidationResult;
this._isBlurOnly = isBlurOnly;
this._validators = buildValidators();
this._inputState = new InputState();
this._elName = el.nodeName.toLowerCase();
this._elType = el.type;
this._isKeyed = (this._elName === 'textarea' || keyStrokedInputTypes.indexOf(this._elType) > -1);
this._runValidatorsBounded = this._runValidators.bind(this);
this._initListeners();
function buildValidators() {
var result = [];
validatorsNameOptionsTuples.forEach(function(validatorsNameOptionsTuple) {
var validatorName = validatorsNameOptionsTuple[0];
var validatorOptions = validatorsNameOptionsTuple[1];
result.push({
name: validatorName,
run: validatorRepo.build(validatorName, validatorOptions)
});
});
return result;
}
/** The default {@link _internal.onInputValidationResult onInputValidationResult} used when {@link vivalid.Input} is initiated without a 3rd parameter
* @name defaultOnInputValidationResult
* @function
* @memberof! _internal
*/
function defaultOnInputValidationResult(el, validationsResult, validatorName, stateEnum) {
var errorDiv;
// for radio buttons and checkboxes: get the last element in group by name
if ((el.nodeName.toLowerCase() === 'input' && (el.type === 'radio' || el.type === 'checkbox'))) {
var getAllByName = el.parentNode.querySelectorAll('input[name="' + el.name + '"]');
el = getAllByName.item(getAllByName.length - 1);
}
if (validationsResult.stateEnum === stateEnum.invalid) {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.textContent = validationsResult.message;
} else {
appendNewErrorDiv(el, validationsResult.message);
}
el.style.borderStyle = "solid";
el.style.borderColor = "#ff0000";
$$.addClass(el, "vivalid-error-input");
} else {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.parentNode.removeChild(errorDiv);
el.style.borderStyle = "";
el.style.borderColor = "";
$$.removeClass(el, "vivalid-error-input");
}
}
function getExistingErrorDiv(el) {
if (el.nextElementSibling && el.nextElementSibling.className === "vivalid-error") {
return el.nextElementSibling;
}
}
function appendNewErrorDiv(el, message) {
errorDiv = document.createElement("DIV");
errorDiv.className = "vivalid-error";
errorDiv.style.color = "#ff0000";
var t = document.createTextNode(validationsResult.message);
errorDiv.appendChild(t);
el.parentNode.insertBefore(errorDiv, el.nextElementSibling);
}
}
} | javascript | function Input(el, validatorsNameOptionsTuples, onInputValidationResult, isBlurOnly) {
if (validInputTagNames.indexOf(el.nodeName.toLowerCase()) === -1) {
throw 'only operates on the following html tags: ' + validInputTagNames.toString();
}
this._el = el;
this._validatorsNameOptionsTuples = validatorsNameOptionsTuples;
this._onInputValidationResult = onInputValidationResult || defaultOnInputValidationResult;
this._isBlurOnly = isBlurOnly;
this._validators = buildValidators();
this._inputState = new InputState();
this._elName = el.nodeName.toLowerCase();
this._elType = el.type;
this._isKeyed = (this._elName === 'textarea' || keyStrokedInputTypes.indexOf(this._elType) > -1);
this._runValidatorsBounded = this._runValidators.bind(this);
this._initListeners();
function buildValidators() {
var result = [];
validatorsNameOptionsTuples.forEach(function(validatorsNameOptionsTuple) {
var validatorName = validatorsNameOptionsTuple[0];
var validatorOptions = validatorsNameOptionsTuple[1];
result.push({
name: validatorName,
run: validatorRepo.build(validatorName, validatorOptions)
});
});
return result;
}
/** The default {@link _internal.onInputValidationResult onInputValidationResult} used when {@link vivalid.Input} is initiated without a 3rd parameter
* @name defaultOnInputValidationResult
* @function
* @memberof! _internal
*/
function defaultOnInputValidationResult(el, validationsResult, validatorName, stateEnum) {
var errorDiv;
// for radio buttons and checkboxes: get the last element in group by name
if ((el.nodeName.toLowerCase() === 'input' && (el.type === 'radio' || el.type === 'checkbox'))) {
var getAllByName = el.parentNode.querySelectorAll('input[name="' + el.name + '"]');
el = getAllByName.item(getAllByName.length - 1);
}
if (validationsResult.stateEnum === stateEnum.invalid) {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.textContent = validationsResult.message;
} else {
appendNewErrorDiv(el, validationsResult.message);
}
el.style.borderStyle = "solid";
el.style.borderColor = "#ff0000";
$$.addClass(el, "vivalid-error-input");
} else {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.parentNode.removeChild(errorDiv);
el.style.borderStyle = "";
el.style.borderColor = "";
$$.removeClass(el, "vivalid-error-input");
}
}
function getExistingErrorDiv(el) {
if (el.nextElementSibling && el.nextElementSibling.className === "vivalid-error") {
return el.nextElementSibling;
}
}
function appendNewErrorDiv(el, message) {
errorDiv = document.createElement("DIV");
errorDiv.className = "vivalid-error";
errorDiv.style.color = "#ff0000";
var t = document.createTextNode(validationsResult.message);
errorDiv.appendChild(t);
el.parentNode.insertBefore(errorDiv, el.nextElementSibling);
}
}
} | [
"function",
"Input",
"(",
"el",
",",
"validatorsNameOptionsTuples",
",",
"onInputValidationResult",
",",
"isBlurOnly",
")",
"{",
"if",
"(",
"validInputTagNames",
".",
"indexOf",
"(",
"el",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"'only operates on the following html tags: '",
"+",
"validInputTagNames",
".",
"toString",
"(",
")",
";",
"}",
"this",
".",
"_el",
"=",
"el",
";",
"this",
".",
"_validatorsNameOptionsTuples",
"=",
"validatorsNameOptionsTuples",
";",
"this",
".",
"_onInputValidationResult",
"=",
"onInputValidationResult",
"||",
"defaultOnInputValidationResult",
";",
"this",
".",
"_isBlurOnly",
"=",
"isBlurOnly",
";",
"this",
".",
"_validators",
"=",
"buildValidators",
"(",
")",
";",
"this",
".",
"_inputState",
"=",
"new",
"InputState",
"(",
")",
";",
"this",
".",
"_elName",
"=",
"el",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
";",
"this",
".",
"_elType",
"=",
"el",
".",
"type",
";",
"this",
".",
"_isKeyed",
"=",
"(",
"this",
".",
"_elName",
"===",
"'textarea'",
"||",
"keyStrokedInputTypes",
".",
"indexOf",
"(",
"this",
".",
"_elType",
")",
">",
"-",
"1",
")",
";",
"this",
".",
"_runValidatorsBounded",
"=",
"this",
".",
"_runValidators",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"_initListeners",
"(",
")",
";",
"function",
"buildValidators",
"(",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"validatorsNameOptionsTuples",
".",
"forEach",
"(",
"function",
"(",
"validatorsNameOptionsTuple",
")",
"{",
"var",
"validatorName",
"=",
"validatorsNameOptionsTuple",
"[",
"0",
"]",
";",
"var",
"validatorOptions",
"=",
"validatorsNameOptionsTuple",
"[",
"1",
"]",
";",
"result",
".",
"push",
"(",
"{",
"name",
":",
"validatorName",
",",
"run",
":",
"validatorRepo",
".",
"build",
"(",
"validatorName",
",",
"validatorOptions",
")",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
"/** The default {@link _internal.onInputValidationResult onInputValidationResult} used when {@link vivalid.Input} is initiated without a 3rd parameter\n * @name defaultOnInputValidationResult\n * @function\n * @memberof! _internal\n */",
"function",
"defaultOnInputValidationResult",
"(",
"el",
",",
"validationsResult",
",",
"validatorName",
",",
"stateEnum",
")",
"{",
"var",
"errorDiv",
";",
"// for radio buttons and checkboxes: get the last element in group by name",
"if",
"(",
"(",
"el",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
"===",
"'input'",
"&&",
"(",
"el",
".",
"type",
"===",
"'radio'",
"||",
"el",
".",
"type",
"===",
"'checkbox'",
")",
")",
")",
"{",
"var",
"getAllByName",
"=",
"el",
".",
"parentNode",
".",
"querySelectorAll",
"(",
"'input[name=\"'",
"+",
"el",
".",
"name",
"+",
"'\"]'",
")",
";",
"el",
"=",
"getAllByName",
".",
"item",
"(",
"getAllByName",
".",
"length",
"-",
"1",
")",
";",
"}",
"if",
"(",
"validationsResult",
".",
"stateEnum",
"===",
"stateEnum",
".",
"invalid",
")",
"{",
"errorDiv",
"=",
"getExistingErrorDiv",
"(",
"el",
")",
";",
"if",
"(",
"errorDiv",
")",
"{",
"errorDiv",
".",
"textContent",
"=",
"validationsResult",
".",
"message",
";",
"}",
"else",
"{",
"appendNewErrorDiv",
"(",
"el",
",",
"validationsResult",
".",
"message",
")",
";",
"}",
"el",
".",
"style",
".",
"borderStyle",
"=",
"\"solid\"",
";",
"el",
".",
"style",
".",
"borderColor",
"=",
"\"#ff0000\"",
";",
"$$",
".",
"addClass",
"(",
"el",
",",
"\"vivalid-error-input\"",
")",
";",
"}",
"else",
"{",
"errorDiv",
"=",
"getExistingErrorDiv",
"(",
"el",
")",
";",
"if",
"(",
"errorDiv",
")",
"{",
"errorDiv",
".",
"parentNode",
".",
"removeChild",
"(",
"errorDiv",
")",
";",
"el",
".",
"style",
".",
"borderStyle",
"=",
"\"\"",
";",
"el",
".",
"style",
".",
"borderColor",
"=",
"\"\"",
";",
"$$",
".",
"removeClass",
"(",
"el",
",",
"\"vivalid-error-input\"",
")",
";",
"}",
"}",
"function",
"getExistingErrorDiv",
"(",
"el",
")",
"{",
"if",
"(",
"el",
".",
"nextElementSibling",
"&&",
"el",
".",
"nextElementSibling",
".",
"className",
"===",
"\"vivalid-error\"",
")",
"{",
"return",
"el",
".",
"nextElementSibling",
";",
"}",
"}",
"function",
"appendNewErrorDiv",
"(",
"el",
",",
"message",
")",
"{",
"errorDiv",
"=",
"document",
".",
"createElement",
"(",
"\"DIV\"",
")",
";",
"errorDiv",
".",
"className",
"=",
"\"vivalid-error\"",
";",
"errorDiv",
".",
"style",
".",
"color",
"=",
"\"#ff0000\"",
";",
"var",
"t",
"=",
"document",
".",
"createTextNode",
"(",
"validationsResult",
".",
"message",
")",
";",
"errorDiv",
".",
"appendChild",
"(",
"t",
")",
";",
"el",
".",
"parentNode",
".",
"insertBefore",
"(",
"errorDiv",
",",
"el",
".",
"nextElementSibling",
")",
";",
"}",
"}",
"}"
]
| creates a new Input object wrapping around a DOM object.
@memberof! vivalid
@class
@example new Input(document.getElementById('Name'), [['required',{msg: 'custom required message'}],['max',{max: 10}]])
@param {HTMLElement} el the DOM object to wrap. For radios and checkboxes, pass only 1 element- the class will find it's siblings with the same name attribute.
@param {_internal.validatorsNameOptionsTuple[]} validatorsNameOptionsTuples <b> the order matters- the input's state is the first {@link _internal.validatorsNameOptionsTuple validatorsNameOptionsTuple} that evulates to a non-valid (pending or invalid) state. </b>
@param {function} [onInputValidationResult] Signature of {@link _internal.onInputValidationResult onInputValidationResult}. A function to handle an input state or message change. If not passed, {@link _internal.defaultOnInputValidationResult defaultOnInputValidationResult} will be used.
@param {boolean} isBlurOnly if true, doesn't not trigger validation on 'input' or 'change' events. | [
"creates",
"a",
"new",
"Input",
"object",
"wrapping",
"around",
"a",
"DOM",
"object",
"."
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/input.js#L21-L113 |
41,186 | basic-web-components/basic-web-components | packages/basic-component-mixins/src/TimerSelectionMixin.js | selectNextWithWrap | function selectNextWithWrap(element) {
const items = element.items;
if (items && items.length > 0) {
if (element.selectedIndex == null || element.selectedIndex === items.length - 1) {
element.selectFirst();
} else {
element.selectNext();
}
}
} | javascript | function selectNextWithWrap(element) {
const items = element.items;
if (items && items.length > 0) {
if (element.selectedIndex == null || element.selectedIndex === items.length - 1) {
element.selectFirst();
} else {
element.selectNext();
}
}
} | [
"function",
"selectNextWithWrap",
"(",
"element",
")",
"{",
"const",
"items",
"=",
"element",
".",
"items",
";",
"if",
"(",
"items",
"&&",
"items",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"element",
".",
"selectedIndex",
"==",
"null",
"||",
"element",
".",
"selectedIndex",
"===",
"items",
".",
"length",
"-",
"1",
")",
"{",
"element",
".",
"selectFirst",
"(",
")",
";",
"}",
"else",
"{",
"element",
".",
"selectNext",
"(",
")",
";",
"}",
"}",
"}"
]
| Select the next item, wrapping to first item if necessary. | [
"Select",
"the",
"next",
"item",
"wrapping",
"to",
"first",
"item",
"if",
"necessary",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/TimerSelectionMixin.js#L155-L164 |
41,187 | abdulhannanali/jest-nyan-reporter | helpers.js | printFailureMessages | function printFailureMessages(results) {
if (!results.numTotalTests || !results.numFailedTests) {
return;
}
console.log(color('bright fail', ` ${symbols.err} Failed Tests:`));
console.log('\n');
results.testResults.forEach(({failureMessage}) => {
if (failureMessage) {
console.log(failureMessage);
}
});
process.stdout.write('\n');
} | javascript | function printFailureMessages(results) {
if (!results.numTotalTests || !results.numFailedTests) {
return;
}
console.log(color('bright fail', ` ${symbols.err} Failed Tests:`));
console.log('\n');
results.testResults.forEach(({failureMessage}) => {
if (failureMessage) {
console.log(failureMessage);
}
});
process.stdout.write('\n');
} | [
"function",
"printFailureMessages",
"(",
"results",
")",
"{",
"if",
"(",
"!",
"results",
".",
"numTotalTests",
"||",
"!",
"results",
".",
"numFailedTests",
")",
"{",
"return",
";",
"}",
"console",
".",
"log",
"(",
"color",
"(",
"'bright fail'",
",",
"`",
"${",
"symbols",
".",
"err",
"}",
"`",
")",
")",
";",
"console",
".",
"log",
"(",
"'\\n'",
")",
";",
"results",
".",
"testResults",
".",
"forEach",
"(",
"(",
"{",
"failureMessage",
"}",
")",
"=>",
"{",
"if",
"(",
"failureMessage",
")",
"{",
"console",
".",
"log",
"(",
"failureMessage",
")",
";",
"}",
"}",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
";",
"}"
]
| Prints failure messsages for the reporters to be displayed | [
"Prints",
"failure",
"messsages",
"for",
"the",
"reporters",
"to",
"be",
"displayed"
]
| 28f121bdb64a340655f3bc6151ff02b55c3d8fd7 | https://github.com/abdulhannanali/jest-nyan-reporter/blob/28f121bdb64a340655f3bc6151ff02b55c3d8fd7/helpers.js#L118-L133 |
41,188 | basic-web-components/basic-web-components | Gruntfile.js | buildDocsList | function buildDocsList() {
const packagesWithoutBuiltDocs = [
'basic-component-mixins',
'basic-web-components'
];
const ary = allPackages.filter(item => {
return packagesWithoutBuiltDocs.indexOf(item) < 0;
}).map(item => {
return {
src: `packages/${item}/src/*.js`,
dest: `packages/${item}/README.md`};
});
return ary.concat(buildMixinsDocsList());
} | javascript | function buildDocsList() {
const packagesWithoutBuiltDocs = [
'basic-component-mixins',
'basic-web-components'
];
const ary = allPackages.filter(item => {
return packagesWithoutBuiltDocs.indexOf(item) < 0;
}).map(item => {
return {
src: `packages/${item}/src/*.js`,
dest: `packages/${item}/README.md`};
});
return ary.concat(buildMixinsDocsList());
} | [
"function",
"buildDocsList",
"(",
")",
"{",
"const",
"packagesWithoutBuiltDocs",
"=",
"[",
"'basic-component-mixins'",
",",
"'basic-web-components'",
"]",
";",
"const",
"ary",
"=",
"allPackages",
".",
"filter",
"(",
"item",
"=>",
"{",
"return",
"packagesWithoutBuiltDocs",
".",
"indexOf",
"(",
"item",
")",
"<",
"0",
";",
"}",
")",
".",
"map",
"(",
"item",
"=>",
"{",
"return",
"{",
"src",
":",
"`",
"${",
"item",
"}",
"`",
",",
"dest",
":",
"`",
"${",
"item",
"}",
"`",
"}",
";",
"}",
")",
";",
"return",
"ary",
".",
"concat",
"(",
"buildMixinsDocsList",
"(",
")",
")",
";",
"}"
]
| Build the global docsList array for use in building the package's README.md documentation | [
"Build",
"the",
"global",
"docsList",
"array",
"for",
"use",
"in",
"building",
"the",
"package",
"s",
"README",
".",
"md",
"documentation"
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/Gruntfile.js#L50-L64 |
41,189 | basic-web-components/basic-web-components | Gruntfile.js | buildMixinsDocsList | function buildMixinsDocsList() {
return fs.readdirSync('packages/basic-component-mixins/src').filter(file => {
return file.indexOf('.js') == file.length - 3;
}).map(file => {
const fileRoot = file.replace('.js', '');
return {
src: `packages/basic-component-mixins/src/${file}`,
dest: `packages/basic-component-mixins/docs/${fileRoot}.md` };
});
} | javascript | function buildMixinsDocsList() {
return fs.readdirSync('packages/basic-component-mixins/src').filter(file => {
return file.indexOf('.js') == file.length - 3;
}).map(file => {
const fileRoot = file.replace('.js', '');
return {
src: `packages/basic-component-mixins/src/${file}`,
dest: `packages/basic-component-mixins/docs/${fileRoot}.md` };
});
} | [
"function",
"buildMixinsDocsList",
"(",
")",
"{",
"return",
"fs",
".",
"readdirSync",
"(",
"'packages/basic-component-mixins/src'",
")",
".",
"filter",
"(",
"file",
"=>",
"{",
"return",
"file",
".",
"indexOf",
"(",
"'.js'",
")",
"==",
"file",
".",
"length",
"-",
"3",
";",
"}",
")",
".",
"map",
"(",
"file",
"=>",
"{",
"const",
"fileRoot",
"=",
"file",
".",
"replace",
"(",
"'.js'",
",",
"''",
")",
";",
"return",
"{",
"src",
":",
"`",
"${",
"file",
"}",
"`",
",",
"dest",
":",
"`",
"${",
"fileRoot",
"}",
"`",
"}",
";",
"}",
")",
";",
"}"
]
| Build the portion of docsList that represents the individual source files within the basic-component-mixins directory. | [
"Build",
"the",
"portion",
"of",
"docsList",
"that",
"represents",
"the",
"individual",
"source",
"files",
"within",
"the",
"basic",
"-",
"component",
"-",
"mixins",
"directory",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/Gruntfile.js#L71-L80 |
41,190 | basic-web-components/basic-web-components | packages/demos/bower_components/custom-elements/src/custom-elements.js | _createElement | function _createElement(doc, tagName, options, callConstructor) {
const customElements = _customElements();
const element = options ? _origCreateElement.call(doc, tagName, options) :
_origCreateElement.call(doc, tagName);
const definition = customElements._definitions.get(tagName.toLowerCase());
if (definition) {
customElements._upgradeElement(element, definition, callConstructor);
}
customElements._observeRoot(element);
return element;
} | javascript | function _createElement(doc, tagName, options, callConstructor) {
const customElements = _customElements();
const element = options ? _origCreateElement.call(doc, tagName, options) :
_origCreateElement.call(doc, tagName);
const definition = customElements._definitions.get(tagName.toLowerCase());
if (definition) {
customElements._upgradeElement(element, definition, callConstructor);
}
customElements._observeRoot(element);
return element;
} | [
"function",
"_createElement",
"(",
"doc",
",",
"tagName",
",",
"options",
",",
"callConstructor",
")",
"{",
"const",
"customElements",
"=",
"_customElements",
"(",
")",
";",
"const",
"element",
"=",
"options",
"?",
"_origCreateElement",
".",
"call",
"(",
"doc",
",",
"tagName",
",",
"options",
")",
":",
"_origCreateElement",
".",
"call",
"(",
"doc",
",",
"tagName",
")",
";",
"const",
"definition",
"=",
"customElements",
".",
"_definitions",
".",
"get",
"(",
"tagName",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"definition",
")",
"{",
"customElements",
".",
"_upgradeElement",
"(",
"element",
",",
"definition",
",",
"callConstructor",
")",
";",
"}",
"customElements",
".",
"_observeRoot",
"(",
"element",
")",
";",
"return",
"element",
";",
"}"
]
| Creates a new element and upgrades it if it's a custom element.
@param {!Document} doc
@param {!string} tagName
@param {Object|undefined} options
@param {boolean} callConstructor whether or not to call the elements
constructor after upgrading. If an element is created by calling its
constructor, then `callConstructor` should be false to prevent double
initialization. | [
"Creates",
"a",
"new",
"element",
"and",
"upgrades",
"it",
"if",
"it",
"s",
"a",
"custom",
"element",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/custom-elements/src/custom-elements.js#L698-L708 |
41,191 | micromatch/parse-glob | index.js | dotdir | function dotdir(base) {
if (base.indexOf('/.') !== -1) {
return true;
}
if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
return true;
}
return false;
} | javascript | function dotdir(base) {
if (base.indexOf('/.') !== -1) {
return true;
}
if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
return true;
}
return false;
} | [
"function",
"dotdir",
"(",
"base",
")",
"{",
"if",
"(",
"base",
".",
"indexOf",
"(",
"'/.'",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"base",
".",
"charAt",
"(",
"0",
")",
"===",
"'.'",
"&&",
"base",
".",
"charAt",
"(",
"1",
")",
"!==",
"'/'",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Returns true if the glob matches dot-directories.
@param {Object} `tok` The tokens object
@param {Object} `path` The path object
@return {Object} | [
"Returns",
"true",
"if",
"the",
"glob",
"matches",
"dot",
"-",
"directories",
"."
]
| 9bfccb63acdeb3b1ed62035b3adef0e5081d8fc6 | https://github.com/micromatch/parse-glob/blob/9bfccb63acdeb3b1ed62035b3adef0e5081d8fc6/index.js#L111-L119 |
41,192 | laardee/serverless-authentication | src/profile.js | formatAddress | function formatAddress(address) {
const result = address
if (result) {
result.formatted =
`${result.street_address}\n${result.postal_code} ${result.locality}\n${result.country}`
return result
}
return null
} | javascript | function formatAddress(address) {
const result = address
if (result) {
result.formatted =
`${result.street_address}\n${result.postal_code} ${result.locality}\n${result.country}`
return result
}
return null
} | [
"function",
"formatAddress",
"(",
"address",
")",
"{",
"const",
"result",
"=",
"address",
"if",
"(",
"result",
")",
"{",
"result",
".",
"formatted",
"=",
"`",
"${",
"result",
".",
"street_address",
"}",
"\\n",
"${",
"result",
".",
"postal_code",
"}",
"${",
"result",
".",
"locality",
"}",
"\\n",
"${",
"result",
".",
"country",
"}",
"`",
"return",
"result",
"}",
"return",
"null",
"}"
]
| Profile class that normalizes profile data fetched from authentication provider | [
"Profile",
"class",
"that",
"normalizes",
"profile",
"data",
"fetched",
"from",
"authentication",
"provider"
]
| 92026681c88020f0282939ec6f1b9a82da51f537 | https://github.com/laardee/serverless-authentication/blob/92026681c88020f0282939ec6f1b9a82da51f537/src/profile.js#L5-L13 |
41,193 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | arrayCopyChildNodes | function arrayCopyChildNodes(parent) {
var copy=[], i=0;
for (var n=parent.firstChild; n; n=n.nextSibling) {
copy[i++] = n;
}
return copy;
} | javascript | function arrayCopyChildNodes(parent) {
var copy=[], i=0;
for (var n=parent.firstChild; n; n=n.nextSibling) {
copy[i++] = n;
}
return copy;
} | [
"function",
"arrayCopyChildNodes",
"(",
"parent",
")",
"{",
"var",
"copy",
"=",
"[",
"]",
",",
"i",
"=",
"0",
";",
"for",
"(",
"var",
"n",
"=",
"parent",
".",
"firstChild",
";",
"n",
";",
"n",
"=",
"n",
".",
"nextSibling",
")",
"{",
"copy",
"[",
"i",
"++",
"]",
"=",
"n",
";",
"}",
"return",
"copy",
";",
"}"
]
| sad but faster than slice... | [
"sad",
"but",
"faster",
"than",
"slice",
"..."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L390-L396 |
41,194 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | saveChildNodes$1 | function saveChildNodes$1(node) {
if (!this.hasChildNodes(node)) {
node.__dom = node.__dom || {};
node.__dom.firstChild = node.firstChild;
node.__dom.lastChild = node.lastChild;
var c$ = node.__dom.childNodes = tree.arrayCopyChildNodes(node);
for (var i=0, n; (i<c$.length) && (n=c$[i]); i++) {
n.__dom = n.__dom || {};
n.__dom.parentNode = node;
n.__dom.nextSibling = c$[i+1] || null;
n.__dom.previousSibling = c$[i-1] || null;
common.patchNode(n);
}
}
} | javascript | function saveChildNodes$1(node) {
if (!this.hasChildNodes(node)) {
node.__dom = node.__dom || {};
node.__dom.firstChild = node.firstChild;
node.__dom.lastChild = node.lastChild;
var c$ = node.__dom.childNodes = tree.arrayCopyChildNodes(node);
for (var i=0, n; (i<c$.length) && (n=c$[i]); i++) {
n.__dom = n.__dom || {};
n.__dom.parentNode = node;
n.__dom.nextSibling = c$[i+1] || null;
n.__dom.previousSibling = c$[i-1] || null;
common.patchNode(n);
}
}
} | [
"function",
"saveChildNodes$1",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"this",
".",
"hasChildNodes",
"(",
"node",
")",
")",
"{",
"node",
".",
"__dom",
"=",
"node",
".",
"__dom",
"||",
"{",
"}",
";",
"node",
".",
"__dom",
".",
"firstChild",
"=",
"node",
".",
"firstChild",
";",
"node",
".",
"__dom",
".",
"lastChild",
"=",
"node",
".",
"lastChild",
";",
"var",
"c$",
"=",
"node",
".",
"__dom",
".",
"childNodes",
"=",
"tree",
".",
"arrayCopyChildNodes",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
";",
"(",
"i",
"<",
"c$",
".",
"length",
")",
"&&",
"(",
"n",
"=",
"c$",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"n",
".",
"__dom",
"=",
"n",
".",
"__dom",
"||",
"{",
"}",
";",
"n",
".",
"__dom",
".",
"parentNode",
"=",
"node",
";",
"n",
".",
"__dom",
".",
"nextSibling",
"=",
"c$",
"[",
"i",
"+",
"1",
"]",
"||",
"null",
";",
"n",
".",
"__dom",
".",
"previousSibling",
"=",
"c$",
"[",
"i",
"-",
"1",
"]",
"||",
"null",
";",
"common",
".",
"patchNode",
"(",
"n",
")",
";",
"}",
"}",
"}"
]
| Capture the list of light children. It's important to do this before we start transforming the DOM into "rendered" state. Children may be added to this list dynamically. It will be treated as the source of truth for the light children of the element. This element's actual children will be treated as the rendered state once this function has been called. | [
"Capture",
"the",
"list",
"of",
"light",
"children",
".",
"It",
"s",
"important",
"to",
"do",
"this",
"before",
"we",
"start",
"transforming",
"the",
"DOM",
"into",
"rendered",
"state",
".",
"Children",
"may",
"be",
"added",
"to",
"this",
"list",
"dynamically",
".",
"It",
"will",
"be",
"treated",
"as",
"the",
"source",
"of",
"truth",
"for",
"the",
"light",
"children",
"of",
"the",
"element",
".",
"This",
"element",
"s",
"actual",
"children",
"will",
"be",
"treated",
"as",
"the",
"rendered",
"state",
"once",
"this",
"function",
"has",
"been",
"called",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L552-L566 |
41,195 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _elementNeedsDistribution | function _elementNeedsDistribution(element) {
var this$1 = this;
var c$ = tree.Logical.getChildNodes(element);
for (var i=0, c; i < c$.length; i++) {
c = c$[i];
if (this$1._distributor.isInsertionPoint(c)) {
return element.getRootNode();
}
}
} | javascript | function _elementNeedsDistribution(element) {
var this$1 = this;
var c$ = tree.Logical.getChildNodes(element);
for (var i=0, c; i < c$.length; i++) {
c = c$[i];
if (this$1._distributor.isInsertionPoint(c)) {
return element.getRootNode();
}
}
} | [
"function",
"_elementNeedsDistribution",
"(",
"element",
")",
"{",
"var",
"this$1",
"=",
"this",
";",
"var",
"c$",
"=",
"tree",
".",
"Logical",
".",
"getChildNodes",
"(",
"element",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"c",
";",
"i",
"<",
"c$",
".",
"length",
";",
"i",
"++",
")",
"{",
"c",
"=",
"c$",
"[",
"i",
"]",
";",
"if",
"(",
"this$1",
".",
"_distributor",
".",
"isInsertionPoint",
"(",
"c",
")",
")",
"{",
"return",
"element",
".",
"getRootNode",
"(",
")",
";",
"}",
"}",
"}"
]
| Return true if a host's children includes an insertion point that selects selectively | [
"Return",
"true",
"if",
"a",
"host",
"s",
"children",
"includes",
"an",
"insertion",
"point",
"that",
"selects",
"selectively"
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1233-L1243 |
41,196 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _composeTree | function _composeTree() {
var this$1 = this;
this._updateChildNodes(this.host, this._composeNode(this.host));
var p$ = this._insertionPoints || [];
for (var i=0, l=p$.length, p, parent; (i<l) && (p=p$[i]); i++) {
parent = tree.Logical.getParentNode(p);
if ((parent !== this$1.host) && (parent !== this$1)) {
this$1._updateChildNodes(parent, this$1._composeNode(parent));
}
}
} | javascript | function _composeTree() {
var this$1 = this;
this._updateChildNodes(this.host, this._composeNode(this.host));
var p$ = this._insertionPoints || [];
for (var i=0, l=p$.length, p, parent; (i<l) && (p=p$[i]); i++) {
parent = tree.Logical.getParentNode(p);
if ((parent !== this$1.host) && (parent !== this$1)) {
this$1._updateChildNodes(parent, this$1._composeNode(parent));
}
}
} | [
"function",
"_composeTree",
"(",
")",
"{",
"var",
"this$1",
"=",
"this",
";",
"this",
".",
"_updateChildNodes",
"(",
"this",
".",
"host",
",",
"this",
".",
"_composeNode",
"(",
"this",
".",
"host",
")",
")",
";",
"var",
"p$",
"=",
"this",
".",
"_insertionPoints",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"p$",
".",
"length",
",",
"p",
",",
"parent",
";",
"(",
"i",
"<",
"l",
")",
"&&",
"(",
"p",
"=",
"p$",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"parent",
"=",
"tree",
".",
"Logical",
".",
"getParentNode",
"(",
"p",
")",
";",
"if",
"(",
"(",
"parent",
"!==",
"this$1",
".",
"host",
")",
"&&",
"(",
"parent",
"!==",
"this$1",
")",
")",
"{",
"this$1",
".",
"_updateChildNodes",
"(",
"parent",
",",
"this$1",
".",
"_composeNode",
"(",
"parent",
")",
")",
";",
"}",
"}",
"}"
]
| Reify dom such that it is at its correct rendering position based on logical distribution. | [
"Reify",
"dom",
"such",
"that",
"it",
"is",
"at",
"its",
"correct",
"rendering",
"position",
"based",
"on",
"logical",
"distribution",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1339-L1350 |
41,197 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _composeNode | function _composeNode(node) {
var this$1 = this;
var children = [];
var c$ = tree.Logical.getChildNodes(node.shadyRoot || node);
for (var i = 0; i < c$.length; i++) {
var child = c$[i];
if (this$1._distributor.isInsertionPoint(child)) {
var distributedNodes = child._distributedNodes ||
(child._distributedNodes = []);
for (var j = 0; j < distributedNodes.length; j++) {
var distributedNode = distributedNodes[j];
if (this$1.isFinalDestination(child, distributedNode)) {
children.push(distributedNode);
}
}
} else {
children.push(child);
}
}
return children;
} | javascript | function _composeNode(node) {
var this$1 = this;
var children = [];
var c$ = tree.Logical.getChildNodes(node.shadyRoot || node);
for (var i = 0; i < c$.length; i++) {
var child = c$[i];
if (this$1._distributor.isInsertionPoint(child)) {
var distributedNodes = child._distributedNodes ||
(child._distributedNodes = []);
for (var j = 0; j < distributedNodes.length; j++) {
var distributedNode = distributedNodes[j];
if (this$1.isFinalDestination(child, distributedNode)) {
children.push(distributedNode);
}
}
} else {
children.push(child);
}
}
return children;
} | [
"function",
"_composeNode",
"(",
"node",
")",
"{",
"var",
"this$1",
"=",
"this",
";",
"var",
"children",
"=",
"[",
"]",
";",
"var",
"c$",
"=",
"tree",
".",
"Logical",
".",
"getChildNodes",
"(",
"node",
".",
"shadyRoot",
"||",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c$",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"child",
"=",
"c$",
"[",
"i",
"]",
";",
"if",
"(",
"this$1",
".",
"_distributor",
".",
"isInsertionPoint",
"(",
"child",
")",
")",
"{",
"var",
"distributedNodes",
"=",
"child",
".",
"_distributedNodes",
"||",
"(",
"child",
".",
"_distributedNodes",
"=",
"[",
"]",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"distributedNodes",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"distributedNode",
"=",
"distributedNodes",
"[",
"j",
"]",
";",
"if",
"(",
"this$1",
".",
"isFinalDestination",
"(",
"child",
",",
"distributedNode",
")",
")",
"{",
"children",
".",
"push",
"(",
"distributedNode",
")",
";",
"}",
"}",
"}",
"else",
"{",
"children",
".",
"push",
"(",
"child",
")",
";",
"}",
"}",
"return",
"children",
";",
"}"
]
| Returns the list of nodes which should be rendered inside `node`. | [
"Returns",
"the",
"list",
"of",
"nodes",
"which",
"should",
"be",
"rendered",
"inside",
"node",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1353-L1374 |
41,198 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _updateChildNodes | function _updateChildNodes(container, children) {
var composed = tree.Composed.getChildNodes(container);
var splices = calculateSplices(children, composed);
// process removals
for (var i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) {
for (var j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) {
// check if the node is still where we expect it is before trying
// to remove it; this can happen if we move a node and
// then schedule its previous host for distribution resulting in
// the node being removed here.
if (tree.Composed.getParentNode(n) === container) {
tree.Composed.removeChild(container, n);
}
composed.splice(s.index + d, 1);
}
d -= s.addedCount;
}
// process adds
for (var i$1=0, s$1, next; (i$1<splices.length) && (s$1=splices[i$1]); i$1++) { //eslint-disable-line no-redeclare
next = composed[s$1.index];
for (var j$1=s$1.index, n$1; j$1 < s$1.index + s$1.addedCount; j$1++) {
n$1 = children[j$1];
tree.Composed.insertBefore(container, n$1, next);
// TODO(sorvell): is this splice strictly needed?
composed.splice(j$1, 0, n$1);
}
}
} | javascript | function _updateChildNodes(container, children) {
var composed = tree.Composed.getChildNodes(container);
var splices = calculateSplices(children, composed);
// process removals
for (var i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) {
for (var j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) {
// check if the node is still where we expect it is before trying
// to remove it; this can happen if we move a node and
// then schedule its previous host for distribution resulting in
// the node being removed here.
if (tree.Composed.getParentNode(n) === container) {
tree.Composed.removeChild(container, n);
}
composed.splice(s.index + d, 1);
}
d -= s.addedCount;
}
// process adds
for (var i$1=0, s$1, next; (i$1<splices.length) && (s$1=splices[i$1]); i$1++) { //eslint-disable-line no-redeclare
next = composed[s$1.index];
for (var j$1=s$1.index, n$1; j$1 < s$1.index + s$1.addedCount; j$1++) {
n$1 = children[j$1];
tree.Composed.insertBefore(container, n$1, next);
// TODO(sorvell): is this splice strictly needed?
composed.splice(j$1, 0, n$1);
}
}
} | [
"function",
"_updateChildNodes",
"(",
"container",
",",
"children",
")",
"{",
"var",
"composed",
"=",
"tree",
".",
"Composed",
".",
"getChildNodes",
"(",
"container",
")",
";",
"var",
"splices",
"=",
"calculateSplices",
"(",
"children",
",",
"composed",
")",
";",
"// process removals",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"d",
"=",
"0",
",",
"s",
";",
"(",
"i",
"<",
"splices",
".",
"length",
")",
"&&",
"(",
"s",
"=",
"splices",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"n",
";",
"(",
"j",
"<",
"s",
".",
"removed",
".",
"length",
")",
"&&",
"(",
"n",
"=",
"s",
".",
"removed",
"[",
"j",
"]",
")",
";",
"j",
"++",
")",
"{",
"// check if the node is still where we expect it is before trying",
"// to remove it; this can happen if we move a node and",
"// then schedule its previous host for distribution resulting in",
"// the node being removed here.",
"if",
"(",
"tree",
".",
"Composed",
".",
"getParentNode",
"(",
"n",
")",
"===",
"container",
")",
"{",
"tree",
".",
"Composed",
".",
"removeChild",
"(",
"container",
",",
"n",
")",
";",
"}",
"composed",
".",
"splice",
"(",
"s",
".",
"index",
"+",
"d",
",",
"1",
")",
";",
"}",
"d",
"-=",
"s",
".",
"addedCount",
";",
"}",
"// process adds",
"for",
"(",
"var",
"i$1",
"=",
"0",
",",
"s$1",
",",
"next",
";",
"(",
"i$1",
"<",
"splices",
".",
"length",
")",
"&&",
"(",
"s$1",
"=",
"splices",
"[",
"i$1",
"]",
")",
";",
"i$1",
"++",
")",
"{",
"//eslint-disable-line no-redeclare",
"next",
"=",
"composed",
"[",
"s$1",
".",
"index",
"]",
";",
"for",
"(",
"var",
"j$1",
"=",
"s$1",
".",
"index",
",",
"n$1",
";",
"j$1",
"<",
"s$1",
".",
"index",
"+",
"s$1",
".",
"addedCount",
";",
"j$1",
"++",
")",
"{",
"n$1",
"=",
"children",
"[",
"j$1",
"]",
";",
"tree",
".",
"Composed",
".",
"insertBefore",
"(",
"container",
",",
"n$1",
",",
"next",
")",
";",
"// TODO(sorvell): is this splice strictly needed?",
"composed",
".",
"splice",
"(",
"j$1",
",",
"0",
",",
"n$1",
")",
";",
"}",
"}",
"}"
]
| Ensures that the rendered node list inside `container` is `children`. | [
"Ensures",
"that",
"the",
"rendered",
"node",
"list",
"inside",
"container",
"is",
"children",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1382-L1409 |
41,199 | basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | addNode | function addNode(container, node, ref_node) {
var ownerRoot = this.ownerShadyRootForNode(container);
if (ownerRoot) {
// optimization: special insertion point tracking
if (node.__noInsertionPoint && ownerRoot._clean) {
ownerRoot._skipUpdateInsertionPoints = true;
}
// note: we always need to see if an insertion point is added
// since this saves logical tree info; however, invalidation state
// needs
var ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot);
// invalidate insertion points IFF not already invalid!
if (ipAdded) {
ownerRoot._skipUpdateInsertionPoints = false;
}
}
if (tree.Logical.hasChildNodes(container)) {
tree.Logical.recordInsertBefore(node, container, ref_node);
}
// if not distributing and not adding to host, do a fast path addition
var handled = this._maybeDistribute(node, container, ownerRoot) ||
container.shadyRoot;
return handled;
} | javascript | function addNode(container, node, ref_node) {
var ownerRoot = this.ownerShadyRootForNode(container);
if (ownerRoot) {
// optimization: special insertion point tracking
if (node.__noInsertionPoint && ownerRoot._clean) {
ownerRoot._skipUpdateInsertionPoints = true;
}
// note: we always need to see if an insertion point is added
// since this saves logical tree info; however, invalidation state
// needs
var ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot);
// invalidate insertion points IFF not already invalid!
if (ipAdded) {
ownerRoot._skipUpdateInsertionPoints = false;
}
}
if (tree.Logical.hasChildNodes(container)) {
tree.Logical.recordInsertBefore(node, container, ref_node);
}
// if not distributing and not adding to host, do a fast path addition
var handled = this._maybeDistribute(node, container, ownerRoot) ||
container.shadyRoot;
return handled;
} | [
"function",
"addNode",
"(",
"container",
",",
"node",
",",
"ref_node",
")",
"{",
"var",
"ownerRoot",
"=",
"this",
".",
"ownerShadyRootForNode",
"(",
"container",
")",
";",
"if",
"(",
"ownerRoot",
")",
"{",
"// optimization: special insertion point tracking",
"if",
"(",
"node",
".",
"__noInsertionPoint",
"&&",
"ownerRoot",
".",
"_clean",
")",
"{",
"ownerRoot",
".",
"_skipUpdateInsertionPoints",
"=",
"true",
";",
"}",
"// note: we always need to see if an insertion point is added",
"// since this saves logical tree info; however, invalidation state",
"// needs",
"var",
"ipAdded",
"=",
"this",
".",
"_maybeAddInsertionPoint",
"(",
"node",
",",
"container",
",",
"ownerRoot",
")",
";",
"// invalidate insertion points IFF not already invalid!",
"if",
"(",
"ipAdded",
")",
"{",
"ownerRoot",
".",
"_skipUpdateInsertionPoints",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"tree",
".",
"Logical",
".",
"hasChildNodes",
"(",
"container",
")",
")",
"{",
"tree",
".",
"Logical",
".",
"recordInsertBefore",
"(",
"node",
",",
"container",
",",
"ref_node",
")",
";",
"}",
"// if not distributing and not adding to host, do a fast path addition",
"var",
"handled",
"=",
"this",
".",
"_maybeDistribute",
"(",
"node",
",",
"container",
",",
"ownerRoot",
")",
"||",
"container",
".",
"shadyRoot",
";",
"return",
"handled",
";",
"}"
]
| Try to add node. Record logical info, track insertion points, perform distribution iff needed. Return true if the add is handled. | [
"Try",
"to",
"add",
"node",
".",
"Record",
"logical",
"info",
"track",
"insertion",
"points",
"perform",
"distribution",
"iff",
"needed",
".",
"Return",
"true",
"if",
"the",
"add",
"is",
"handled",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1605-L1628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.