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
|
---|---|---|---|---|---|---|---|---|---|---|---|
45,800 | solid/solid-auth-tls | src/auth.js | loginFromBrowser | function loginFromBrowser (endpoint, config) {
let uri
switch (endpoint) {
case AUTH_ENDPOINTS.PRIMARY:
uri = config.authEndpoint || window.location.origin + window.location.pathname
break
case AUTH_ENDPOINTS.SECONDARY:
uri = config.fallbackAuthEndpoint
break
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.addEventListener('load', () => {
resolve(xhr.getResponseHeader('user') || null)
})
xhr.addEventListener('error', err => {
reject(err)
})
xhr.open('HEAD', uri)
xhr.send()
})
} | javascript | function loginFromBrowser (endpoint, config) {
let uri
switch (endpoint) {
case AUTH_ENDPOINTS.PRIMARY:
uri = config.authEndpoint || window.location.origin + window.location.pathname
break
case AUTH_ENDPOINTS.SECONDARY:
uri = config.fallbackAuthEndpoint
break
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.addEventListener('load', () => {
resolve(xhr.getResponseHeader('user') || null)
})
xhr.addEventListener('error', err => {
reject(err)
})
xhr.open('HEAD', uri)
xhr.send()
})
} | [
"function",
"loginFromBrowser",
"(",
"endpoint",
",",
"config",
")",
"{",
"let",
"uri",
"switch",
"(",
"endpoint",
")",
"{",
"case",
"AUTH_ENDPOINTS",
".",
"PRIMARY",
":",
"uri",
"=",
"config",
".",
"authEndpoint",
"||",
"window",
".",
"location",
".",
"origin",
"+",
"window",
".",
"location",
".",
"pathname",
"break",
"case",
"AUTH_ENDPOINTS",
".",
"SECONDARY",
":",
"uri",
"=",
"config",
".",
"fallbackAuthEndpoint",
"break",
"}",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"xhr",
"=",
"new",
"XMLHttpRequest",
"(",
")",
"xhr",
".",
"withCredentials",
"=",
"true",
"xhr",
".",
"addEventListener",
"(",
"'load'",
",",
"(",
")",
"=>",
"{",
"resolve",
"(",
"xhr",
".",
"getResponseHeader",
"(",
"'user'",
")",
"||",
"null",
")",
"}",
")",
"xhr",
".",
"addEventListener",
"(",
"'error'",
",",
"err",
"=>",
"{",
"reject",
"(",
"err",
")",
"}",
")",
"xhr",
".",
"open",
"(",
"'HEAD'",
",",
"uri",
")",
"xhr",
".",
"send",
"(",
")",
"}",
")",
"}"
]
| Logs in to the specified endpoint from within the browser
@param {AUTH_ENDPOINTS} endpoint - the endpoint type
@param {@link module:config-default} config - the config object
@returns {(Promise<String>|Promise<null>)} the WebID as a string if the
client cert is recognized, otherwise null. | [
"Logs",
"in",
"to",
"the",
"specified",
"endpoint",
"from",
"within",
"the",
"browser"
]
| a27dea9c29778db936adf48be8042895af3a8f43 | https://github.com/solid/solid-auth-tls/blob/a27dea9c29778db936adf48be8042895af3a8f43/src/auth.js#L73-L97 |
45,801 | solid/solid-auth-tls | src/auth.js | loginFromNode | function loginFromNode (endpoint, config) {
if (!(config.key && config.cert)) {
throw new Error('Must provide TLS key and cert when running in node')
}
let uri
switch (endpoint) {
case AUTH_ENDPOINTS.PRIMARY:
uri = config.authEndpoint
break
case AUTH_ENDPOINTS.SECONDARY:
uri = config.fallbackAuthEndpoint
break
}
let fs, https, url
if (!global.IS_BROWSER) {
fs = require('fs')
https = require('https')
url = require('url')
}
return Promise.all([config.key, config.cert].map(filename =>
new Promise((resolve, reject) => {
fs.readFile(filename, (err, data) => err ? reject(err) : resolve(data))
})
)).then(([keyBuf, certBuf]) => {
const parsedUrl = url.parse(uri)
const options = {
method: 'HEAD',
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.path,
timeout: 5000,
key: keyBuf,
cert: certBuf
}
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
resolve(res.headers['user'] || null)
})
req.on('error', reject)
req.end()
})
})
} | javascript | function loginFromNode (endpoint, config) {
if (!(config.key && config.cert)) {
throw new Error('Must provide TLS key and cert when running in node')
}
let uri
switch (endpoint) {
case AUTH_ENDPOINTS.PRIMARY:
uri = config.authEndpoint
break
case AUTH_ENDPOINTS.SECONDARY:
uri = config.fallbackAuthEndpoint
break
}
let fs, https, url
if (!global.IS_BROWSER) {
fs = require('fs')
https = require('https')
url = require('url')
}
return Promise.all([config.key, config.cert].map(filename =>
new Promise((resolve, reject) => {
fs.readFile(filename, (err, data) => err ? reject(err) : resolve(data))
})
)).then(([keyBuf, certBuf]) => {
const parsedUrl = url.parse(uri)
const options = {
method: 'HEAD',
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.path,
timeout: 5000,
key: keyBuf,
cert: certBuf
}
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
resolve(res.headers['user'] || null)
})
req.on('error', reject)
req.end()
})
})
} | [
"function",
"loginFromNode",
"(",
"endpoint",
",",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"config",
".",
"key",
"&&",
"config",
".",
"cert",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Must provide TLS key and cert when running in node'",
")",
"}",
"let",
"uri",
"switch",
"(",
"endpoint",
")",
"{",
"case",
"AUTH_ENDPOINTS",
".",
"PRIMARY",
":",
"uri",
"=",
"config",
".",
"authEndpoint",
"break",
"case",
"AUTH_ENDPOINTS",
".",
"SECONDARY",
":",
"uri",
"=",
"config",
".",
"fallbackAuthEndpoint",
"break",
"}",
"let",
"fs",
",",
"https",
",",
"url",
"if",
"(",
"!",
"global",
".",
"IS_BROWSER",
")",
"{",
"fs",
"=",
"require",
"(",
"'fs'",
")",
"https",
"=",
"require",
"(",
"'https'",
")",
"url",
"=",
"require",
"(",
"'url'",
")",
"}",
"return",
"Promise",
".",
"all",
"(",
"[",
"config",
".",
"key",
",",
"config",
".",
"cert",
"]",
".",
"map",
"(",
"filename",
"=>",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"readFile",
"(",
"filename",
",",
"(",
"err",
",",
"data",
")",
"=>",
"err",
"?",
"reject",
"(",
"err",
")",
":",
"resolve",
"(",
"data",
")",
")",
"}",
")",
")",
")",
".",
"then",
"(",
"(",
"[",
"keyBuf",
",",
"certBuf",
"]",
")",
"=>",
"{",
"const",
"parsedUrl",
"=",
"url",
".",
"parse",
"(",
"uri",
")",
"const",
"options",
"=",
"{",
"method",
":",
"'HEAD'",
",",
"hostname",
":",
"parsedUrl",
".",
"hostname",
",",
"port",
":",
"parsedUrl",
".",
"port",
",",
"path",
":",
"parsedUrl",
".",
"path",
",",
"timeout",
":",
"5000",
",",
"key",
":",
"keyBuf",
",",
"cert",
":",
"certBuf",
"}",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"req",
"=",
"https",
".",
"request",
"(",
"options",
",",
"res",
"=>",
"{",
"resolve",
"(",
"res",
".",
"headers",
"[",
"'user'",
"]",
"||",
"null",
")",
"}",
")",
"req",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
"req",
".",
"end",
"(",
")",
"}",
")",
"}",
")",
"}"
]
| Logs in to the specified endpoint from within a Node.js environment
@param {AUTH_ENDPOINTS} endpoint - the endpoint type
@param {@link module:config-default} config - the config object
@returns {(Promise<String>|Promise<null>)} the WebID as a string if the
client cert is recognized, otherwise null. | [
"Logs",
"in",
"to",
"the",
"specified",
"endpoint",
"from",
"within",
"a",
"Node",
".",
"js",
"environment"
]
| a27dea9c29778db936adf48be8042895af3a8f43 | https://github.com/solid/solid-auth-tls/blob/a27dea9c29778db936adf48be8042895af3a8f43/src/auth.js#L106-L153 |
45,802 | danigb/note.midi | index.js | midi | function midi (note) {
if ((typeof note === 'number' || typeof note === 'string') &&
note > 0 && note < 128) return +note
var p = Array.isArray(note) ? note : parse(note)
if (!p || p.length < 2) return null
return p[0] * 7 + p[1] * 12 + 12
} | javascript | function midi (note) {
if ((typeof note === 'number' || typeof note === 'string') &&
note > 0 && note < 128) return +note
var p = Array.isArray(note) ? note : parse(note)
if (!p || p.length < 2) return null
return p[0] * 7 + p[1] * 12 + 12
} | [
"function",
"midi",
"(",
"note",
")",
"{",
"if",
"(",
"(",
"typeof",
"note",
"===",
"'number'",
"||",
"typeof",
"note",
"===",
"'string'",
")",
"&&",
"note",
">",
"0",
"&&",
"note",
"<",
"128",
")",
"return",
"+",
"note",
"var",
"p",
"=",
"Array",
".",
"isArray",
"(",
"note",
")",
"?",
"note",
":",
"parse",
"(",
"note",
")",
"if",
"(",
"!",
"p",
"||",
"p",
".",
"length",
"<",
"2",
")",
"return",
"null",
"return",
"p",
"[",
"0",
"]",
"*",
"7",
"+",
"p",
"[",
"1",
"]",
"*",
"12",
"+",
"12",
"}"
]
| Get the midi number of a note
If the argument passed to this function is a valid midi number, it returns it
The note can be an string in scientific notation or
[array pitch notation](https://github.com/danigb/music.array.notation)
@name midi
@function
@param {String|Array} note - the note in string or array notation
@return {Integer} the midi number
@example
midi('A4') // => 69
midi('a3') // => 57
midi([0, 2]) // => 36 (C2 in array notation)
midi(60) // => 50 | [
"Get",
"the",
"midi",
"number",
"of",
"a",
"note"
]
| 4673847d157859995d51d10c8b853ee447fca448 | https://github.com/danigb/note.midi/blob/4673847d157859995d51d10c8b853ee447fca448/index.js#L24-L30 |
45,803 | cettia/cettia-protocol | lib/socket.js | find | function find() {
// If there is no remaining URI, fires `error` and `close` event as it means that all
// tries failed.
if (uris.length === 0) {
// Now that `connecting` event is being fired, there is no `error` and `close` event user
// added. Delays to fire them a little while.
setTimeout(function() {
self.emit("error", new Error());
self.emit("close");
}, 0);
return;
}
// A temporal variable to be used while finding working one.
var testTransport;
// Get the first uri by removing it from `uris`. For example, `[1,2].shift()` returns `1`
// and make the array `[2]`.
var uri = uris.shift();
// Transport handles only the specific types of URIs. It finds which transport factory can
// handle this `uri` among ones specified by `transports` option.
for (var i = 0; i < options.transports.length; i++) {
// A transport factory creates and returns a transport object if it can handle the given
// URI and nothing if not.
testTransport = options.transports[i](uri, options);
// If the factory handles this type of URI,
if (testTransport) {
break;
}
}
// If there is no transport matching with the given URI, try with the next URI.
if (!testTransport) {
find();
return;
}
// This is to stop the whole process to find a working transport when the `close` method
// is called before `open` event.
function stop() {
testTransport.removeListener("close", find);
testTransport.close();
}
// Until the socket is opened, `close` method should trigger `stop` function as well.
self.once("close", stop);
// It establishes a connection.
testTransport.open();
// If it fails, it should remove stop listener and try with the next URI. These event handlers
// will be removed once this transport is recognized as working.
testTransport.on("close", function() {
self.removeListener("close", stop);
});
testTransport.on("close", find);
// Node.js kills the process by default when an `error` event is fired if there is no
// listener for it. However, a user doesn't need to be notified of an error from this
// transport being tested.
testTransport.on("error", function() {
});
// If it succeeds, it means that the process to find working transport is done. The first
// transport text message is used to handshake the socket protocol. Note that `once`
// registers one-time event handler.
testTransport.once("text", function(text) {
// The handshake output is in the form of URI. Query params starting with `cettia-`
// represent protocol header.
var headers = url.parse(text, true).query;
// The server prints an id of the socket as a `cettia-id` param, `id` header,
// every time the transport connects. If the server issues a new id,
if (id !== headers["cettia-id"]) {
// That means there was no `id` or the server socket whose id is `id` was deleted in
// the server due to long-term disconnection.
id = headers["cettia-id"];
// Fires a `new` event as a new socket is created.
self.emit("new");
}
// To maintain an alive connection, `heartbeat` is used.
options.heartbeat = +headers["cettia-heartbeat"];
// `_heartbeat` is for testing so it should be not passed from the server in production.
// The default value is `5000`.
options._heartbeat = +headers["cettia-_heartbeat"] || 5000;
// Now that the working transport is found and handshaking is completed, it stops
// a process to find a working transport by removing `close` event handler `find` and
// associates the working transport with the socket.
testTransport.removeListener("close", find);
transport = testTransport;
// When an event object is created from `text` or `binary` event,
function onevent(event) {
// Event should have the following properties:
// * `id: string`: an event identifier.
// * `type: string`: an event type.
// * `data: any`: an event data.
// * `reply: boolean`: `true` if this event requires the reply.
// If the server sends a plain event, dispatch it.
if (!event.reply) {
self.emit(event.type, event.data);
} else {
var latch;
// A function to create a function.
function reply(success) {
// A controller function.
return function(value) {
// This latch prevents double reply.
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: value, exception: !success});
}
};
}
// Here, the controller is passed to the event handler as 2nd argument and
// allows to call the server's `resolved` or `rejected` callback by sending
// `reply` event.
self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
}
}
// When the transport has received a text message from the server,
// it deserializes a text message into an event object in the JSON format and deals with it.
transport.on("text", function(text) {
onevent(JSON.parse(text));
});
// When the transport has received a binary message from the server.
// it deserializes a binary message into an event object in the
// [MessagePack](http://msgpack.org) format and deals with it.
transport.on("binary", function(binary) {
onevent(msgpack.decode(binary));
});
// When any error has occurred.
transport.on("error", function(error) {
self.emit("error", error);
});
// When the transport has been closed for any reason.
transport.on("close", function() {
self.emit("close");
});
// Now that the working transport is associated and the communication is possible,
// it removes `close` event handler `stop` and fires `open` event.
self.removeListener("close", stop);
self.emit("open");
});
} | javascript | function find() {
// If there is no remaining URI, fires `error` and `close` event as it means that all
// tries failed.
if (uris.length === 0) {
// Now that `connecting` event is being fired, there is no `error` and `close` event user
// added. Delays to fire them a little while.
setTimeout(function() {
self.emit("error", new Error());
self.emit("close");
}, 0);
return;
}
// A temporal variable to be used while finding working one.
var testTransport;
// Get the first uri by removing it from `uris`. For example, `[1,2].shift()` returns `1`
// and make the array `[2]`.
var uri = uris.shift();
// Transport handles only the specific types of URIs. It finds which transport factory can
// handle this `uri` among ones specified by `transports` option.
for (var i = 0; i < options.transports.length; i++) {
// A transport factory creates and returns a transport object if it can handle the given
// URI and nothing if not.
testTransport = options.transports[i](uri, options);
// If the factory handles this type of URI,
if (testTransport) {
break;
}
}
// If there is no transport matching with the given URI, try with the next URI.
if (!testTransport) {
find();
return;
}
// This is to stop the whole process to find a working transport when the `close` method
// is called before `open` event.
function stop() {
testTransport.removeListener("close", find);
testTransport.close();
}
// Until the socket is opened, `close` method should trigger `stop` function as well.
self.once("close", stop);
// It establishes a connection.
testTransport.open();
// If it fails, it should remove stop listener and try with the next URI. These event handlers
// will be removed once this transport is recognized as working.
testTransport.on("close", function() {
self.removeListener("close", stop);
});
testTransport.on("close", find);
// Node.js kills the process by default when an `error` event is fired if there is no
// listener for it. However, a user doesn't need to be notified of an error from this
// transport being tested.
testTransport.on("error", function() {
});
// If it succeeds, it means that the process to find working transport is done. The first
// transport text message is used to handshake the socket protocol. Note that `once`
// registers one-time event handler.
testTransport.once("text", function(text) {
// The handshake output is in the form of URI. Query params starting with `cettia-`
// represent protocol header.
var headers = url.parse(text, true).query;
// The server prints an id of the socket as a `cettia-id` param, `id` header,
// every time the transport connects. If the server issues a new id,
if (id !== headers["cettia-id"]) {
// That means there was no `id` or the server socket whose id is `id` was deleted in
// the server due to long-term disconnection.
id = headers["cettia-id"];
// Fires a `new` event as a new socket is created.
self.emit("new");
}
// To maintain an alive connection, `heartbeat` is used.
options.heartbeat = +headers["cettia-heartbeat"];
// `_heartbeat` is for testing so it should be not passed from the server in production.
// The default value is `5000`.
options._heartbeat = +headers["cettia-_heartbeat"] || 5000;
// Now that the working transport is found and handshaking is completed, it stops
// a process to find a working transport by removing `close` event handler `find` and
// associates the working transport with the socket.
testTransport.removeListener("close", find);
transport = testTransport;
// When an event object is created from `text` or `binary` event,
function onevent(event) {
// Event should have the following properties:
// * `id: string`: an event identifier.
// * `type: string`: an event type.
// * `data: any`: an event data.
// * `reply: boolean`: `true` if this event requires the reply.
// If the server sends a plain event, dispatch it.
if (!event.reply) {
self.emit(event.type, event.data);
} else {
var latch;
// A function to create a function.
function reply(success) {
// A controller function.
return function(value) {
// This latch prevents double reply.
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: value, exception: !success});
}
};
}
// Here, the controller is passed to the event handler as 2nd argument and
// allows to call the server's `resolved` or `rejected` callback by sending
// `reply` event.
self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
}
}
// When the transport has received a text message from the server,
// it deserializes a text message into an event object in the JSON format and deals with it.
transport.on("text", function(text) {
onevent(JSON.parse(text));
});
// When the transport has received a binary message from the server.
// it deserializes a binary message into an event object in the
// [MessagePack](http://msgpack.org) format and deals with it.
transport.on("binary", function(binary) {
onevent(msgpack.decode(binary));
});
// When any error has occurred.
transport.on("error", function(error) {
self.emit("error", error);
});
// When the transport has been closed for any reason.
transport.on("close", function() {
self.emit("close");
});
// Now that the working transport is associated and the communication is possible,
// it removes `close` event handler `stop` and fires `open` event.
self.removeListener("close", stop);
self.emit("open");
});
} | [
"function",
"find",
"(",
")",
"{",
"// If there is no remaining URI, fires `error` and `close` event as it means that all",
"// tries failed.",
"if",
"(",
"uris",
".",
"length",
"===",
"0",
")",
"{",
"// Now that `connecting` event is being fired, there is no `error` and `close` event user",
"// added. Delays to fire them a little while.",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"new",
"Error",
"(",
")",
")",
";",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"}",
",",
"0",
")",
";",
"return",
";",
"}",
"// A temporal variable to be used while finding working one.",
"var",
"testTransport",
";",
"// Get the first uri by removing it from `uris`. For example, `[1,2].shift()` returns `1`",
"// and make the array `[2]`.",
"var",
"uri",
"=",
"uris",
".",
"shift",
"(",
")",
";",
"// Transport handles only the specific types of URIs. It finds which transport factory can",
"// handle this `uri` among ones specified by `transports` option.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"transports",
".",
"length",
";",
"i",
"++",
")",
"{",
"// A transport factory creates and returns a transport object if it can handle the given",
"// URI and nothing if not.",
"testTransport",
"=",
"options",
".",
"transports",
"[",
"i",
"]",
"(",
"uri",
",",
"options",
")",
";",
"// If the factory handles this type of URI,",
"if",
"(",
"testTransport",
")",
"{",
"break",
";",
"}",
"}",
"// If there is no transport matching with the given URI, try with the next URI.",
"if",
"(",
"!",
"testTransport",
")",
"{",
"find",
"(",
")",
";",
"return",
";",
"}",
"// This is to stop the whole process to find a working transport when the `close` method",
"// is called before `open` event.",
"function",
"stop",
"(",
")",
"{",
"testTransport",
".",
"removeListener",
"(",
"\"close\"",
",",
"find",
")",
";",
"testTransport",
".",
"close",
"(",
")",
";",
"}",
"// Until the socket is opened, `close` method should trigger `stop` function as well.",
"self",
".",
"once",
"(",
"\"close\"",
",",
"stop",
")",
";",
"// It establishes a connection.",
"testTransport",
".",
"open",
"(",
")",
";",
"// If it fails, it should remove stop listener and try with the next URI. These event handlers",
"// will be removed once this transport is recognized as working.",
"testTransport",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"self",
".",
"removeListener",
"(",
"\"close\"",
",",
"stop",
")",
";",
"}",
")",
";",
"testTransport",
".",
"on",
"(",
"\"close\"",
",",
"find",
")",
";",
"// Node.js kills the process by default when an `error` event is fired if there is no",
"// listener for it. However, a user doesn't need to be notified of an error from this",
"// transport being tested.",
"testTransport",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
")",
"{",
"}",
")",
";",
"// If it succeeds, it means that the process to find working transport is done. The first",
"// transport text message is used to handshake the socket protocol. Note that `once`",
"// registers one-time event handler.",
"testTransport",
".",
"once",
"(",
"\"text\"",
",",
"function",
"(",
"text",
")",
"{",
"// The handshake output is in the form of URI. Query params starting with `cettia-`",
"// represent protocol header.",
"var",
"headers",
"=",
"url",
".",
"parse",
"(",
"text",
",",
"true",
")",
".",
"query",
";",
"// The server prints an id of the socket as a `cettia-id` param, `id` header,",
"// every time the transport connects. If the server issues a new id,",
"if",
"(",
"id",
"!==",
"headers",
"[",
"\"cettia-id\"",
"]",
")",
"{",
"// That means there was no `id` or the server socket whose id is `id` was deleted in",
"// the server due to long-term disconnection.",
"id",
"=",
"headers",
"[",
"\"cettia-id\"",
"]",
";",
"// Fires a `new` event as a new socket is created.",
"self",
".",
"emit",
"(",
"\"new\"",
")",
";",
"}",
"// To maintain an alive connection, `heartbeat` is used.",
"options",
".",
"heartbeat",
"=",
"+",
"headers",
"[",
"\"cettia-heartbeat\"",
"]",
";",
"// `_heartbeat` is for testing so it should be not passed from the server in production.",
"// The default value is `5000`.",
"options",
".",
"_heartbeat",
"=",
"+",
"headers",
"[",
"\"cettia-_heartbeat\"",
"]",
"||",
"5000",
";",
"// Now that the working transport is found and handshaking is completed, it stops",
"// a process to find a working transport by removing `close` event handler `find` and",
"// associates the working transport with the socket.",
"testTransport",
".",
"removeListener",
"(",
"\"close\"",
",",
"find",
")",
";",
"transport",
"=",
"testTransport",
";",
"// When an event object is created from `text` or `binary` event,",
"function",
"onevent",
"(",
"event",
")",
"{",
"// Event should have the following properties:",
"// * `id: string`: an event identifier.",
"// * `type: string`: an event type.",
"// * `data: any`: an event data.",
"// * `reply: boolean`: `true` if this event requires the reply.",
"// If the server sends a plain event, dispatch it.",
"if",
"(",
"!",
"event",
".",
"reply",
")",
"{",
"self",
".",
"emit",
"(",
"event",
".",
"type",
",",
"event",
".",
"data",
")",
";",
"}",
"else",
"{",
"var",
"latch",
";",
"// A function to create a function.",
"function",
"reply",
"(",
"success",
")",
"{",
"// A controller function.",
"return",
"function",
"(",
"value",
")",
"{",
"// This latch prevents double reply.",
"if",
"(",
"!",
"latch",
")",
"{",
"latch",
"=",
"true",
";",
"self",
".",
"send",
"(",
"\"reply\"",
",",
"{",
"id",
":",
"event",
".",
"id",
",",
"data",
":",
"value",
",",
"exception",
":",
"!",
"success",
"}",
")",
";",
"}",
"}",
";",
"}",
"// Here, the controller is passed to the event handler as 2nd argument and",
"// allows to call the server's `resolved` or `rejected` callback by sending",
"// `reply` event.",
"self",
".",
"emit",
"(",
"event",
".",
"type",
",",
"event",
".",
"data",
",",
"{",
"resolve",
":",
"reply",
"(",
"true",
")",
",",
"reject",
":",
"reply",
"(",
"false",
")",
"}",
")",
";",
"}",
"}",
"// When the transport has received a text message from the server,",
"// it deserializes a text message into an event object in the JSON format and deals with it.",
"transport",
".",
"on",
"(",
"\"text\"",
",",
"function",
"(",
"text",
")",
"{",
"onevent",
"(",
"JSON",
".",
"parse",
"(",
"text",
")",
")",
";",
"}",
")",
";",
"// When the transport has received a binary message from the server.",
"// it deserializes a binary message into an event object in the",
"// [MessagePack](http://msgpack.org) format and deals with it.",
"transport",
".",
"on",
"(",
"\"binary\"",
",",
"function",
"(",
"binary",
")",
"{",
"onevent",
"(",
"msgpack",
".",
"decode",
"(",
"binary",
")",
")",
";",
"}",
")",
";",
"// When any error has occurred.",
"transport",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"error",
")",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"error",
")",
";",
"}",
")",
";",
"// When the transport has been closed for any reason.",
"transport",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"}",
")",
";",
"// Now that the working transport is associated and the communication is possible,",
"// it removes `close` event handler `stop` and fires `open` event.",
"self",
".",
"removeListener",
"(",
"\"close\"",
",",
"stop",
")",
";",
"self",
".",
"emit",
"(",
"\"open\"",
")",
";",
"}",
")",
";",
"}"
]
| Starts a process to find a working transport. | [
"Starts",
"a",
"process",
"to",
"find",
"a",
"working",
"transport",
"."
]
| 9af3b578a9ae7b33099932903b52faeb2ca92528 | https://github.com/cettia/cettia-protocol/blob/9af3b578a9ae7b33099932903b52faeb2ca92528/lib/socket.js#L120-L259 |
45,804 | cettia/cettia-protocol | lib/server.js | onevent | function onevent(event) {
// Event should have the following properties:
// * `id: string`: an event identifier.
// * `type: string`: an event type.
// * `data: any`: an event data.
// * `reply: boolean`: true if this event requires the reply.
// If the client sends a plain event, dispatch it.
if (!event.reply) {
self.emit(event.type, event.data);
} else {
var latch;
// A function to create a function.
function reply(success) {
// A controller function.
return function(value) {
// This latch prevents double reply.
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: value, exception: !success});
}
};
}
// Here, the controller is passed to the event handler as 2nd argument and allows
// to call the server's `resolved` or `rejected` callback by sending `reply` event.
self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
}
} | javascript | function onevent(event) {
// Event should have the following properties:
// * `id: string`: an event identifier.
// * `type: string`: an event type.
// * `data: any`: an event data.
// * `reply: boolean`: true if this event requires the reply.
// If the client sends a plain event, dispatch it.
if (!event.reply) {
self.emit(event.type, event.data);
} else {
var latch;
// A function to create a function.
function reply(success) {
// A controller function.
return function(value) {
// This latch prevents double reply.
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: value, exception: !success});
}
};
}
// Here, the controller is passed to the event handler as 2nd argument and allows
// to call the server's `resolved` or `rejected` callback by sending `reply` event.
self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
}
} | [
"function",
"onevent",
"(",
"event",
")",
"{",
"// Event should have the following properties:",
"// * `id: string`: an event identifier.",
"// * `type: string`: an event type.",
"// * `data: any`: an event data.",
"// * `reply: boolean`: true if this event requires the reply.",
"// If the client sends a plain event, dispatch it.",
"if",
"(",
"!",
"event",
".",
"reply",
")",
"{",
"self",
".",
"emit",
"(",
"event",
".",
"type",
",",
"event",
".",
"data",
")",
";",
"}",
"else",
"{",
"var",
"latch",
";",
"// A function to create a function.",
"function",
"reply",
"(",
"success",
")",
"{",
"// A controller function.",
"return",
"function",
"(",
"value",
")",
"{",
"// This latch prevents double reply.",
"if",
"(",
"!",
"latch",
")",
"{",
"latch",
"=",
"true",
";",
"self",
".",
"send",
"(",
"\"reply\"",
",",
"{",
"id",
":",
"event",
".",
"id",
",",
"data",
":",
"value",
",",
"exception",
":",
"!",
"success",
"}",
")",
";",
"}",
"}",
";",
"}",
"// Here, the controller is passed to the event handler as 2nd argument and allows",
"// to call the server's `resolved` or `rejected` callback by sending `reply` event.",
"self",
".",
"emit",
"(",
"event",
".",
"type",
",",
"event",
".",
"data",
",",
"{",
"resolve",
":",
"reply",
"(",
"true",
")",
",",
"reject",
":",
"reply",
"(",
"false",
")",
"}",
")",
";",
"}",
"}"
]
| When an event object is created from `text` or `binary` event. | [
"When",
"an",
"event",
"object",
"is",
"created",
"from",
"text",
"or",
"binary",
"event",
"."
]
| 9af3b578a9ae7b33099932903b52faeb2ca92528 | https://github.com/cettia/cettia-protocol/blob/9af3b578a9ae7b33099932903b52faeb2ca92528/lib/server.js#L96-L124 |
45,805 | kidney/postcss-iconfont | src/index.js | insertGlyphsRules | function insertGlyphsRules(rule, result) {
// Reverse order
// make sure to insert the characters in ascending order
let glyphs = result.glyphs.slice(0);
let glyphLen = glyphs.length;
while (glyphLen--) {
let glyph = glyphs[glyphLen];
let node = postcss.rule({
selector: '.' + result.opts.fontName + '-' + glyph.name + ':before'
});
node.append(postcss.decl({
prop: 'content',
value: '\'\\' +
glyph.unicode[0]
.charCodeAt(0)
.toString(16)
.toUpperCase()
+ '\''
}));
rule.parent.insertAfter(rule, node);
}
let node = postcss.rule({
selector: '[class^="' + result.opts.fontName + '-"], [class*=" ' + result.opts.fontName + '-"]'
});
[
{prop: 'font-family', value: '\'' + result.opts.fontName + '\''},
{prop: 'speak', value: 'none'},
{prop: 'font-style', value: 'normal'},
{prop: 'font-weight', value: 'normal'},
{prop: 'font-variant', value: 'normal'},
{prop: 'text-transform', value: 'none'},
{prop: 'line-height', value: 1},
{prop: '-webkit-font-smoothing', value: 'antialiased'},
{prop: '-moz-osx-font-smoothing', value: 'grayscale'}
].forEach(function (item) {
node.append(postcss.decl({
prop: item.prop,
value: item.value
}));
});
rule.parent.insertAfter(rule, node);
} | javascript | function insertGlyphsRules(rule, result) {
// Reverse order
// make sure to insert the characters in ascending order
let glyphs = result.glyphs.slice(0);
let glyphLen = glyphs.length;
while (glyphLen--) {
let glyph = glyphs[glyphLen];
let node = postcss.rule({
selector: '.' + result.opts.fontName + '-' + glyph.name + ':before'
});
node.append(postcss.decl({
prop: 'content',
value: '\'\\' +
glyph.unicode[0]
.charCodeAt(0)
.toString(16)
.toUpperCase()
+ '\''
}));
rule.parent.insertAfter(rule, node);
}
let node = postcss.rule({
selector: '[class^="' + result.opts.fontName + '-"], [class*=" ' + result.opts.fontName + '-"]'
});
[
{prop: 'font-family', value: '\'' + result.opts.fontName + '\''},
{prop: 'speak', value: 'none'},
{prop: 'font-style', value: 'normal'},
{prop: 'font-weight', value: 'normal'},
{prop: 'font-variant', value: 'normal'},
{prop: 'text-transform', value: 'none'},
{prop: 'line-height', value: 1},
{prop: '-webkit-font-smoothing', value: 'antialiased'},
{prop: '-moz-osx-font-smoothing', value: 'grayscale'}
].forEach(function (item) {
node.append(postcss.decl({
prop: item.prop,
value: item.value
}));
});
rule.parent.insertAfter(rule, node);
} | [
"function",
"insertGlyphsRules",
"(",
"rule",
",",
"result",
")",
"{",
"// Reverse order",
"// make sure to insert the characters in ascending order",
"let",
"glyphs",
"=",
"result",
".",
"glyphs",
".",
"slice",
"(",
"0",
")",
";",
"let",
"glyphLen",
"=",
"glyphs",
".",
"length",
";",
"while",
"(",
"glyphLen",
"--",
")",
"{",
"let",
"glyph",
"=",
"glyphs",
"[",
"glyphLen",
"]",
";",
"let",
"node",
"=",
"postcss",
".",
"rule",
"(",
"{",
"selector",
":",
"'.'",
"+",
"result",
".",
"opts",
".",
"fontName",
"+",
"'-'",
"+",
"glyph",
".",
"name",
"+",
"':before'",
"}",
")",
";",
"node",
".",
"append",
"(",
"postcss",
".",
"decl",
"(",
"{",
"prop",
":",
"'content'",
",",
"value",
":",
"'\\'\\\\'",
"+",
"glyph",
".",
"unicode",
"[",
"0",
"]",
".",
"charCodeAt",
"(",
"0",
")",
".",
"toString",
"(",
"16",
")",
".",
"toUpperCase",
"(",
")",
"+",
"'\\''",
"}",
")",
")",
";",
"rule",
".",
"parent",
".",
"insertAfter",
"(",
"rule",
",",
"node",
")",
";",
"}",
"let",
"node",
"=",
"postcss",
".",
"rule",
"(",
"{",
"selector",
":",
"'[class^=\"'",
"+",
"result",
".",
"opts",
".",
"fontName",
"+",
"'-\"], [class*=\" '",
"+",
"result",
".",
"opts",
".",
"fontName",
"+",
"'-\"]'",
"}",
")",
";",
"[",
"{",
"prop",
":",
"'font-family'",
",",
"value",
":",
"'\\''",
"+",
"result",
".",
"opts",
".",
"fontName",
"+",
"'\\''",
"}",
",",
"{",
"prop",
":",
"'speak'",
",",
"value",
":",
"'none'",
"}",
",",
"{",
"prop",
":",
"'font-style'",
",",
"value",
":",
"'normal'",
"}",
",",
"{",
"prop",
":",
"'font-weight'",
",",
"value",
":",
"'normal'",
"}",
",",
"{",
"prop",
":",
"'font-variant'",
",",
"value",
":",
"'normal'",
"}",
",",
"{",
"prop",
":",
"'text-transform'",
",",
"value",
":",
"'none'",
"}",
",",
"{",
"prop",
":",
"'line-height'",
",",
"value",
":",
"1",
"}",
",",
"{",
"prop",
":",
"'-webkit-font-smoothing'",
",",
"value",
":",
"'antialiased'",
"}",
",",
"{",
"prop",
":",
"'-moz-osx-font-smoothing'",
",",
"value",
":",
"'grayscale'",
"}",
"]",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"node",
".",
"append",
"(",
"postcss",
".",
"decl",
"(",
"{",
"prop",
":",
"item",
".",
"prop",
",",
"value",
":",
"item",
".",
"value",
"}",
")",
")",
";",
"}",
")",
";",
"rule",
".",
"parent",
".",
"insertAfter",
"(",
"rule",
",",
"node",
")",
";",
"}"
]
| Insert glyphs css rules
@param rule
@param result | [
"Insert",
"glyphs",
"css",
"rules"
]
| 35bc3eecc0a0baa1db32ec523ff2904b0b9aa08d | https://github.com/kidney/postcss-iconfont/blob/35bc3eecc0a0baa1db32ec523ff2904b0b9aa08d/src/index.js#L170-L214 |
45,806 | rksm/estree-to-js | index.js | extractTypeSourcesFromMarkdown | function extractTypeSourcesFromMarkdown(mdSource) {
var types = lang.string.lines(mdSource).reduce((typesAkk, line) => {
if (line.trim().startsWith("//")) return typesAkk;
if (typesAkk.current && !line.trim().length) {
typesAkk.types.push(typesAkk.current); typesAkk.current = [];
} else if (typesAkk.current && line.indexOf("```") > -1) {
typesAkk.types.push(typesAkk.current); typesAkk.current = null;
} else if (!typesAkk.current && line.indexOf("```js") > -1) {
typesAkk.current = [];
} else if (typesAkk.current) typesAkk.current.push(line);
return typesAkk;
}, {current: null, types: []}).types;
return lang.arr.invoke(types, "join", "\n");
} | javascript | function extractTypeSourcesFromMarkdown(mdSource) {
var types = lang.string.lines(mdSource).reduce((typesAkk, line) => {
if (line.trim().startsWith("//")) return typesAkk;
if (typesAkk.current && !line.trim().length) {
typesAkk.types.push(typesAkk.current); typesAkk.current = [];
} else if (typesAkk.current && line.indexOf("```") > -1) {
typesAkk.types.push(typesAkk.current); typesAkk.current = null;
} else if (!typesAkk.current && line.indexOf("```js") > -1) {
typesAkk.current = [];
} else if (typesAkk.current) typesAkk.current.push(line);
return typesAkk;
}, {current: null, types: []}).types;
return lang.arr.invoke(types, "join", "\n");
} | [
"function",
"extractTypeSourcesFromMarkdown",
"(",
"mdSource",
")",
"{",
"var",
"types",
"=",
"lang",
".",
"string",
".",
"lines",
"(",
"mdSource",
")",
".",
"reduce",
"(",
"(",
"typesAkk",
",",
"line",
")",
"=>",
"{",
"if",
"(",
"line",
".",
"trim",
"(",
")",
".",
"startsWith",
"(",
"\"//\"",
")",
")",
"return",
"typesAkk",
";",
"if",
"(",
"typesAkk",
".",
"current",
"&&",
"!",
"line",
".",
"trim",
"(",
")",
".",
"length",
")",
"{",
"typesAkk",
".",
"types",
".",
"push",
"(",
"typesAkk",
".",
"current",
")",
";",
"typesAkk",
".",
"current",
"=",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"typesAkk",
".",
"current",
"&&",
"line",
".",
"indexOf",
"(",
"\"```\"",
")",
">",
"-",
"1",
")",
"{",
"typesAkk",
".",
"types",
".",
"push",
"(",
"typesAkk",
".",
"current",
")",
";",
"typesAkk",
".",
"current",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"!",
"typesAkk",
".",
"current",
"&&",
"line",
".",
"indexOf",
"(",
"\"```js\"",
")",
">",
"-",
"1",
")",
"{",
"typesAkk",
".",
"current",
"=",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"typesAkk",
".",
"current",
")",
"typesAkk",
".",
"current",
".",
"push",
"(",
"line",
")",
";",
"return",
"typesAkk",
";",
"}",
",",
"{",
"current",
":",
"null",
",",
"types",
":",
"[",
"]",
"}",
")",
".",
"types",
";",
"return",
"lang",
".",
"arr",
".",
"invoke",
"(",
"types",
",",
"\"join\"",
",",
"\"\\n\"",
")",
";",
"}"
]
| -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- estree spec markdown parser | [
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"estree",
"spec",
"markdown",
"parser"
]
| 3cb21c9c63ff329651f08197d353965e80551bd2 | https://github.com/rksm/estree-to-js/blob/3cb21c9c63ff329651f08197d353965e80551bd2/index.js#L53-L66 |
45,807 | alexindigo/cartesian | index.js | cartesian | function cartesian(list)
{
var last, init, keys, product = [];
if (Array.isArray(list))
{
init = [];
last = list.length - 1;
}
else if (typeof list == 'object' && list !== null)
{
init = {};
keys = Object.keys(list);
last = keys.length - 1;
}
else
{
throw new TypeError('Expecting an Array or an Object, but `' + (list === null ? 'null' : typeof list) + '` provided.');
}
function add(row, i)
{
var j, k, r;
k = keys ? keys[i] : i;
// either array or not, not expecting objects here
Array.isArray(list[k]) || (typeof list[k] == 'undefined' ? list[k] = [] : list[k] = [list[k]]);
for (j=0; j < list[k].length; j++)
{
r = clone(row);
store(r, list[k][j], k);
if (i >= last)
{
product.push(r);
}
else
{
add(r, i + 1);
}
}
}
add(init, 0);
return product;
} | javascript | function cartesian(list)
{
var last, init, keys, product = [];
if (Array.isArray(list))
{
init = [];
last = list.length - 1;
}
else if (typeof list == 'object' && list !== null)
{
init = {};
keys = Object.keys(list);
last = keys.length - 1;
}
else
{
throw new TypeError('Expecting an Array or an Object, but `' + (list === null ? 'null' : typeof list) + '` provided.');
}
function add(row, i)
{
var j, k, r;
k = keys ? keys[i] : i;
// either array or not, not expecting objects here
Array.isArray(list[k]) || (typeof list[k] == 'undefined' ? list[k] = [] : list[k] = [list[k]]);
for (j=0; j < list[k].length; j++)
{
r = clone(row);
store(r, list[k][j], k);
if (i >= last)
{
product.push(r);
}
else
{
add(r, i + 1);
}
}
}
add(init, 0);
return product;
} | [
"function",
"cartesian",
"(",
"list",
")",
"{",
"var",
"last",
",",
"init",
",",
"keys",
",",
"product",
"=",
"[",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"list",
")",
")",
"{",
"init",
"=",
"[",
"]",
";",
"last",
"=",
"list",
".",
"length",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"typeof",
"list",
"==",
"'object'",
"&&",
"list",
"!==",
"null",
")",
"{",
"init",
"=",
"{",
"}",
";",
"keys",
"=",
"Object",
".",
"keys",
"(",
"list",
")",
";",
"last",
"=",
"keys",
".",
"length",
"-",
"1",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expecting an Array or an Object, but `'",
"+",
"(",
"list",
"===",
"null",
"?",
"'null'",
":",
"typeof",
"list",
")",
"+",
"'` provided.'",
")",
";",
"}",
"function",
"add",
"(",
"row",
",",
"i",
")",
"{",
"var",
"j",
",",
"k",
",",
"r",
";",
"k",
"=",
"keys",
"?",
"keys",
"[",
"i",
"]",
":",
"i",
";",
"// either array or not, not expecting objects here",
"Array",
".",
"isArray",
"(",
"list",
"[",
"k",
"]",
")",
"||",
"(",
"typeof",
"list",
"[",
"k",
"]",
"==",
"'undefined'",
"?",
"list",
"[",
"k",
"]",
"=",
"[",
"]",
":",
"list",
"[",
"k",
"]",
"=",
"[",
"list",
"[",
"k",
"]",
"]",
")",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"list",
"[",
"k",
"]",
".",
"length",
";",
"j",
"++",
")",
"{",
"r",
"=",
"clone",
"(",
"row",
")",
";",
"store",
"(",
"r",
",",
"list",
"[",
"k",
"]",
"[",
"j",
"]",
",",
"k",
")",
";",
"if",
"(",
"i",
">=",
"last",
")",
"{",
"product",
".",
"push",
"(",
"r",
")",
";",
"}",
"else",
"{",
"add",
"(",
"r",
",",
"i",
"+",
"1",
")",
";",
"}",
"}",
"}",
"add",
"(",
"init",
",",
"0",
")",
";",
"return",
"product",
";",
"}"
]
| Creates cartesian product of the provided properties
@param {object|array} list - list of (array) properties or array of arrays
@returns {array} all the combinations of the properties | [
"Creates",
"cartesian",
"product",
"of",
"the",
"provided",
"properties"
]
| 378663ad87902a058bd7202eb3e87a91993c1d3a | https://github.com/alexindigo/cartesian/blob/378663ad87902a058bd7202eb3e87a91993c1d3a/index.js#L12-L60 |
45,808 | alexindigo/cartesian | index.js | store | function store(obj, elem, key)
{
Array.isArray(obj) ? obj.push(elem) : (obj[key] = elem);
} | javascript | function store(obj, elem, key)
{
Array.isArray(obj) ? obj.push(elem) : (obj[key] = elem);
} | [
"function",
"store",
"(",
"obj",
",",
"elem",
",",
"key",
")",
"{",
"Array",
".",
"isArray",
"(",
"obj",
")",
"?",
"obj",
".",
"push",
"(",
"elem",
")",
":",
"(",
"obj",
"[",
"key",
"]",
"=",
"elem",
")",
";",
"}"
]
| Stores provided element in the provided object or array
@param {object|array} obj - object or array to add to
@param {mixed} elem - element to add
@param {string|number} key - object's property key to add to
@returns {void} | [
"Stores",
"provided",
"element",
"in",
"the",
"provided",
"object",
"or",
"array"
]
| 378663ad87902a058bd7202eb3e87a91993c1d3a | https://github.com/alexindigo/cartesian/blob/378663ad87902a058bd7202eb3e87a91993c1d3a/index.js#L81-L84 |
45,809 | jordangarcia/nuclear-js-react-addons | build/nuclearComponent.js | nuclearComponent | function nuclearComponent(Component, getDataBindings) {
console.warn('nuclearComponent is deprecated, use `connect()` instead');
// support decorator pattern
// detect all React Components because they have a render method
if (arguments.length === 0 || !Component.prototype.render) {
// Component here is the getDataBindings Function
return _connect2['default'](Component);
}
return _connect2['default'](getDataBindings)(Component);
} | javascript | function nuclearComponent(Component, getDataBindings) {
console.warn('nuclearComponent is deprecated, use `connect()` instead');
// support decorator pattern
// detect all React Components because they have a render method
if (arguments.length === 0 || !Component.prototype.render) {
// Component here is the getDataBindings Function
return _connect2['default'](Component);
}
return _connect2['default'](getDataBindings)(Component);
} | [
"function",
"nuclearComponent",
"(",
"Component",
",",
"getDataBindings",
")",
"{",
"console",
".",
"warn",
"(",
"'nuclearComponent is deprecated, use `connect()` instead'",
")",
";",
"// support decorator pattern",
"// detect all React Components because they have a render method",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
"||",
"!",
"Component",
".",
"prototype",
".",
"render",
")",
"{",
"// Component here is the getDataBindings Function",
"return",
"_connect2",
"[",
"'default'",
"]",
"(",
"Component",
")",
";",
"}",
"return",
"_connect2",
"[",
"'default'",
"]",
"(",
"getDataBindings",
")",
"(",
"Component",
")",
";",
"}"
]
| Provides dataBindings + reactor
as props to wrapped component
Example:
var WrappedComponent = nuclearComponent(Component, function(props) {
return { counter: 'counter' };
);
Also supports the decorator pattern:
@nuclearComponent((props) => {
return { counter: 'counter' }
})
class BaseComponent extends React.Component {
render() {
const { counter, reactor } = this.props;
return <div/>;
}
}
@method nuclearComponent
@param {React.Component} [Component] component to wrap
@param {Function} getDataBindings function which returns dataBindings to listen for data change
@returns {React.Component|Function} returns function if using decorator pattern | [
"Provides",
"dataBindings",
"+",
"reactor",
"as",
"props",
"to",
"wrapped",
"component"
]
| 5550ebd6ec07bfec01aa557908735142613dcdb3 | https://github.com/jordangarcia/nuclear-js-react-addons/blob/5550ebd6ec07bfec01aa557908735142613dcdb3/build/nuclearComponent.js#L38-L48 |
45,810 | opendxl/node-red-contrib-dxl | lib/node-utils.js | function (value, defaultValue) {
if (module.exports.isEmpty(value)) {
value = defaultValue
} else if (typeof value === 'string') {
value = value.trim().toLowerCase()
switch (value) {
case 'false':
value = 0
break
case 'true':
value = 1
break
default:
value = Number(value)
}
} else if (typeof value === 'boolean') {
value = Number(value)
} else if (isNaN(value)) {
value = NaN
}
return value
} | javascript | function (value, defaultValue) {
if (module.exports.isEmpty(value)) {
value = defaultValue
} else if (typeof value === 'string') {
value = value.trim().toLowerCase()
switch (value) {
case 'false':
value = 0
break
case 'true':
value = 1
break
default:
value = Number(value)
}
} else if (typeof value === 'boolean') {
value = Number(value)
} else if (isNaN(value)) {
value = NaN
}
return value
} | [
"function",
"(",
"value",
",",
"defaultValue",
")",
"{",
"if",
"(",
"module",
".",
"exports",
".",
"isEmpty",
"(",
"value",
")",
")",
"{",
"value",
"=",
"defaultValue",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"value",
"=",
"value",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
"switch",
"(",
"value",
")",
"{",
"case",
"'false'",
":",
"value",
"=",
"0",
"break",
"case",
"'true'",
":",
"value",
"=",
"1",
"break",
"default",
":",
"value",
"=",
"Number",
"(",
"value",
")",
"}",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'boolean'",
")",
"{",
"value",
"=",
"Number",
"(",
"value",
")",
"}",
"else",
"if",
"(",
"isNaN",
"(",
"value",
")",
")",
"{",
"value",
"=",
"NaN",
"}",
"return",
"value",
"}"
]
| Convert the supplied value into a number.
@param value - The value to convert.
@param defaultValue - If the value parameter is undefined, null,
a zero-length string, or a string containing only whitespace characters,
the defaultValue is returned.
@returns The converted or default value. If the value parameter is
non-null, not a zero-length string, and not a string containing only
whitespace characters but cannot be converted to a number, NaN is
returned.
@private | [
"Convert",
"the",
"supplied",
"value",
"into",
"a",
"number",
"."
]
| a68169c4357162f48d98006fb40843795f997f28 | https://github.com/opendxl/node-red-contrib-dxl/blob/a68169c4357162f48d98006fb40843795f997f28/lib/node-utils.js#L21-L42 |
|
45,811 | sheepsteak/react-perf-component | lib/index.js | perf | function perf(Target) {
if (process.env.NODE_ENV === 'production') {
return Target;
}
// eslint-disable-next-line global-require
var ReactPerf = require('react-addons-perf');
var Perf = function (_Component) {
_inherits(Perf, _Component);
function Perf() {
_classCallCheck(this, Perf);
return _possibleConstructorReturn(this, (Perf.__proto__ || Object.getPrototypeOf(Perf)).apply(this, arguments));
}
_createClass(Perf, [{
key: 'componentDidMount',
value: function componentDidMount() {
ReactPerf.start();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
ReactPerf.stop();
var measurements = ReactPerf.getLastMeasurements();
ReactPerf.printWasted(measurements);
ReactPerf.start();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
ReactPerf.stop();
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(Target, this.props);
}
}]);
return Perf;
}(_react.Component);
Perf.displayName = 'perf(' + (Target.displayName || Target.name || 'Component') + ')';
Perf.WrappedComponent = Target;
return Perf;
} | javascript | function perf(Target) {
if (process.env.NODE_ENV === 'production') {
return Target;
}
// eslint-disable-next-line global-require
var ReactPerf = require('react-addons-perf');
var Perf = function (_Component) {
_inherits(Perf, _Component);
function Perf() {
_classCallCheck(this, Perf);
return _possibleConstructorReturn(this, (Perf.__proto__ || Object.getPrototypeOf(Perf)).apply(this, arguments));
}
_createClass(Perf, [{
key: 'componentDidMount',
value: function componentDidMount() {
ReactPerf.start();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
ReactPerf.stop();
var measurements = ReactPerf.getLastMeasurements();
ReactPerf.printWasted(measurements);
ReactPerf.start();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
ReactPerf.stop();
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(Target, this.props);
}
}]);
return Perf;
}(_react.Component);
Perf.displayName = 'perf(' + (Target.displayName || Target.name || 'Component') + ')';
Perf.WrappedComponent = Target;
return Perf;
} | [
"function",
"perf",
"(",
"Target",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
")",
"{",
"return",
"Target",
";",
"}",
"// eslint-disable-next-line global-require",
"var",
"ReactPerf",
"=",
"require",
"(",
"'react-addons-perf'",
")",
";",
"var",
"Perf",
"=",
"function",
"(",
"_Component",
")",
"{",
"_inherits",
"(",
"Perf",
",",
"_Component",
")",
";",
"function",
"Perf",
"(",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"Perf",
")",
";",
"return",
"_possibleConstructorReturn",
"(",
"this",
",",
"(",
"Perf",
".",
"__proto__",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"Perf",
")",
")",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
"_createClass",
"(",
"Perf",
",",
"[",
"{",
"key",
":",
"'componentDidMount'",
",",
"value",
":",
"function",
"componentDidMount",
"(",
")",
"{",
"ReactPerf",
".",
"start",
"(",
")",
";",
"}",
"}",
",",
"{",
"key",
":",
"'componentDidUpdate'",
",",
"value",
":",
"function",
"componentDidUpdate",
"(",
")",
"{",
"ReactPerf",
".",
"stop",
"(",
")",
";",
"var",
"measurements",
"=",
"ReactPerf",
".",
"getLastMeasurements",
"(",
")",
";",
"ReactPerf",
".",
"printWasted",
"(",
"measurements",
")",
";",
"ReactPerf",
".",
"start",
"(",
")",
";",
"}",
"}",
",",
"{",
"key",
":",
"'componentWillUnmount'",
",",
"value",
":",
"function",
"componentWillUnmount",
"(",
")",
"{",
"ReactPerf",
".",
"stop",
"(",
")",
";",
"}",
"}",
",",
"{",
"key",
":",
"'render'",
",",
"value",
":",
"function",
"render",
"(",
")",
"{",
"return",
"_react2",
".",
"default",
".",
"createElement",
"(",
"Target",
",",
"this",
".",
"props",
")",
";",
"}",
"}",
"]",
")",
";",
"return",
"Perf",
";",
"}",
"(",
"_react",
".",
"Component",
")",
";",
"Perf",
".",
"displayName",
"=",
"'perf('",
"+",
"(",
"Target",
".",
"displayName",
"||",
"Target",
".",
"name",
"||",
"'Component'",
")",
"+",
"')'",
";",
"Perf",
".",
"WrappedComponent",
"=",
"Target",
";",
"return",
"Perf",
";",
"}"
]
| Wraps the passed in `Component` in a higher-order component. It can then
measure the performance of every render of the `Component`.
Can also be used as an ES2016 decorator.
@param {ReactComponent} Component the component to wrap
@return {ReactComponent} the wrapped component | [
"Wraps",
"the",
"passed",
"in",
"Component",
"in",
"a",
"higher",
"-",
"order",
"component",
".",
"It",
"can",
"then",
"measure",
"the",
"performance",
"of",
"every",
"render",
"of",
"the",
"Component",
"."
]
| b6b34c578e715940e59f958ba5b5d1b52a64f253 | https://github.com/sheepsteak/react-perf-component/blob/b6b34c578e715940e59f958ba5b5d1b52a64f253/lib/index.js#L31-L81 |
45,812 | jordangarcia/nuclear-js-react-addons | build/provideReactor.js | provideReactor | function provideReactor(Component, additionalContextTypes) {
console.warn('`provideReactor` is deprecated, use `<Provider reactor={reactor} />` instead');
// support decorator pattern
if (arguments.length === 0 || typeof arguments[0] !== 'function') {
additionalContextTypes = arguments[0];
return function connectToReactorDecorator(ComponentToDecorate) {
return createComponent(ComponentToDecorate, additionalContextTypes);
};
}
return createComponent.apply(null, arguments);
} | javascript | function provideReactor(Component, additionalContextTypes) {
console.warn('`provideReactor` is deprecated, use `<Provider reactor={reactor} />` instead');
// support decorator pattern
if (arguments.length === 0 || typeof arguments[0] !== 'function') {
additionalContextTypes = arguments[0];
return function connectToReactorDecorator(ComponentToDecorate) {
return createComponent(ComponentToDecorate, additionalContextTypes);
};
}
return createComponent.apply(null, arguments);
} | [
"function",
"provideReactor",
"(",
"Component",
",",
"additionalContextTypes",
")",
"{",
"console",
".",
"warn",
"(",
"'`provideReactor` is deprecated, use `<Provider reactor={reactor} />` instead'",
")",
";",
"// support decorator pattern",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
"||",
"typeof",
"arguments",
"[",
"0",
"]",
"!==",
"'function'",
")",
"{",
"additionalContextTypes",
"=",
"arguments",
"[",
"0",
"]",
";",
"return",
"function",
"connectToReactorDecorator",
"(",
"ComponentToDecorate",
")",
"{",
"return",
"createComponent",
"(",
"ComponentToDecorate",
",",
"additionalContextTypes",
")",
";",
"}",
";",
"}",
"return",
"createComponent",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"}"
]
| Provides reactor prop to all children as React context
Example:
var WrappedComponent = provideReactor(Component, {
foo: React.PropTypes.string
});
Also supports the decorator pattern:
@provideReactor({
foo: React.PropTypes.string
})
class BaseComponent extends React.Component {
render() {
return <div/>;
}
}
@method provideReactor
@param {React.Component} [Component] component to wrap
@param {object} additionalContextTypes Additional contextTypes to add
@returns {React.Component|Function} returns function if using decorator pattern | [
"Provides",
"reactor",
"prop",
"to",
"all",
"children",
"as",
"React",
"context"
]
| 5550ebd6ec07bfec01aa557908735142613dcdb3 | https://github.com/jordangarcia/nuclear-js-react-addons/blob/5550ebd6ec07bfec01aa557908735142613dcdb3/build/provideReactor.js#L81-L92 |
45,813 | jefftham/wsm | lib/wsm.js | wsConnect | function wsConnect() {
var typeOfConnection;
if (location.protocol === 'https:') {
typeOfConnection = 'wss';
} else {
typeOfConnection = 'ws'
}
self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);
self.ws.onopen = function (event) {
//send an intial message to server and prove that the connection is built.
self.send('connected', 'WSM: Browser confirms websocket connection.')
reactive(self);
};
self.ws.onmessage = function (event) {
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
//console.log(event.data);
self.processMessage(JSON.parse(event.data));
};
self.ws.onclose = function (event) {
wsConnect();
}
} | javascript | function wsConnect() {
var typeOfConnection;
if (location.protocol === 'https:') {
typeOfConnection = 'wss';
} else {
typeOfConnection = 'ws'
}
self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);
self.ws.onopen = function (event) {
//send an intial message to server and prove that the connection is built.
self.send('connected', 'WSM: Browser confirms websocket connection.')
reactive(self);
};
self.ws.onmessage = function (event) {
// flags.binary will be set if a binary data is received.
// flags.masked will be set if the data was masked.
//console.log(event.data);
self.processMessage(JSON.parse(event.data));
};
self.ws.onclose = function (event) {
wsConnect();
}
} | [
"function",
"wsConnect",
"(",
")",
"{",
"var",
"typeOfConnection",
";",
"if",
"(",
"location",
".",
"protocol",
"===",
"'https:'",
")",
"{",
"typeOfConnection",
"=",
"'wss'",
";",
"}",
"else",
"{",
"typeOfConnection",
"=",
"'ws'",
"}",
"self",
".",
"ws",
"=",
"new",
"WebSocket",
"(",
"typeOfConnection",
"+",
"'://'",
"+",
"location",
".",
"hostname",
"+",
"':'",
"+",
"location",
".",
"port",
")",
";",
"self",
".",
"ws",
".",
"onopen",
"=",
"function",
"(",
"event",
")",
"{",
"//send an intial message to server and prove that the connection is built.",
"self",
".",
"send",
"(",
"'connected'",
",",
"'WSM: Browser confirms websocket connection.'",
")",
"reactive",
"(",
"self",
")",
";",
"}",
";",
"self",
".",
"ws",
".",
"onmessage",
"=",
"function",
"(",
"event",
")",
"{",
"// flags.binary will be set if a binary data is received.",
"// flags.masked will be set if the data was masked.",
"//console.log(event.data);",
"self",
".",
"processMessage",
"(",
"JSON",
".",
"parse",
"(",
"event",
".",
"data",
")",
")",
";",
"}",
";",
"self",
".",
"ws",
".",
"onclose",
"=",
"function",
"(",
"event",
")",
"{",
"wsConnect",
"(",
")",
";",
"}",
"}"
]
| on browser
wrap browser's websocket connection into one function, if the connection drop or close, try to reconnect itself. | [
"on",
"browser",
"wrap",
"browser",
"s",
"websocket",
"connection",
"into",
"one",
"function",
"if",
"the",
"connection",
"drop",
"or",
"close",
"try",
"to",
"reconnect",
"itself",
"."
]
| 6d88aa1e8cc21384aa918c3f9526fe61aa92483f | https://github.com/jefftham/wsm/blob/6d88aa1e8cc21384aa918c3f9526fe61aa92483f/lib/wsm.js#L172-L205 |
45,814 | Ustimov/node-red-flow-drawer | src/red/localfilesystem.js | getLocalNodeFiles | function getLocalNodeFiles(dir) {
dir = path.resolve(dir);
var result = [];
var files = [];
var icons = [];
try {
files = fs.readdirSync(dir);
} catch(err) {
return {files: [], icons: []};
}
files.sort();
files.forEach(function(fn) {
var stats = fs.statSync(path.join(dir,fn));
if (stats.isFile()) {
if (/\.js$/.test(fn)) {
var info = getLocalFile(path.join(dir,fn));
if (info) {
result.push(info);
}
}
} else if (stats.isDirectory()) {
// Ignore /.dirs/, /lib/ /node_modules/
if (!/^(\..*|lib|icons|node_modules|test|locales)$/.test(fn)) {
var subDirResults = getLocalNodeFiles(path.join(dir,fn));
result = result.concat(subDirResults.files);
icons = icons.concat(subDirResults.icons);
} else if (fn === "icons") {
var iconList = scanIconDir(path.join(dir,fn));
icons.push({path:path.join(dir,fn),icons:iconList});
}
}
});
return {files: result, icons: icons};
} | javascript | function getLocalNodeFiles(dir) {
dir = path.resolve(dir);
var result = [];
var files = [];
var icons = [];
try {
files = fs.readdirSync(dir);
} catch(err) {
return {files: [], icons: []};
}
files.sort();
files.forEach(function(fn) {
var stats = fs.statSync(path.join(dir,fn));
if (stats.isFile()) {
if (/\.js$/.test(fn)) {
var info = getLocalFile(path.join(dir,fn));
if (info) {
result.push(info);
}
}
} else if (stats.isDirectory()) {
// Ignore /.dirs/, /lib/ /node_modules/
if (!/^(\..*|lib|icons|node_modules|test|locales)$/.test(fn)) {
var subDirResults = getLocalNodeFiles(path.join(dir,fn));
result = result.concat(subDirResults.files);
icons = icons.concat(subDirResults.icons);
} else if (fn === "icons") {
var iconList = scanIconDir(path.join(dir,fn));
icons.push({path:path.join(dir,fn),icons:iconList});
}
}
});
return {files: result, icons: icons};
} | [
"function",
"getLocalNodeFiles",
"(",
"dir",
")",
"{",
"dir",
"=",
"path",
".",
"resolve",
"(",
"dir",
")",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"files",
"=",
"[",
"]",
";",
"var",
"icons",
"=",
"[",
"]",
";",
"try",
"{",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"{",
"files",
":",
"[",
"]",
",",
"icons",
":",
"[",
"]",
"}",
";",
"}",
"files",
".",
"sort",
"(",
")",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"fn",
")",
"{",
"var",
"stats",
"=",
"fs",
".",
"statSync",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"fn",
")",
")",
";",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"if",
"(",
"/",
"\\.js$",
"/",
".",
"test",
"(",
"fn",
")",
")",
"{",
"var",
"info",
"=",
"getLocalFile",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"fn",
")",
")",
";",
"if",
"(",
"info",
")",
"{",
"result",
".",
"push",
"(",
"info",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"// Ignore /.dirs/, /lib/ /node_modules/",
"if",
"(",
"!",
"/",
"^(\\..*|lib|icons|node_modules|test|locales)$",
"/",
".",
"test",
"(",
"fn",
")",
")",
"{",
"var",
"subDirResults",
"=",
"getLocalNodeFiles",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"fn",
")",
")",
";",
"result",
"=",
"result",
".",
"concat",
"(",
"subDirResults",
".",
"files",
")",
";",
"icons",
"=",
"icons",
".",
"concat",
"(",
"subDirResults",
".",
"icons",
")",
";",
"}",
"else",
"if",
"(",
"fn",
"===",
"\"icons\"",
")",
"{",
"var",
"iconList",
"=",
"scanIconDir",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"fn",
")",
")",
";",
"icons",
".",
"push",
"(",
"{",
"path",
":",
"path",
".",
"join",
"(",
"dir",
",",
"fn",
")",
",",
"icons",
":",
"iconList",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"{",
"files",
":",
"result",
",",
"icons",
":",
"icons",
"}",
";",
"}"
]
| Synchronously walks the directory looking for node files.
Emits 'node-icon-dir' events for an icon dirs found
@param dir the directory to search
@return an array of fully-qualified paths to .js files | [
"Synchronously",
"walks",
"the",
"directory",
"looking",
"for",
"node",
"files",
".",
"Emits",
"node",
"-",
"icon",
"-",
"dir",
"events",
"for",
"an",
"icon",
"dirs",
"found"
]
| 58bb5f760d6800f41b9557e030b1ea7db2db02c0 | https://github.com/Ustimov/node-red-flow-drawer/blob/58bb5f760d6800f41b9557e030b1ea7db2db02c0/src/red/localfilesystem.js#L74-L108 |
45,815 | Ustimov/node-red-flow-drawer | src/red/localfilesystem.js | scanTreeForNodesModules | function scanTreeForNodesModules(moduleName) {
var dir = settings.coreNodesDir;
var results = [];
var userDir;
if (settings.userDir) {
userDir = path.join(settings.userDir,"node_modules");
results = scanDirForNodesModules(userDir,moduleName);
results.forEach(function(r) { r.local = true; });
}
if (dir) {
var up = path.resolve(path.join(dir,".."));
while (up !== dir) {
var pm = path.join(dir,"node_modules");
if (pm != userDir) {
results = results.concat(scanDirForNodesModules(pm,moduleName));
}
dir = up;
up = path.resolve(path.join(dir,".."));
}
}
return results;
} | javascript | function scanTreeForNodesModules(moduleName) {
var dir = settings.coreNodesDir;
var results = [];
var userDir;
if (settings.userDir) {
userDir = path.join(settings.userDir,"node_modules");
results = scanDirForNodesModules(userDir,moduleName);
results.forEach(function(r) { r.local = true; });
}
if (dir) {
var up = path.resolve(path.join(dir,".."));
while (up !== dir) {
var pm = path.join(dir,"node_modules");
if (pm != userDir) {
results = results.concat(scanDirForNodesModules(pm,moduleName));
}
dir = up;
up = path.resolve(path.join(dir,".."));
}
}
return results;
} | [
"function",
"scanTreeForNodesModules",
"(",
"moduleName",
")",
"{",
"var",
"dir",
"=",
"settings",
".",
"coreNodesDir",
";",
"var",
"results",
"=",
"[",
"]",
";",
"var",
"userDir",
";",
"if",
"(",
"settings",
".",
"userDir",
")",
"{",
"userDir",
"=",
"path",
".",
"join",
"(",
"settings",
".",
"userDir",
",",
"\"node_modules\"",
")",
";",
"results",
"=",
"scanDirForNodesModules",
"(",
"userDir",
",",
"moduleName",
")",
";",
"results",
".",
"forEach",
"(",
"function",
"(",
"r",
")",
"{",
"r",
".",
"local",
"=",
"true",
";",
"}",
")",
";",
"}",
"if",
"(",
"dir",
")",
"{",
"var",
"up",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"\"..\"",
")",
")",
";",
"while",
"(",
"up",
"!==",
"dir",
")",
"{",
"var",
"pm",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"\"node_modules\"",
")",
";",
"if",
"(",
"pm",
"!=",
"userDir",
")",
"{",
"results",
"=",
"results",
".",
"concat",
"(",
"scanDirForNodesModules",
"(",
"pm",
",",
"moduleName",
")",
")",
";",
"}",
"dir",
"=",
"up",
";",
"up",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"\"..\"",
")",
")",
";",
"}",
"}",
"return",
"results",
";",
"}"
]
| Scans the node_modules path for nodes
@param moduleName the name of the module to be found
@return a list of node modules: {dir,package} | [
"Scans",
"the",
"node_modules",
"path",
"for",
"nodes"
]
| 58bb5f760d6800f41b9557e030b1ea7db2db02c0 | https://github.com/Ustimov/node-red-flow-drawer/blob/58bb5f760d6800f41b9557e030b1ea7db2db02c0/src/red/localfilesystem.js#L163-L186 |
45,816 | NickCis/polygonize | src/Graph.js | validateGeoJson | function validateGeoJson(geoJson) {
if (!geoJson)
throw new Error('No geojson passed');
if (geoJson.type !== 'FeatureCollection' &&
geoJson.type !== 'GeometryCollection' &&
geoJson.type !== 'MultiLineString' &&
geoJson.type !== 'LineString' &&
geoJson.type !== 'Feature'
)
throw new Error(`Invalid input type '${geoJson.type}'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature`);
} | javascript | function validateGeoJson(geoJson) {
if (!geoJson)
throw new Error('No geojson passed');
if (geoJson.type !== 'FeatureCollection' &&
geoJson.type !== 'GeometryCollection' &&
geoJson.type !== 'MultiLineString' &&
geoJson.type !== 'LineString' &&
geoJson.type !== 'Feature'
)
throw new Error(`Invalid input type '${geoJson.type}'. Geojson must be FeatureCollection, GeometryCollection, LineString, MultiLineString or Feature`);
} | [
"function",
"validateGeoJson",
"(",
"geoJson",
")",
"{",
"if",
"(",
"!",
"geoJson",
")",
"throw",
"new",
"Error",
"(",
"'No geojson passed'",
")",
";",
"if",
"(",
"geoJson",
".",
"type",
"!==",
"'FeatureCollection'",
"&&",
"geoJson",
".",
"type",
"!==",
"'GeometryCollection'",
"&&",
"geoJson",
".",
"type",
"!==",
"'MultiLineString'",
"&&",
"geoJson",
".",
"type",
"!==",
"'LineString'",
"&&",
"geoJson",
".",
"type",
"!==",
"'Feature'",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"geoJson",
".",
"type",
"}",
"`",
")",
";",
"}"
]
| Validates the geoJson.
@param {Geojson} geoJson - input geoJson.
@throws {Error} if geoJson is invalid. | [
"Validates",
"the",
"geoJson",
"."
]
| f8f9ea78debfdfd1d60a7429ddf6ba64fb54d0cc | https://github.com/NickCis/polygonize/blob/f8f9ea78debfdfd1d60a7429ddf6ba64fb54d0cc/src/Graph.js#L12-L23 |
45,817 | discolabs/grunt-shopify-theme-settings | tasks/shopify_theme_settings.js | getCombinedTemplateDirectory | function getCombinedTemplateDirectory(templateDirectories) {
// Automatically track and clean up files at exit.
temp.track();
// Create a temporary directory to hold our template files.
var combinedTemplateDirectory = temp.mkdirSync('templates');
// Copy templates from our source directories into the combined directory.
templateDirectories.reverse().forEach(function(templateDirectory) {
grunt.file.expand(path.join(templateDirectory, '*.html')).forEach(function(srcPath) {
var srcFilename = path.basename(srcPath),
destPath = path.join(combinedTemplateDirectory, srcFilename);
grunt.file.copy(srcPath, destPath);
});
});
return combinedTemplateDirectory;
} | javascript | function getCombinedTemplateDirectory(templateDirectories) {
// Automatically track and clean up files at exit.
temp.track();
// Create a temporary directory to hold our template files.
var combinedTemplateDirectory = temp.mkdirSync('templates');
// Copy templates from our source directories into the combined directory.
templateDirectories.reverse().forEach(function(templateDirectory) {
grunt.file.expand(path.join(templateDirectory, '*.html')).forEach(function(srcPath) {
var srcFilename = path.basename(srcPath),
destPath = path.join(combinedTemplateDirectory, srcFilename);
grunt.file.copy(srcPath, destPath);
});
});
return combinedTemplateDirectory;
} | [
"function",
"getCombinedTemplateDirectory",
"(",
"templateDirectories",
")",
"{",
"// Automatically track and clean up files at exit.",
"temp",
".",
"track",
"(",
")",
";",
"// Create a temporary directory to hold our template files.",
"var",
"combinedTemplateDirectory",
"=",
"temp",
".",
"mkdirSync",
"(",
"'templates'",
")",
";",
"// Copy templates from our source directories into the combined directory.",
"templateDirectories",
".",
"reverse",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"templateDirectory",
")",
"{",
"grunt",
".",
"file",
".",
"expand",
"(",
"path",
".",
"join",
"(",
"templateDirectory",
",",
"'*.html'",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"srcPath",
")",
"{",
"var",
"srcFilename",
"=",
"path",
".",
"basename",
"(",
"srcPath",
")",
",",
"destPath",
"=",
"path",
".",
"join",
"(",
"combinedTemplateDirectory",
",",
"srcFilename",
")",
";",
"grunt",
".",
"file",
".",
"copy",
"(",
"srcPath",
",",
"destPath",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"combinedTemplateDirectory",
";",
"}"
]
| Given a list of template directories, compile them into a single template directory.
Templates with the same name will be overridden, with preference given to those first in the list.
@param templateDirectories
@return string | [
"Given",
"a",
"list",
"of",
"template",
"directories",
"compile",
"them",
"into",
"a",
"single",
"template",
"directory",
".",
"Templates",
"with",
"the",
"same",
"name",
"will",
"be",
"overridden",
"with",
"preference",
"given",
"to",
"those",
"first",
"in",
"the",
"list",
"."
]
| 31ac81131de393ef4d5715f2d90a5641c8d991f8 | https://github.com/discolabs/grunt-shopify-theme-settings/blob/31ac81131de393ef4d5715f2d90a5641c8d991f8/tasks/shopify_theme_settings.js#L99-L116 |
45,818 | discolabs/grunt-shopify-theme-settings | tasks/shopify_theme_settings.js | addSwigFilters | function addSwigFilters() {
/**
* Zero padding function.
* Used as both a filter and internally here.
*
* @param input
* @param length
* @returns {string}
*/
function zeropad(input, length) {
input = input + ''; // Ensure input is a string.
length = length || 2; // Ensure a length is set.
return input.length >= length ? input : new Array(length - input.length + 1).join('0') + input;
}
/**
* Add a very simple range filter that handles integers with step = 1.
*
* @return []
*/
swig.setFilter('range', function(start, stop, step) {
var range = [];
for(var i = start; i <= stop; i += step) {
range.push(i);
}
return range;
});
/**
* Convert a string in hh:mm format to the number of seconds after midnight it represents.
*
* @return in
*/
swig.setFilter('hhmm_to_seconds', function(hhmm) {
var parts = hhmm.split(':');
return parts[0] * 60 * 60 + parts[1] * 60;
});
/**
*
*/
swig.setFilter('seconds_to_hhmm', function(seconds) {
var date = new Date(seconds * 1000);
return zeropad(date.getUTCHours()) + ':' + zeropad(date.getUTCMinutes());
});
/**
* Add a filter to zero-pad the input to the given length (default 2).
*/
swig.setFilter('zeropad', zeropad);
} | javascript | function addSwigFilters() {
/**
* Zero padding function.
* Used as both a filter and internally here.
*
* @param input
* @param length
* @returns {string}
*/
function zeropad(input, length) {
input = input + ''; // Ensure input is a string.
length = length || 2; // Ensure a length is set.
return input.length >= length ? input : new Array(length - input.length + 1).join('0') + input;
}
/**
* Add a very simple range filter that handles integers with step = 1.
*
* @return []
*/
swig.setFilter('range', function(start, stop, step) {
var range = [];
for(var i = start; i <= stop; i += step) {
range.push(i);
}
return range;
});
/**
* Convert a string in hh:mm format to the number of seconds after midnight it represents.
*
* @return in
*/
swig.setFilter('hhmm_to_seconds', function(hhmm) {
var parts = hhmm.split(':');
return parts[0] * 60 * 60 + parts[1] * 60;
});
/**
*
*/
swig.setFilter('seconds_to_hhmm', function(seconds) {
var date = new Date(seconds * 1000);
return zeropad(date.getUTCHours()) + ':' + zeropad(date.getUTCMinutes());
});
/**
* Add a filter to zero-pad the input to the given length (default 2).
*/
swig.setFilter('zeropad', zeropad);
} | [
"function",
"addSwigFilters",
"(",
")",
"{",
"/**\n * Zero padding function.\n * Used as both a filter and internally here.\n *\n * @param input\n * @param length\n * @returns {string}\n */",
"function",
"zeropad",
"(",
"input",
",",
"length",
")",
"{",
"input",
"=",
"input",
"+",
"''",
";",
"// Ensure input is a string.",
"length",
"=",
"length",
"||",
"2",
";",
"// Ensure a length is set.",
"return",
"input",
".",
"length",
">=",
"length",
"?",
"input",
":",
"new",
"Array",
"(",
"length",
"-",
"input",
".",
"length",
"+",
"1",
")",
".",
"join",
"(",
"'0'",
")",
"+",
"input",
";",
"}",
"/**\n * Add a very simple range filter that handles integers with step = 1.\n *\n * @return []\n */",
"swig",
".",
"setFilter",
"(",
"'range'",
",",
"function",
"(",
"start",
",",
"stop",
",",
"step",
")",
"{",
"var",
"range",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"start",
";",
"i",
"<=",
"stop",
";",
"i",
"+=",
"step",
")",
"{",
"range",
".",
"push",
"(",
"i",
")",
";",
"}",
"return",
"range",
";",
"}",
")",
";",
"/**\n * Convert a string in hh:mm format to the number of seconds after midnight it represents.\n *\n * @return in\n */",
"swig",
".",
"setFilter",
"(",
"'hhmm_to_seconds'",
",",
"function",
"(",
"hhmm",
")",
"{",
"var",
"parts",
"=",
"hhmm",
".",
"split",
"(",
"':'",
")",
";",
"return",
"parts",
"[",
"0",
"]",
"*",
"60",
"*",
"60",
"+",
"parts",
"[",
"1",
"]",
"*",
"60",
";",
"}",
")",
";",
"/**\n *\n */",
"swig",
".",
"setFilter",
"(",
"'seconds_to_hhmm'",
",",
"function",
"(",
"seconds",
")",
"{",
"var",
"date",
"=",
"new",
"Date",
"(",
"seconds",
"*",
"1000",
")",
";",
"return",
"zeropad",
"(",
"date",
".",
"getUTCHours",
"(",
")",
")",
"+",
"':'",
"+",
"zeropad",
"(",
"date",
".",
"getUTCMinutes",
"(",
")",
")",
";",
"}",
")",
";",
"/**\n * Add a filter to zero-pad the input to the given length (default 2).\n */",
"swig",
".",
"setFilter",
"(",
"'zeropad'",
",",
"zeropad",
")",
";",
"}"
]
| Add some custom filters to Swig for use in templates. | [
"Add",
"some",
"custom",
"filters",
"to",
"Swig",
"for",
"use",
"in",
"templates",
"."
]
| 31ac81131de393ef4d5715f2d90a5641c8d991f8 | https://github.com/discolabs/grunt-shopify-theme-settings/blob/31ac81131de393ef4d5715f2d90a5641c8d991f8/tasks/shopify_theme_settings.js#L121-L173 |
45,819 | discolabs/grunt-shopify-theme-settings | tasks/shopify_theme_settings.js | zeropad | function zeropad(input, length) {
input = input + ''; // Ensure input is a string.
length = length || 2; // Ensure a length is set.
return input.length >= length ? input : new Array(length - input.length + 1).join('0') + input;
} | javascript | function zeropad(input, length) {
input = input + ''; // Ensure input is a string.
length = length || 2; // Ensure a length is set.
return input.length >= length ? input : new Array(length - input.length + 1).join('0') + input;
} | [
"function",
"zeropad",
"(",
"input",
",",
"length",
")",
"{",
"input",
"=",
"input",
"+",
"''",
";",
"// Ensure input is a string.",
"length",
"=",
"length",
"||",
"2",
";",
"// Ensure a length is set.",
"return",
"input",
".",
"length",
">=",
"length",
"?",
"input",
":",
"new",
"Array",
"(",
"length",
"-",
"input",
".",
"length",
"+",
"1",
")",
".",
"join",
"(",
"'0'",
")",
"+",
"input",
";",
"}"
]
| Zero padding function.
Used as both a filter and internally here.
@param input
@param length
@returns {string} | [
"Zero",
"padding",
"function",
".",
"Used",
"as",
"both",
"a",
"filter",
"and",
"internally",
"here",
"."
]
| 31ac81131de393ef4d5715f2d90a5641c8d991f8 | https://github.com/discolabs/grunt-shopify-theme-settings/blob/31ac81131de393ef4d5715f2d90a5641c8d991f8/tasks/shopify_theme_settings.js#L131-L135 |
45,820 | jhermsmeier/gulp-rm | index.js | rmdirWalk | function rmdirWalk( ls, done ) {
if( ls.length === 0 ) return done()
fs.rmdir( ls.shift().path, function( error ) {
if( error ) log( error.message )
rmdirWalk( ls, done )
})
} | javascript | function rmdirWalk( ls, done ) {
if( ls.length === 0 ) return done()
fs.rmdir( ls.shift().path, function( error ) {
if( error ) log( error.message )
rmdirWalk( ls, done )
})
} | [
"function",
"rmdirWalk",
"(",
"ls",
",",
"done",
")",
"{",
"if",
"(",
"ls",
".",
"length",
"===",
"0",
")",
"return",
"done",
"(",
")",
"fs",
".",
"rmdir",
"(",
"ls",
".",
"shift",
"(",
")",
".",
"path",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"log",
"(",
"error",
".",
"message",
")",
"rmdirWalk",
"(",
"ls",
",",
"done",
")",
"}",
")",
"}"
]
| Walk an array of directories and
delete one after another
@param {Array<Object>} ls
@param {Function} done | [
"Walk",
"an",
"array",
"of",
"directories",
"and",
"delete",
"one",
"after",
"another"
]
| 73a223b13b55030b0201da313124a42f4163eafb | https://github.com/jhermsmeier/gulp-rm/blob/73a223b13b55030b0201da313124a42f4163eafb/index.js#L12-L18 |
45,821 | koajs/atomic-session | lib/mongodb.js | Session | function Session(context) {
this.context = context
this.cookies = context.cookies
this.update = this.update.bind(this)
} | javascript | function Session(context) {
this.context = context
this.cookies = context.cookies
this.update = this.update.bind(this)
} | [
"function",
"Session",
"(",
"context",
")",
"{",
"this",
".",
"context",
"=",
"context",
"this",
".",
"cookies",
"=",
"context",
".",
"cookies",
"this",
".",
"update",
"=",
"this",
".",
"update",
".",
"bind",
"(",
"this",
")",
"}"
]
| Session constructor. | [
"Session",
"constructor",
"."
]
| 5ef7ccd8ae2189e1e35a9422670f83d7b7ba079a | https://github.com/koajs/atomic-session/blob/5ef7ccd8ae2189e1e35a9422670f83d7b7ba079a/lib/mongodb.js#L90-L94 |
45,822 | adriann0/npm-aprs-parser | lib/SymbolIconUtils.js | function (symbol) {
return symbolDict[symbol.charCodeAt(0)] && symbolDict[symbol.charCodeAt(0)][symbol.charCodeAt(1)] || symbolDict[symbol.charCodeAt(1)] && symbolDict[symbol.charCodeAt(0)][symbol.charCodeAt(0)];
} | javascript | function (symbol) {
return symbolDict[symbol.charCodeAt(0)] && symbolDict[symbol.charCodeAt(0)][symbol.charCodeAt(1)] || symbolDict[symbol.charCodeAt(1)] && symbolDict[symbol.charCodeAt(0)][symbol.charCodeAt(0)];
} | [
"function",
"(",
"symbol",
")",
"{",
"return",
"symbolDict",
"[",
"symbol",
".",
"charCodeAt",
"(",
"0",
")",
"]",
"&&",
"symbolDict",
"[",
"symbol",
".",
"charCodeAt",
"(",
"0",
")",
"]",
"[",
"symbol",
".",
"charCodeAt",
"(",
"1",
")",
"]",
"||",
"symbolDict",
"[",
"symbol",
".",
"charCodeAt",
"(",
"1",
")",
"]",
"&&",
"symbolDict",
"[",
"symbol",
".",
"charCodeAt",
"(",
"0",
")",
"]",
"[",
"symbol",
".",
"charCodeAt",
"(",
"0",
")",
"]",
";",
"}"
]
| table + symbol id | [
"table",
"+",
"symbol",
"id"
]
| c189e758cca0641a37c426ebd4c9e0a880d6bdb3 | https://github.com/adriann0/npm-aprs-parser/blob/c189e758cca0641a37c426ebd4c9e0a880d6bdb3/lib/SymbolIconUtils.js#L204-L206 |
|
45,823 | LastLeaf/epub-generator | lib/builder.js | function(){
STATIC_FILES.forEach(function(file){
addFile(fs.createReadStream(__dirname + '/templates/' + file), { name: file });
});
} | javascript | function(){
STATIC_FILES.forEach(function(file){
addFile(fs.createReadStream(__dirname + '/templates/' + file), { name: file });
});
} | [
"function",
"(",
")",
"{",
"STATIC_FILES",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"addFile",
"(",
"fs",
".",
"createReadStream",
"(",
"__dirname",
"+",
"'/templates/'",
"+",
"file",
")",
",",
"{",
"name",
":",
"file",
"}",
")",
";",
"}",
")",
";",
"}"
]
| add static files | [
"add",
"static",
"files"
]
| de7191f990c6c61dc4ff55238e79be7517e46bc3 | https://github.com/LastLeaf/epub-generator/blob/de7191f990c6c61dc4ff55238e79be7517e46bc3/lib/builder.js#L46-L50 |
|
45,824 | LastLeaf/epub-generator | lib/builder.js | function(){
for(var i=0; i<DYNAMIC_FILES.length; i++) {
addFile(dynamicFilesCompiled[i](options), { name: DYNAMIC_FILES[i] });
}
} | javascript | function(){
for(var i=0; i<DYNAMIC_FILES.length; i++) {
addFile(dynamicFilesCompiled[i](options), { name: DYNAMIC_FILES[i] });
}
} | [
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"DYNAMIC_FILES",
".",
"length",
";",
"i",
"++",
")",
"{",
"addFile",
"(",
"dynamicFilesCompiled",
"[",
"i",
"]",
"(",
"options",
")",
",",
"{",
"name",
":",
"DYNAMIC_FILES",
"[",
"i",
"]",
"}",
")",
";",
"}",
"}"
]
| add dynamic files | [
"add",
"dynamic",
"files"
]
| de7191f990c6c61dc4ff55238e79be7517e46bc3 | https://github.com/LastLeaf/epub-generator/blob/de7191f990c6c61dc4ff55238e79be7517e46bc3/lib/builder.js#L53-L57 |
|
45,825 | nebrius/transport-logger | lib/transportlogger.js | Transport | function Transport(settings, levels) {
settings = settings || {};
this.levels = levels;
// Set the base settings
this.settings = {
levels: levels,
timestamp: !!settings.timestamp,
prependLevel: !!settings.prependLevel,
colorize: !!settings.colorize,
name: settings.name
};
// Parse the min logging level
this.settings.minLevel = settings.hasOwnProperty('minLevel') ? settings.minLevel : DEFAULT_MIN_LEVEL;
if (this.settings.minLevel && getLevelIndex(this.settings.minLevel, levels) === -1) {
throw new Error('Invalid minimum logging level "' + this.settings.minLevel + '"');
}
// Determine the stream
if (settings.destination) {
if (typeof settings.destination === 'string' || settings.destination instanceof String) {
ensurePathExists(path.dirname(settings.destination));
this.stream = fs.createWriteStream(settings.destination, {
flags: 'a'
});
this.destination = settings.destination;
if (fs.existsSync(settings.destination)) {
this.lineCount = fs.readFileSync(settings.destination).toString().split('\n').length;
}
if (typeof settings.maxLines != 'undefined') {
this.maxLines = settings.maxLines;
}
} else if (['object', 'function'].indexOf(typeof settings.destination) !== -1 && settings.destination instanceof stream.Writable) {
this.stream = settings.destination;
} else {
throw new Error('Invalid destination specified. A destination must be a string, a writable stream instance, or undefined');
}
}
// Set/create the formatter method
this.formatter = settings.formatter ? settings.formatter : defaultFormatter;
} | javascript | function Transport(settings, levels) {
settings = settings || {};
this.levels = levels;
// Set the base settings
this.settings = {
levels: levels,
timestamp: !!settings.timestamp,
prependLevel: !!settings.prependLevel,
colorize: !!settings.colorize,
name: settings.name
};
// Parse the min logging level
this.settings.minLevel = settings.hasOwnProperty('minLevel') ? settings.minLevel : DEFAULT_MIN_LEVEL;
if (this.settings.minLevel && getLevelIndex(this.settings.minLevel, levels) === -1) {
throw new Error('Invalid minimum logging level "' + this.settings.minLevel + '"');
}
// Determine the stream
if (settings.destination) {
if (typeof settings.destination === 'string' || settings.destination instanceof String) {
ensurePathExists(path.dirname(settings.destination));
this.stream = fs.createWriteStream(settings.destination, {
flags: 'a'
});
this.destination = settings.destination;
if (fs.existsSync(settings.destination)) {
this.lineCount = fs.readFileSync(settings.destination).toString().split('\n').length;
}
if (typeof settings.maxLines != 'undefined') {
this.maxLines = settings.maxLines;
}
} else if (['object', 'function'].indexOf(typeof settings.destination) !== -1 && settings.destination instanceof stream.Writable) {
this.stream = settings.destination;
} else {
throw new Error('Invalid destination specified. A destination must be a string, a writable stream instance, or undefined');
}
}
// Set/create the formatter method
this.formatter = settings.formatter ? settings.formatter : defaultFormatter;
} | [
"function",
"Transport",
"(",
"settings",
",",
"levels",
")",
"{",
"settings",
"=",
"settings",
"||",
"{",
"}",
";",
"this",
".",
"levels",
"=",
"levels",
";",
"// Set the base settings",
"this",
".",
"settings",
"=",
"{",
"levels",
":",
"levels",
",",
"timestamp",
":",
"!",
"!",
"settings",
".",
"timestamp",
",",
"prependLevel",
":",
"!",
"!",
"settings",
".",
"prependLevel",
",",
"colorize",
":",
"!",
"!",
"settings",
".",
"colorize",
",",
"name",
":",
"settings",
".",
"name",
"}",
";",
"// Parse the min logging level",
"this",
".",
"settings",
".",
"minLevel",
"=",
"settings",
".",
"hasOwnProperty",
"(",
"'minLevel'",
")",
"?",
"settings",
".",
"minLevel",
":",
"DEFAULT_MIN_LEVEL",
";",
"if",
"(",
"this",
".",
"settings",
".",
"minLevel",
"&&",
"getLevelIndex",
"(",
"this",
".",
"settings",
".",
"minLevel",
",",
"levels",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid minimum logging level \"'",
"+",
"this",
".",
"settings",
".",
"minLevel",
"+",
"'\"'",
")",
";",
"}",
"// Determine the stream",
"if",
"(",
"settings",
".",
"destination",
")",
"{",
"if",
"(",
"typeof",
"settings",
".",
"destination",
"===",
"'string'",
"||",
"settings",
".",
"destination",
"instanceof",
"String",
")",
"{",
"ensurePathExists",
"(",
"path",
".",
"dirname",
"(",
"settings",
".",
"destination",
")",
")",
";",
"this",
".",
"stream",
"=",
"fs",
".",
"createWriteStream",
"(",
"settings",
".",
"destination",
",",
"{",
"flags",
":",
"'a'",
"}",
")",
";",
"this",
".",
"destination",
"=",
"settings",
".",
"destination",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"settings",
".",
"destination",
")",
")",
"{",
"this",
".",
"lineCount",
"=",
"fs",
".",
"readFileSync",
"(",
"settings",
".",
"destination",
")",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"length",
";",
"}",
"if",
"(",
"typeof",
"settings",
".",
"maxLines",
"!=",
"'undefined'",
")",
"{",
"this",
".",
"maxLines",
"=",
"settings",
".",
"maxLines",
";",
"}",
"}",
"else",
"if",
"(",
"[",
"'object'",
",",
"'function'",
"]",
".",
"indexOf",
"(",
"typeof",
"settings",
".",
"destination",
")",
"!==",
"-",
"1",
"&&",
"settings",
".",
"destination",
"instanceof",
"stream",
".",
"Writable",
")",
"{",
"this",
".",
"stream",
"=",
"settings",
".",
"destination",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid destination specified. A destination must be a string, a writable stream instance, or undefined'",
")",
";",
"}",
"}",
"// Set/create the formatter method",
"this",
".",
"formatter",
"=",
"settings",
".",
"formatter",
"?",
"settings",
".",
"formatter",
":",
"defaultFormatter",
";",
"}"
]
| Settings for creating a transport.
@name module:transport-logger.TransportSettings
@type Object
@property {Boolean} [timestamp] Timestamps each log message with a UTC date (default false)
@property {Boolean} [prependLevel] Prepends each log message with the log level (default false)
@property {String} [minLevel] The minimum logging level (default DEFAULT_MIN_LEVEL)
@property {Function} [formatter] A function to format messages with
@property {String | stream.Writable} [destination] The path to the log file
@property {String} [name] The name of the stream
@property {Number} [maxLines] The maximum number of lines to log befor rolling over to a new file. This only
applies to file transports created using a string path for the destination. | [
"Settings",
"for",
"creating",
"a",
"transport",
"."
]
| d9a0eef021ac9511ed215e688ddb4ca97392eea1 | https://github.com/nebrius/transport-logger/blob/d9a0eef021ac9511ed215e688ddb4ca97392eea1/lib/transportlogger.js#L103-L145 |
45,826 | nebrius/transport-logger | lib/transportlogger.js | Logger | function Logger(transports, settings) {
var i, len,
transport,
levels,
transportInstances = [],
names = {};
// Normalize the inputs
if (!transports) {
transports = [{}];
} else if (!Array.isArray(transports)) {
transports = [transports];
}
settings = settings || {};
levels = settings.levels || DEFAULT_LEVELS;
// Create the transports
for (i = 0, len = transports.length; i < len; i++) {
transport = transports[i];
if (transport.name) {
names[transport.name] = 1;
}
transportInstances.push(new Transport(transport, levels));
}
// Create the log methods
levels.forEach(function (level) {
this[level.id] = function log() {
var i, ilen, j, jlen,
p,
messages = Array.prototype.slice.call(arguments, 0),
transportMessages = new Array(messages.length),
areNamed = new Array(messages.length),
areAnyNamed = false,
message,
isNamed;
for (i = 0, ilen = messages.length; i < ilen; i++) {
message = messages[i];
isNamed = false;
if (typeof message === 'object') {
isNamed = true;
for (p in message) {
if (message.hasOwnProperty(p)) {
if (!names[p]) {
isNamed = false;
}
}
}
}
areNamed[i] = isNamed;
areAnyNamed = areAnyNamed || isNamed;
}
for (i = 0, ilen = transportInstances.length; i < ilen; i++) {
if (areAnyNamed) {
for (j = 0, jlen = messages.length; j < jlen; j++) {
if (areNamed[j]) {
transportMessages[j] = messages[j][transportInstances[i].settings.name];
} else {
transportMessages[j] = messages[j];
}
}
transportInstances[i].log(transportMessages, level);
} else {
transportInstances[i].log(messages, level);
}
}
};
}.bind(this));
} | javascript | function Logger(transports, settings) {
var i, len,
transport,
levels,
transportInstances = [],
names = {};
// Normalize the inputs
if (!transports) {
transports = [{}];
} else if (!Array.isArray(transports)) {
transports = [transports];
}
settings = settings || {};
levels = settings.levels || DEFAULT_LEVELS;
// Create the transports
for (i = 0, len = transports.length; i < len; i++) {
transport = transports[i];
if (transport.name) {
names[transport.name] = 1;
}
transportInstances.push(new Transport(transport, levels));
}
// Create the log methods
levels.forEach(function (level) {
this[level.id] = function log() {
var i, ilen, j, jlen,
p,
messages = Array.prototype.slice.call(arguments, 0),
transportMessages = new Array(messages.length),
areNamed = new Array(messages.length),
areAnyNamed = false,
message,
isNamed;
for (i = 0, ilen = messages.length; i < ilen; i++) {
message = messages[i];
isNamed = false;
if (typeof message === 'object') {
isNamed = true;
for (p in message) {
if (message.hasOwnProperty(p)) {
if (!names[p]) {
isNamed = false;
}
}
}
}
areNamed[i] = isNamed;
areAnyNamed = areAnyNamed || isNamed;
}
for (i = 0, ilen = transportInstances.length; i < ilen; i++) {
if (areAnyNamed) {
for (j = 0, jlen = messages.length; j < jlen; j++) {
if (areNamed[j]) {
transportMessages[j] = messages[j][transportInstances[i].settings.name];
} else {
transportMessages[j] = messages[j];
}
}
transportInstances[i].log(transportMessages, level);
} else {
transportInstances[i].log(messages, level);
}
}
};
}.bind(this));
} | [
"function",
"Logger",
"(",
"transports",
",",
"settings",
")",
"{",
"var",
"i",
",",
"len",
",",
"transport",
",",
"levels",
",",
"transportInstances",
"=",
"[",
"]",
",",
"names",
"=",
"{",
"}",
";",
"// Normalize the inputs",
"if",
"(",
"!",
"transports",
")",
"{",
"transports",
"=",
"[",
"{",
"}",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"transports",
")",
")",
"{",
"transports",
"=",
"[",
"transports",
"]",
";",
"}",
"settings",
"=",
"settings",
"||",
"{",
"}",
";",
"levels",
"=",
"settings",
".",
"levels",
"||",
"DEFAULT_LEVELS",
";",
"// Create the transports",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"transports",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"transport",
"=",
"transports",
"[",
"i",
"]",
";",
"if",
"(",
"transport",
".",
"name",
")",
"{",
"names",
"[",
"transport",
".",
"name",
"]",
"=",
"1",
";",
"}",
"transportInstances",
".",
"push",
"(",
"new",
"Transport",
"(",
"transport",
",",
"levels",
")",
")",
";",
"}",
"// Create the log methods",
"levels",
".",
"forEach",
"(",
"function",
"(",
"level",
")",
"{",
"this",
"[",
"level",
".",
"id",
"]",
"=",
"function",
"log",
"(",
")",
"{",
"var",
"i",
",",
"ilen",
",",
"j",
",",
"jlen",
",",
"p",
",",
"messages",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
",",
"transportMessages",
"=",
"new",
"Array",
"(",
"messages",
".",
"length",
")",
",",
"areNamed",
"=",
"new",
"Array",
"(",
"messages",
".",
"length",
")",
",",
"areAnyNamed",
"=",
"false",
",",
"message",
",",
"isNamed",
";",
"for",
"(",
"i",
"=",
"0",
",",
"ilen",
"=",
"messages",
".",
"length",
";",
"i",
"<",
"ilen",
";",
"i",
"++",
")",
"{",
"message",
"=",
"messages",
"[",
"i",
"]",
";",
"isNamed",
"=",
"false",
";",
"if",
"(",
"typeof",
"message",
"===",
"'object'",
")",
"{",
"isNamed",
"=",
"true",
";",
"for",
"(",
"p",
"in",
"message",
")",
"{",
"if",
"(",
"message",
".",
"hasOwnProperty",
"(",
"p",
")",
")",
"{",
"if",
"(",
"!",
"names",
"[",
"p",
"]",
")",
"{",
"isNamed",
"=",
"false",
";",
"}",
"}",
"}",
"}",
"areNamed",
"[",
"i",
"]",
"=",
"isNamed",
";",
"areAnyNamed",
"=",
"areAnyNamed",
"||",
"isNamed",
";",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"ilen",
"=",
"transportInstances",
".",
"length",
";",
"i",
"<",
"ilen",
";",
"i",
"++",
")",
"{",
"if",
"(",
"areAnyNamed",
")",
"{",
"for",
"(",
"j",
"=",
"0",
",",
"jlen",
"=",
"messages",
".",
"length",
";",
"j",
"<",
"jlen",
";",
"j",
"++",
")",
"{",
"if",
"(",
"areNamed",
"[",
"j",
"]",
")",
"{",
"transportMessages",
"[",
"j",
"]",
"=",
"messages",
"[",
"j",
"]",
"[",
"transportInstances",
"[",
"i",
"]",
".",
"settings",
".",
"name",
"]",
";",
"}",
"else",
"{",
"transportMessages",
"[",
"j",
"]",
"=",
"messages",
"[",
"j",
"]",
";",
"}",
"}",
"transportInstances",
"[",
"i",
"]",
".",
"log",
"(",
"transportMessages",
",",
"level",
")",
";",
"}",
"else",
"{",
"transportInstances",
"[",
"i",
"]",
".",
"log",
"(",
"messages",
",",
"level",
")",
";",
"}",
"}",
"}",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| The global settings for the logger that applies to all transports
@name module:transport-logger.GlobalSettings
@type Object
@property {Object} [levels] The log levels
@property {String} <log-level> The key specifies the log level, and the value specifies the color. Colors are one of
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', and 'normal'
Creates a new logger instance
@name module:transport-logger.Logger
@constructor
@param {TransportSettings | TransportSettings[]} [transports] The transports to use
@param {GlobalSettings} [settings] The global settings | [
"The",
"global",
"settings",
"for",
"the",
"logger",
"that",
"applies",
"to",
"all",
"transports"
]
| d9a0eef021ac9511ed215e688ddb4ca97392eea1 | https://github.com/nebrius/transport-logger/blob/d9a0eef021ac9511ed215e688ddb4ca97392eea1/lib/transportlogger.js#L217-L285 |
45,827 | jan-swiecki/node-autowire | lib/ModuleFinder.js | mapAllNames | function mapAllNames(path) {
log("[%s] Mapping %s", self.parentModuleName, path);
fs.readdirSync(path).forEach(function(p){
var absPath = PATH.resolve(path+PATH.sep+p);
var lstat = fs.lstatSync(absPath);
if(lstat.isFile() && isModule(p)) {
var name = getModuleName(p);
self.updateNameCache(name, absPath);
} else if(! isIgnoreFolder(p) && lstat.isDirectory()) {
mapAllNames(absPath);
}
});
function isIgnoreFolder(folderName) {
return !folderName || folderName === 'node_modules' || folderName[0] === '.';
}
function isModule(p) {
return p.match(/\.(js|json)$/);
}
function getModuleName(p) {
return p.replace(/\.(js|json)$/, '');
}
} | javascript | function mapAllNames(path) {
log("[%s] Mapping %s", self.parentModuleName, path);
fs.readdirSync(path).forEach(function(p){
var absPath = PATH.resolve(path+PATH.sep+p);
var lstat = fs.lstatSync(absPath);
if(lstat.isFile() && isModule(p)) {
var name = getModuleName(p);
self.updateNameCache(name, absPath);
} else if(! isIgnoreFolder(p) && lstat.isDirectory()) {
mapAllNames(absPath);
}
});
function isIgnoreFolder(folderName) {
return !folderName || folderName === 'node_modules' || folderName[0] === '.';
}
function isModule(p) {
return p.match(/\.(js|json)$/);
}
function getModuleName(p) {
return p.replace(/\.(js|json)$/, '');
}
} | [
"function",
"mapAllNames",
"(",
"path",
")",
"{",
"log",
"(",
"\"[%s] Mapping %s\"",
",",
"self",
".",
"parentModuleName",
",",
"path",
")",
";",
"fs",
".",
"readdirSync",
"(",
"path",
")",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"absPath",
"=",
"PATH",
".",
"resolve",
"(",
"path",
"+",
"PATH",
".",
"sep",
"+",
"p",
")",
";",
"var",
"lstat",
"=",
"fs",
".",
"lstatSync",
"(",
"absPath",
")",
";",
"if",
"(",
"lstat",
".",
"isFile",
"(",
")",
"&&",
"isModule",
"(",
"p",
")",
")",
"{",
"var",
"name",
"=",
"getModuleName",
"(",
"p",
")",
";",
"self",
".",
"updateNameCache",
"(",
"name",
",",
"absPath",
")",
";",
"}",
"else",
"if",
"(",
"!",
"isIgnoreFolder",
"(",
"p",
")",
"&&",
"lstat",
".",
"isDirectory",
"(",
")",
")",
"{",
"mapAllNames",
"(",
"absPath",
")",
";",
"}",
"}",
")",
";",
"function",
"isIgnoreFolder",
"(",
"folderName",
")",
"{",
"return",
"!",
"folderName",
"||",
"folderName",
"===",
"'node_modules'",
"||",
"folderName",
"[",
"0",
"]",
"===",
"'.'",
";",
"}",
"function",
"isModule",
"(",
"p",
")",
"{",
"return",
"p",
".",
"match",
"(",
"/",
"\\.(js|json)$",
"/",
")",
";",
"}",
"function",
"getModuleName",
"(",
"p",
")",
"{",
"return",
"p",
".",
"replace",
"(",
"/",
"\\.(js|json)$",
"/",
",",
"''",
")",
";",
"}",
"}"
]
| Saves absPath -> filename mapping in the map
@param path | [
"Saves",
"absPath",
"-",
">",
"filename",
"mapping",
"in",
"the",
"map"
]
| a5bddb8d1d581ffab9c23e2a50c8fedede83ec1b | https://github.com/jan-swiecki/node-autowire/blob/a5bddb8d1d581ffab9c23e2a50c8fedede83ec1b/lib/ModuleFinder.js#L338-L363 |
45,828 | jan-swiecki/node-autowire | lib/ModuleFinder.js | findProjectRoot | function findProjectRoot(startPath) {
log.trace("findProjectRoot startPath = %s", startPath);
if(isDiskRoot()) {
if(hasPackageJson()) {
return startPath;
} else {
throw new Error("Cannot find project root");
}
} else if(hasPackageJson()) {
return startPath;
} else {
return findProjectRoot(PATH.resolve(startPath+PATH.sep+".."));
}
function hasPackageJson() {
return fs.existsSync(startPath+PATH.sep+"package.json");
}
function isDiskRoot() {
return startPath.match(/^([A-Z]:\\\\|\/)$/);
}
} | javascript | function findProjectRoot(startPath) {
log.trace("findProjectRoot startPath = %s", startPath);
if(isDiskRoot()) {
if(hasPackageJson()) {
return startPath;
} else {
throw new Error("Cannot find project root");
}
} else if(hasPackageJson()) {
return startPath;
} else {
return findProjectRoot(PATH.resolve(startPath+PATH.sep+".."));
}
function hasPackageJson() {
return fs.existsSync(startPath+PATH.sep+"package.json");
}
function isDiskRoot() {
return startPath.match(/^([A-Z]:\\\\|\/)$/);
}
} | [
"function",
"findProjectRoot",
"(",
"startPath",
")",
"{",
"log",
".",
"trace",
"(",
"\"findProjectRoot startPath = %s\"",
",",
"startPath",
")",
";",
"if",
"(",
"isDiskRoot",
"(",
")",
")",
"{",
"if",
"(",
"hasPackageJson",
"(",
")",
")",
"{",
"return",
"startPath",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"Cannot find project root\"",
")",
";",
"}",
"}",
"else",
"if",
"(",
"hasPackageJson",
"(",
")",
")",
"{",
"return",
"startPath",
";",
"}",
"else",
"{",
"return",
"findProjectRoot",
"(",
"PATH",
".",
"resolve",
"(",
"startPath",
"+",
"PATH",
".",
"sep",
"+",
"\"..\"",
")",
")",
";",
"}",
"function",
"hasPackageJson",
"(",
")",
"{",
"return",
"fs",
".",
"existsSync",
"(",
"startPath",
"+",
"PATH",
".",
"sep",
"+",
"\"package.json\"",
")",
";",
"}",
"function",
"isDiskRoot",
"(",
")",
"{",
"return",
"startPath",
".",
"match",
"(",
"/",
"^([A-Z]:\\\\\\\\|\\/)$",
"/",
")",
";",
"}",
"}"
]
| Going up the folder tree returns the first
folder with package.json present.
@param startPath
@returns {*} | [
"Going",
"up",
"the",
"folder",
"tree",
"returns",
"the",
"first",
"folder",
"with",
"package",
".",
"json",
"present",
"."
]
| a5bddb8d1d581ffab9c23e2a50c8fedede83ec1b | https://github.com/jan-swiecki/node-autowire/blob/a5bddb8d1d581ffab9c23e2a50c8fedede83ec1b/lib/ModuleFinder.js#L400-L421 |
45,829 | cettia/cettia-protocol | lib/transport-http-server.js | createLongpollTransport | function createLongpollTransport(req, res) {
// The current response which can be used to send a message or close the connection. It's not
// null when it's available and null when it's not available.
var response;
// A flag to mark this transport is aborted. It's used when `response` is not available, if
// user closes the connection.
var aborted;
// A timer to prevent from being idle connection which may happen if the succeeding poll
// request is not arrived.
var closeTimer;
// The parameters of the first request. That of subsequent requests are not used.
var params = req.params;
// A queue containing messages that the server couldn't send.
var queue = [];
// A transport object.
var self = createBaseTransport(req, res);
// In long polling, multiple HTTP exchanges are used to establish a channel for the server to
// write message to client. This function will be called every time the client performs a request.
self.refresh = function(req, res) {
// Any error on request-response should propagate to transport.
req.on("error", function(error) {
self.emit("error", error);
});
res.on("error", function(error) {
self.emit("error", error);
});
// When the underlying connection was terminated abnormally.
res.on("close", function() {
self.emit("close");
});
// When the complete response has been sent.
res.on("finish", function() {
// If this request was to `poll` and this response was ended through `end` not
// `endedWithMessage`, it means it is the end of the transport. Hence, fires the `close`
// event.
if (req.params["cettia-transport-when"] === "poll" && !res.endedWithMessage) {
self.emit("close");
// Otherwise the client will issue `poll` request again. If not, this connection falls
// into limbo. To prevent that, it sets a timer which fires `close` event unless the
// client issues `poll` request in 3s.
} else {
closeTimer = setTimeout(function() {
self.emit("close");
}, 3000);
}
});
// A custom property to show how it was ended through either `endWithMessage` for sending a
// message or `end` for closing the connection. An ended response can't be used again.
res.endedWithMessage = false;
// A custom method to send a message through this response.
res.endWithMessage = function(data) {
// Flags the current response is ended with message.
res.endedWithMessage = true;
// `data` should be either a `Buffer` or a string.
if (typeof data === "string") {
// As for text message, the content-type header should be `text/javascript` for JSONP
// and `text/plain` for the others.
res.setHeader("content-type", "text/" +
// If it's JSONP, `cettia-transport-jsonp` param is `true`.
(params["cettia-transport-jsonp"] === "true" ? "javascript" : "plain") + "; charset=utf-8");
// All the long polling transports have to finish the request after processing. The
// `res`'s `finish` event will be fired after this.
res.end(params["cettia-transport-jsonp"] === "true" ?
// In case of JSONP, the response text is supposed to be a JavaScript code executing a
// callback with data. The callback name is passed as the first request's
// `cettia-transport-callback` param and the data to be returned have to be escaped to
// a JavaScript string literal. For others, no formatting is needed. In any case,
// data should be encoded in `utf-8`.
params["cettia-transport-callback"] + "(" + JSON.stringify(data) + ");" : data, "utf-8");
} else {
// As for binary message, the content-type header should be `application/octet-stream`.
// Old browsers depending on JSONP can't handle binary data so we don't need to consider
// them here.
res.setHeader("content-type", "application/octet-stream");
res.end(data);
}
};
switch (req.params["cettia-transport-when"]) {
// The first request
case "open":
// `script` tag which is a host object used in old browsers to perform long polling
// transport can't read HTTP response headers as well as write HTTP request headers. That's
// why we uses the first response's body as a handshake output instead of HTTP headers. The
// handshake result should be formatted in URI.
res.endWithMessage(url.format({
// Adds the following transport protocol headers:
// * `cettia-transport-id`: an identifier.
// * `cettia-transport-version`: the implemented long polling transport version.
query: {
"cettia-transport-version": "1.0",
"cettia-transport-id": self.id
}
}));
break;
// The succeeding request after the first request
case "poll":
// Resets timer as new exchange is supplied.
clearTimeout(closeTimer);
// If aborted is `true` here, it means the user tried to close the connection but it
// couldn't be done because `response` was null. So ends this incoming exchange. It will
// fire `close` event through `res`'s `finish` event handler.
if (aborted) {
res.end();
} else {
// If the queue is not empty, it means there are remaining messages so that the server
// should send them again.
if (queue.length) {
// Removes the first cached message from the queue and send it. FYI,
// `[1,2,3].shift()` returns in `1` and results in `[2,3]`.
res.endWithMessage(queue.shift());
} else {
// If not, assigns `res` to `response`.
response = res;
}
}
break;
// It shouldn't happen.
default:
self.emit("error", new Error("protocol"));
self.close();
break;
}
};
self.write = function(data) {
// Only when the current response exists, it's possible to send a message.
if (response) {
// After `response.endWithMessage`, `response` can't be used again.
var resp = response;
response = null;
resp.endWithMessage(data);
// If not, the data will be cached and sent in next poll through `refresh` method.
} else {
queue.push(data);
}
};
self.close = function() {
// Only when the current response exists, it's possible to close the
// connection.
if (response) {
// After `response.end`, `response` can't be used again.
var resp = response;
response = null;
resp.end();
// If not, a next poll request will be ended immediately by `aborted` flag through
// `refresh` method.
} else {
aborted = true;
}
return this;
};
// Refreshes with the first exchange.
self.refresh(req, res);
return self;
} | javascript | function createLongpollTransport(req, res) {
// The current response which can be used to send a message or close the connection. It's not
// null when it's available and null when it's not available.
var response;
// A flag to mark this transport is aborted. It's used when `response` is not available, if
// user closes the connection.
var aborted;
// A timer to prevent from being idle connection which may happen if the succeeding poll
// request is not arrived.
var closeTimer;
// The parameters of the first request. That of subsequent requests are not used.
var params = req.params;
// A queue containing messages that the server couldn't send.
var queue = [];
// A transport object.
var self = createBaseTransport(req, res);
// In long polling, multiple HTTP exchanges are used to establish a channel for the server to
// write message to client. This function will be called every time the client performs a request.
self.refresh = function(req, res) {
// Any error on request-response should propagate to transport.
req.on("error", function(error) {
self.emit("error", error);
});
res.on("error", function(error) {
self.emit("error", error);
});
// When the underlying connection was terminated abnormally.
res.on("close", function() {
self.emit("close");
});
// When the complete response has been sent.
res.on("finish", function() {
// If this request was to `poll` and this response was ended through `end` not
// `endedWithMessage`, it means it is the end of the transport. Hence, fires the `close`
// event.
if (req.params["cettia-transport-when"] === "poll" && !res.endedWithMessage) {
self.emit("close");
// Otherwise the client will issue `poll` request again. If not, this connection falls
// into limbo. To prevent that, it sets a timer which fires `close` event unless the
// client issues `poll` request in 3s.
} else {
closeTimer = setTimeout(function() {
self.emit("close");
}, 3000);
}
});
// A custom property to show how it was ended through either `endWithMessage` for sending a
// message or `end` for closing the connection. An ended response can't be used again.
res.endedWithMessage = false;
// A custom method to send a message through this response.
res.endWithMessage = function(data) {
// Flags the current response is ended with message.
res.endedWithMessage = true;
// `data` should be either a `Buffer` or a string.
if (typeof data === "string") {
// As for text message, the content-type header should be `text/javascript` for JSONP
// and `text/plain` for the others.
res.setHeader("content-type", "text/" +
// If it's JSONP, `cettia-transport-jsonp` param is `true`.
(params["cettia-transport-jsonp"] === "true" ? "javascript" : "plain") + "; charset=utf-8");
// All the long polling transports have to finish the request after processing. The
// `res`'s `finish` event will be fired after this.
res.end(params["cettia-transport-jsonp"] === "true" ?
// In case of JSONP, the response text is supposed to be a JavaScript code executing a
// callback with data. The callback name is passed as the first request's
// `cettia-transport-callback` param and the data to be returned have to be escaped to
// a JavaScript string literal. For others, no formatting is needed. In any case,
// data should be encoded in `utf-8`.
params["cettia-transport-callback"] + "(" + JSON.stringify(data) + ");" : data, "utf-8");
} else {
// As for binary message, the content-type header should be `application/octet-stream`.
// Old browsers depending on JSONP can't handle binary data so we don't need to consider
// them here.
res.setHeader("content-type", "application/octet-stream");
res.end(data);
}
};
switch (req.params["cettia-transport-when"]) {
// The first request
case "open":
// `script` tag which is a host object used in old browsers to perform long polling
// transport can't read HTTP response headers as well as write HTTP request headers. That's
// why we uses the first response's body as a handshake output instead of HTTP headers. The
// handshake result should be formatted in URI.
res.endWithMessage(url.format({
// Adds the following transport protocol headers:
// * `cettia-transport-id`: an identifier.
// * `cettia-transport-version`: the implemented long polling transport version.
query: {
"cettia-transport-version": "1.0",
"cettia-transport-id": self.id
}
}));
break;
// The succeeding request after the first request
case "poll":
// Resets timer as new exchange is supplied.
clearTimeout(closeTimer);
// If aborted is `true` here, it means the user tried to close the connection but it
// couldn't be done because `response` was null. So ends this incoming exchange. It will
// fire `close` event through `res`'s `finish` event handler.
if (aborted) {
res.end();
} else {
// If the queue is not empty, it means there are remaining messages so that the server
// should send them again.
if (queue.length) {
// Removes the first cached message from the queue and send it. FYI,
// `[1,2,3].shift()` returns in `1` and results in `[2,3]`.
res.endWithMessage(queue.shift());
} else {
// If not, assigns `res` to `response`.
response = res;
}
}
break;
// It shouldn't happen.
default:
self.emit("error", new Error("protocol"));
self.close();
break;
}
};
self.write = function(data) {
// Only when the current response exists, it's possible to send a message.
if (response) {
// After `response.endWithMessage`, `response` can't be used again.
var resp = response;
response = null;
resp.endWithMessage(data);
// If not, the data will be cached and sent in next poll through `refresh` method.
} else {
queue.push(data);
}
};
self.close = function() {
// Only when the current response exists, it's possible to close the
// connection.
if (response) {
// After `response.end`, `response` can't be used again.
var resp = response;
response = null;
resp.end();
// If not, a next poll request will be ended immediately by `aborted` flag through
// `refresh` method.
} else {
aborted = true;
}
return this;
};
// Refreshes with the first exchange.
self.refresh(req, res);
return self;
} | [
"function",
"createLongpollTransport",
"(",
"req",
",",
"res",
")",
"{",
"// The current response which can be used to send a message or close the connection. It's not",
"// null when it's available and null when it's not available.",
"var",
"response",
";",
"// A flag to mark this transport is aborted. It's used when `response` is not available, if",
"// user closes the connection.",
"var",
"aborted",
";",
"// A timer to prevent from being idle connection which may happen if the succeeding poll",
"// request is not arrived.",
"var",
"closeTimer",
";",
"// The parameters of the first request. That of subsequent requests are not used.",
"var",
"params",
"=",
"req",
".",
"params",
";",
"// A queue containing messages that the server couldn't send.",
"var",
"queue",
"=",
"[",
"]",
";",
"// A transport object.",
"var",
"self",
"=",
"createBaseTransport",
"(",
"req",
",",
"res",
")",
";",
"// In long polling, multiple HTTP exchanges are used to establish a channel for the server to",
"// write message to client. This function will be called every time the client performs a request.",
"self",
".",
"refresh",
"=",
"function",
"(",
"req",
",",
"res",
")",
"{",
"// Any error on request-response should propagate to transport.",
"req",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"error",
")",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"error",
")",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"error",
")",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"error",
")",
";",
"}",
")",
";",
"// When the underlying connection was terminated abnormally.",
"res",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"}",
")",
";",
"// When the complete response has been sent.",
"res",
".",
"on",
"(",
"\"finish\"",
",",
"function",
"(",
")",
"{",
"// If this request was to `poll` and this response was ended through `end` not",
"// `endedWithMessage`, it means it is the end of the transport. Hence, fires the `close`",
"// event.",
"if",
"(",
"req",
".",
"params",
"[",
"\"cettia-transport-when\"",
"]",
"===",
"\"poll\"",
"&&",
"!",
"res",
".",
"endedWithMessage",
")",
"{",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"// Otherwise the client will issue `poll` request again. If not, this connection falls",
"// into limbo. To prevent that, it sets a timer which fires `close` event unless the",
"// client issues `poll` request in 3s.",
"}",
"else",
"{",
"closeTimer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"}",
",",
"3000",
")",
";",
"}",
"}",
")",
";",
"// A custom property to show how it was ended through either `endWithMessage` for sending a",
"// message or `end` for closing the connection. An ended response can't be used again.",
"res",
".",
"endedWithMessage",
"=",
"false",
";",
"// A custom method to send a message through this response.",
"res",
".",
"endWithMessage",
"=",
"function",
"(",
"data",
")",
"{",
"// Flags the current response is ended with message.",
"res",
".",
"endedWithMessage",
"=",
"true",
";",
"// `data` should be either a `Buffer` or a string.",
"if",
"(",
"typeof",
"data",
"===",
"\"string\"",
")",
"{",
"// As for text message, the content-type header should be `text/javascript` for JSONP",
"// and `text/plain` for the others.",
"res",
".",
"setHeader",
"(",
"\"content-type\"",
",",
"\"text/\"",
"+",
"// If it's JSONP, `cettia-transport-jsonp` param is `true`.",
"(",
"params",
"[",
"\"cettia-transport-jsonp\"",
"]",
"===",
"\"true\"",
"?",
"\"javascript\"",
":",
"\"plain\"",
")",
"+",
"\"; charset=utf-8\"",
")",
";",
"// All the long polling transports have to finish the request after processing. The",
"// `res`'s `finish` event will be fired after this.",
"res",
".",
"end",
"(",
"params",
"[",
"\"cettia-transport-jsonp\"",
"]",
"===",
"\"true\"",
"?",
"// In case of JSONP, the response text is supposed to be a JavaScript code executing a",
"// callback with data. The callback name is passed as the first request's",
"// `cettia-transport-callback` param and the data to be returned have to be escaped to",
"// a JavaScript string literal. For others, no formatting is needed. In any case,",
"// data should be encoded in `utf-8`.",
"params",
"[",
"\"cettia-transport-callback\"",
"]",
"+",
"\"(\"",
"+",
"JSON",
".",
"stringify",
"(",
"data",
")",
"+",
"\");\"",
":",
"data",
",",
"\"utf-8\"",
")",
";",
"}",
"else",
"{",
"// As for binary message, the content-type header should be `application/octet-stream`.",
"// Old browsers depending on JSONP can't handle binary data so we don't need to consider",
"// them here.",
"res",
".",
"setHeader",
"(",
"\"content-type\"",
",",
"\"application/octet-stream\"",
")",
";",
"res",
".",
"end",
"(",
"data",
")",
";",
"}",
"}",
";",
"switch",
"(",
"req",
".",
"params",
"[",
"\"cettia-transport-when\"",
"]",
")",
"{",
"// The first request",
"case",
"\"open\"",
":",
"// `script` tag which is a host object used in old browsers to perform long polling",
"// transport can't read HTTP response headers as well as write HTTP request headers. That's",
"// why we uses the first response's body as a handshake output instead of HTTP headers. The",
"// handshake result should be formatted in URI.",
"res",
".",
"endWithMessage",
"(",
"url",
".",
"format",
"(",
"{",
"// Adds the following transport protocol headers:",
"// * `cettia-transport-id`: an identifier.",
"// * `cettia-transport-version`: the implemented long polling transport version.",
"query",
":",
"{",
"\"cettia-transport-version\"",
":",
"\"1.0\"",
",",
"\"cettia-transport-id\"",
":",
"self",
".",
"id",
"}",
"}",
")",
")",
";",
"break",
";",
"// The succeeding request after the first request",
"case",
"\"poll\"",
":",
"// Resets timer as new exchange is supplied.",
"clearTimeout",
"(",
"closeTimer",
")",
";",
"// If aborted is `true` here, it means the user tried to close the connection but it",
"// couldn't be done because `response` was null. So ends this incoming exchange. It will",
"// fire `close` event through `res`'s `finish` event handler.",
"if",
"(",
"aborted",
")",
"{",
"res",
".",
"end",
"(",
")",
";",
"}",
"else",
"{",
"// If the queue is not empty, it means there are remaining messages so that the server",
"// should send them again.",
"if",
"(",
"queue",
".",
"length",
")",
"{",
"// Removes the first cached message from the queue and send it. FYI,",
"// `[1,2,3].shift()` returns in `1` and results in `[2,3]`.",
"res",
".",
"endWithMessage",
"(",
"queue",
".",
"shift",
"(",
")",
")",
";",
"}",
"else",
"{",
"// If not, assigns `res` to `response`.",
"response",
"=",
"res",
";",
"}",
"}",
"break",
";",
"// It shouldn't happen.",
"default",
":",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"new",
"Error",
"(",
"\"protocol\"",
")",
")",
";",
"self",
".",
"close",
"(",
")",
";",
"break",
";",
"}",
"}",
";",
"self",
".",
"write",
"=",
"function",
"(",
"data",
")",
"{",
"// Only when the current response exists, it's possible to send a message.",
"if",
"(",
"response",
")",
"{",
"// After `response.endWithMessage`, `response` can't be used again.",
"var",
"resp",
"=",
"response",
";",
"response",
"=",
"null",
";",
"resp",
".",
"endWithMessage",
"(",
"data",
")",
";",
"// If not, the data will be cached and sent in next poll through `refresh` method.",
"}",
"else",
"{",
"queue",
".",
"push",
"(",
"data",
")",
";",
"}",
"}",
";",
"self",
".",
"close",
"=",
"function",
"(",
")",
"{",
"// Only when the current response exists, it's possible to close the",
"// connection.",
"if",
"(",
"response",
")",
"{",
"// After `response.end`, `response` can't be used again.",
"var",
"resp",
"=",
"response",
";",
"response",
"=",
"null",
";",
"resp",
".",
"end",
"(",
")",
";",
"// If not, a next poll request will be ended immediately by `aborted` flag through",
"// `refresh` method.",
"}",
"else",
"{",
"aborted",
"=",
"true",
";",
"}",
"return",
"this",
";",
"}",
";",
"// Refreshes with the first exchange.",
"self",
".",
"refresh",
"(",
"req",
",",
"res",
")",
";",
"return",
"self",
";",
"}"
]
| The client performs a HTTP persistent connection and the server ends the response with data. Then, the client receives it and performs a request again and again. | [
"The",
"client",
"performs",
"a",
"HTTP",
"persistent",
"connection",
"and",
"the",
"server",
"ends",
"the",
"response",
"with",
"data",
".",
"Then",
"the",
"client",
"receives",
"it",
"and",
"performs",
"a",
"request",
"again",
"and",
"again",
"."
]
| 9af3b578a9ae7b33099932903b52faeb2ca92528 | https://github.com/cettia/cettia-protocol/blob/9af3b578a9ae7b33099932903b52faeb2ca92528/lib/transport-http-server.js#L271-L425 |
45,830 | eladnava/koa-async | wrapper.js | wrapAsyncMethod | function wrapAsyncMethod(fn, ctx) {
return function() {
// Obtain function arguments
var args = [].slice.call(arguments);
// Return a thunkified function that receives a done callback
return new Promise(function(resolve, reject) {
// Add a custom callback to provided args
args.push(function(err, result) {
// Failed?
if (err) {
return reject(err);
}
// Success
resolve(result);
});
// Call original function
fn.apply(ctx, args);
});
};
} | javascript | function wrapAsyncMethod(fn, ctx) {
return function() {
// Obtain function arguments
var args = [].slice.call(arguments);
// Return a thunkified function that receives a done callback
return new Promise(function(resolve, reject) {
// Add a custom callback to provided args
args.push(function(err, result) {
// Failed?
if (err) {
return reject(err);
}
// Success
resolve(result);
});
// Call original function
fn.apply(ctx, args);
});
};
} | [
"function",
"wrapAsyncMethod",
"(",
"fn",
",",
"ctx",
")",
"{",
"return",
"function",
"(",
")",
"{",
"// Obtain function arguments",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"// Return a thunkified function that receives a done callback",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"// Add a custom callback to provided args",
"args",
".",
"push",
"(",
"function",
"(",
"err",
",",
"result",
")",
"{",
"// Failed?",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"// Success",
"resolve",
"(",
"result",
")",
";",
"}",
")",
";",
"// Call original function",
"fn",
".",
"apply",
"(",
"ctx",
",",
"args",
")",
";",
"}",
")",
";",
"}",
";",
"}"
]
| Wrap async methods inside a promise | [
"Wrap",
"async",
"methods",
"inside",
"a",
"promise"
]
| e1f2b3a483c0c8dde853bbc29860b96bcf91707a | https://github.com/eladnava/koa-async/blob/e1f2b3a483c0c8dde853bbc29860b96bcf91707a/wrapper.js#L4-L26 |
45,831 | eladnava/koa-async | wrapper.js | wrapAsync | function wrapAsync() {
// Traverse async methods
for (var fn in async) {
// Promisify the method
async[fn] = wrapAsyncMethod(async[fn], async);
}
// Return co-friendly async object
return async;
} | javascript | function wrapAsync() {
// Traverse async methods
for (var fn in async) {
// Promisify the method
async[fn] = wrapAsyncMethod(async[fn], async);
}
// Return co-friendly async object
return async;
} | [
"function",
"wrapAsync",
"(",
")",
"{",
"// Traverse async methods",
"for",
"(",
"var",
"fn",
"in",
"async",
")",
"{",
"// Promisify the method",
"async",
"[",
"fn",
"]",
"=",
"wrapAsyncMethod",
"(",
"async",
"[",
"fn",
"]",
",",
"async",
")",
";",
"}",
"// Return co-friendly async object",
"return",
"async",
";",
"}"
]
| Wraps an async object with co-friendly functions | [
"Wraps",
"an",
"async",
"object",
"with",
"co",
"-",
"friendly",
"functions"
]
| e1f2b3a483c0c8dde853bbc29860b96bcf91707a | https://github.com/eladnava/koa-async/blob/e1f2b3a483c0c8dde853bbc29860b96bcf91707a/wrapper.js#L29-L38 |
45,832 | silas/node-mesos | lib/marathon.js | Marathon | function Marathon(opts) {
if (!(this instanceof Marathon)) {
return new Marathon(opts);
}
opts = opts || {};
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || '8080') + '/v2';
}
opts.name = 'marathon';
opts.type = 'json';
papi.Client.call(this, opts);
this.app = new App(this);
this.eventSubscription = new EventSubscription(this);
} | javascript | function Marathon(opts) {
if (!(this instanceof Marathon)) {
return new Marathon(opts);
}
opts = opts || {};
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || '8080') + '/v2';
}
opts.name = 'marathon';
opts.type = 'json';
papi.Client.call(this, opts);
this.app = new App(this);
this.eventSubscription = new EventSubscription(this);
} | [
"function",
"Marathon",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Marathon",
")",
")",
"{",
"return",
"new",
"Marathon",
"(",
"opts",
")",
";",
"}",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"opts",
".",
"baseUrl",
")",
"{",
"opts",
".",
"baseUrl",
"=",
"(",
"opts",
".",
"secure",
"?",
"'https:'",
":",
"'http:'",
")",
"+",
"'//'",
"+",
"(",
"opts",
".",
"host",
"||",
"'127.0.0.1'",
")",
"+",
"':'",
"+",
"(",
"opts",
".",
"port",
"||",
"'8080'",
")",
"+",
"'/v2'",
";",
"}",
"opts",
".",
"name",
"=",
"'marathon'",
";",
"opts",
".",
"type",
"=",
"'json'",
";",
"papi",
".",
"Client",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"this",
".",
"app",
"=",
"new",
"App",
"(",
"this",
")",
";",
"this",
".",
"eventSubscription",
"=",
"new",
"EventSubscription",
"(",
"this",
")",
";",
"}"
]
| Initialize a new `Marathon` client.
@param {Object} opts | [
"Initialize",
"a",
"new",
"Marathon",
"client",
"."
]
| 157ca9fa9cfeb13def49cf8f6ef53ff7e708da95 | https://github.com/silas/node-mesos/blob/157ca9fa9cfeb13def49cf8f6ef53ff7e708da95/lib/marathon.js#L25-L44 |
45,833 | jordangarcia/nuclear-js-react-addons | src/nuclearMixin.js | getState | function getState(reactor, data) {
var state = {}
each(data, function(value, key) {
state[key] = reactor.evaluate(value)
})
return state
} | javascript | function getState(reactor, data) {
var state = {}
each(data, function(value, key) {
state[key] = reactor.evaluate(value)
})
return state
} | [
"function",
"getState",
"(",
"reactor",
",",
"data",
")",
"{",
"var",
"state",
"=",
"{",
"}",
"each",
"(",
"data",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"state",
"[",
"key",
"]",
"=",
"reactor",
".",
"evaluate",
"(",
"value",
")",
"}",
")",
"return",
"state",
"}"
]
| Returns a mapping of the getDataBinding keys to
the reactor values | [
"Returns",
"a",
"mapping",
"of",
"the",
"getDataBinding",
"keys",
"to",
"the",
"reactor",
"values"
]
| 5550ebd6ec07bfec01aa557908735142613dcdb3 | https://github.com/jordangarcia/nuclear-js-react-addons/blob/5550ebd6ec07bfec01aa557908735142613dcdb3/src/nuclearMixin.js#L18-L24 |
45,834 | IonicaBizau/fs-file-tree | lib/index.js | fsFileTree | function fsFileTree (inputPath, opts, cb) {
let result = {};
if (typeof inputPath === "function") {
cb = inputPath;
inputPath = process.cwd();
opts = {};
} else if (typeof opts === "function") {
cb = opts;
if (typeof inputPath === "object") {
opts = inputPath;
inputPath = process.cwd();
} else {
opts = {};
}
}
readDir(inputPath, (err, items) => {
if (err) { return cb(err); }
sameTime(bindy(items, (c, done) => {
let basename = path.basename(c.path);
if (basename.charAt(0) === "." && !opts.all) {
return done();
}
if (opts.camelCase) {
basename = camelo(basename);
}
if (c.stat.isDirectory()) {
return fsFileTree(c.path, opts, (err, res) => {
if (err) { return done(err); }
result[basename] = res;
done();
});
}
result[basename] = c;
done();
}), err => cb(err, result));
});
} | javascript | function fsFileTree (inputPath, opts, cb) {
let result = {};
if (typeof inputPath === "function") {
cb = inputPath;
inputPath = process.cwd();
opts = {};
} else if (typeof opts === "function") {
cb = opts;
if (typeof inputPath === "object") {
opts = inputPath;
inputPath = process.cwd();
} else {
opts = {};
}
}
readDir(inputPath, (err, items) => {
if (err) { return cb(err); }
sameTime(bindy(items, (c, done) => {
let basename = path.basename(c.path);
if (basename.charAt(0) === "." && !opts.all) {
return done();
}
if (opts.camelCase) {
basename = camelo(basename);
}
if (c.stat.isDirectory()) {
return fsFileTree(c.path, opts, (err, res) => {
if (err) { return done(err); }
result[basename] = res;
done();
});
}
result[basename] = c;
done();
}), err => cb(err, result));
});
} | [
"function",
"fsFileTree",
"(",
"inputPath",
",",
"opts",
",",
"cb",
")",
"{",
"let",
"result",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"inputPath",
"===",
"\"function\"",
")",
"{",
"cb",
"=",
"inputPath",
";",
"inputPath",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"opts",
"=",
"{",
"}",
";",
"}",
"else",
"if",
"(",
"typeof",
"opts",
"===",
"\"function\"",
")",
"{",
"cb",
"=",
"opts",
";",
"if",
"(",
"typeof",
"inputPath",
"===",
"\"object\"",
")",
"{",
"opts",
"=",
"inputPath",
";",
"inputPath",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"}",
"else",
"{",
"opts",
"=",
"{",
"}",
";",
"}",
"}",
"readDir",
"(",
"inputPath",
",",
"(",
"err",
",",
"items",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"sameTime",
"(",
"bindy",
"(",
"items",
",",
"(",
"c",
",",
"done",
")",
"=>",
"{",
"let",
"basename",
"=",
"path",
".",
"basename",
"(",
"c",
".",
"path",
")",
";",
"if",
"(",
"basename",
".",
"charAt",
"(",
"0",
")",
"===",
"\".\"",
"&&",
"!",
"opts",
".",
"all",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"if",
"(",
"opts",
".",
"camelCase",
")",
"{",
"basename",
"=",
"camelo",
"(",
"basename",
")",
";",
"}",
"if",
"(",
"c",
".",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
"fsFileTree",
"(",
"c",
".",
"path",
",",
"opts",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"err",
")",
";",
"}",
"result",
"[",
"basename",
"]",
"=",
"res",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
"result",
"[",
"basename",
"]",
"=",
"c",
";",
"done",
"(",
")",
";",
"}",
")",
",",
"err",
"=>",
"cb",
"(",
"err",
",",
"result",
")",
")",
";",
"}",
")",
";",
"}"
]
| fsFileTree
Get a directory file tree as an object.
@name fsFileTree
@function
@param {String} inputPath The input path.
@param {Object} opts An object containing the following fields:
- `camelCase` (Boolean): Convert the file names in camelcase format (to be easily accessible using dot notation).
- `all` (Boolean): If `true`, it will include the hidden files/directories.
@param {Function} cb The callback function. | [
"fsFileTree",
"Get",
"a",
"directory",
"file",
"tree",
"as",
"an",
"object",
"."
]
| a16cf9258ef96734b4767d546edd17616d61df21 | https://github.com/IonicaBizau/fs-file-tree/blob/a16cf9258ef96734b4767d546edd17616d61df21/lib/index.js#L24-L65 |
45,835 | gragland/react-component-data | src/resolveRecursive.js | walkTree | function walkTree(element, context, mergeProps, visitor) {
const Component = element.type;
if (typeof Component === 'function') {
const props = assign({}, Component.defaultProps, element.props, (mergeProps || {}));
let childContext = context;
let child;
// Are we are a react class?
// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L66
if (Component.prototype && Component.prototype.isReactComponent) {
const instance = new Component(props, context);
// In case the user doesn't pass these to super in the constructor
instance.props = instance.props || props;
instance.context = instance.context || context;
// Override setState to just change the state, not queue up an update.
// We can't do the default React thing as we aren't mounted "properly"
// however, we don't need to re-render as well only support setState in
// componentWillMount, which happens *before* rendere.
instance.setState = (newState) => {
instance.state = assign({}, instance.state, newState);
};
// This is a poor man's version of
// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L181
if (instance.componentWillMount) {
instance.componentWillMount();
}
if (instance.getChildContext) {
childContext = assign({}, context, instance.getChildContext());
}
// Query we need to resolve first so stop traversing.
if (visitor(element, instance, context) === false) {
return;
}
child = instance.render();
} else { // just a stateless functional
// Query we need to resolve first so stop traversing.
if (visitor(element, null, context) === false) {
return;
}
child = Component(props, context);
}
if (child) {
walkTree(child, childContext, null, visitor);
}
} else { // a basic string or dom element, just get children
// Query we need to resolve first so stop traversing.
if (visitor(element, null, context) === false) {
return;
}
// Multiple children, traverse each one.
if (element.props && element.props.children) {
React.Children.forEach(element.props.children, (child) => {
if (child) {
walkTree(child, context, null, visitor);
}
});
}
}
} | javascript | function walkTree(element, context, mergeProps, visitor) {
const Component = element.type;
if (typeof Component === 'function') {
const props = assign({}, Component.defaultProps, element.props, (mergeProps || {}));
let childContext = context;
let child;
// Are we are a react class?
// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L66
if (Component.prototype && Component.prototype.isReactComponent) {
const instance = new Component(props, context);
// In case the user doesn't pass these to super in the constructor
instance.props = instance.props || props;
instance.context = instance.context || context;
// Override setState to just change the state, not queue up an update.
// We can't do the default React thing as we aren't mounted "properly"
// however, we don't need to re-render as well only support setState in
// componentWillMount, which happens *before* rendere.
instance.setState = (newState) => {
instance.state = assign({}, instance.state, newState);
};
// This is a poor man's version of
// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L181
if (instance.componentWillMount) {
instance.componentWillMount();
}
if (instance.getChildContext) {
childContext = assign({}, context, instance.getChildContext());
}
// Query we need to resolve first so stop traversing.
if (visitor(element, instance, context) === false) {
return;
}
child = instance.render();
} else { // just a stateless functional
// Query we need to resolve first so stop traversing.
if (visitor(element, null, context) === false) {
return;
}
child = Component(props, context);
}
if (child) {
walkTree(child, childContext, null, visitor);
}
} else { // a basic string or dom element, just get children
// Query we need to resolve first so stop traversing.
if (visitor(element, null, context) === false) {
return;
}
// Multiple children, traverse each one.
if (element.props && element.props.children) {
React.Children.forEach(element.props.children, (child) => {
if (child) {
walkTree(child, context, null, visitor);
}
});
}
}
} | [
"function",
"walkTree",
"(",
"element",
",",
"context",
",",
"mergeProps",
",",
"visitor",
")",
"{",
"const",
"Component",
"=",
"element",
".",
"type",
";",
"if",
"(",
"typeof",
"Component",
"===",
"'function'",
")",
"{",
"const",
"props",
"=",
"assign",
"(",
"{",
"}",
",",
"Component",
".",
"defaultProps",
",",
"element",
".",
"props",
",",
"(",
"mergeProps",
"||",
"{",
"}",
")",
")",
";",
"let",
"childContext",
"=",
"context",
";",
"let",
"child",
";",
"// Are we are a react class?",
"// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L66",
"if",
"(",
"Component",
".",
"prototype",
"&&",
"Component",
".",
"prototype",
".",
"isReactComponent",
")",
"{",
"const",
"instance",
"=",
"new",
"Component",
"(",
"props",
",",
"context",
")",
";",
"// In case the user doesn't pass these to super in the constructor",
"instance",
".",
"props",
"=",
"instance",
".",
"props",
"||",
"props",
";",
"instance",
".",
"context",
"=",
"instance",
".",
"context",
"||",
"context",
";",
"// Override setState to just change the state, not queue up an update.",
"// We can't do the default React thing as we aren't mounted \"properly\"",
"// however, we don't need to re-render as well only support setState in",
"// componentWillMount, which happens *before* rendere.",
"instance",
".",
"setState",
"=",
"(",
"newState",
")",
"=>",
"{",
"instance",
".",
"state",
"=",
"assign",
"(",
"{",
"}",
",",
"instance",
".",
"state",
",",
"newState",
")",
";",
"}",
";",
"// This is a poor man's version of",
"// https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L181",
"if",
"(",
"instance",
".",
"componentWillMount",
")",
"{",
"instance",
".",
"componentWillMount",
"(",
")",
";",
"}",
"if",
"(",
"instance",
".",
"getChildContext",
")",
"{",
"childContext",
"=",
"assign",
"(",
"{",
"}",
",",
"context",
",",
"instance",
".",
"getChildContext",
"(",
")",
")",
";",
"}",
"// Query we need to resolve first so stop traversing.",
"if",
"(",
"visitor",
"(",
"element",
",",
"instance",
",",
"context",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"child",
"=",
"instance",
".",
"render",
"(",
")",
";",
"}",
"else",
"{",
"// just a stateless functional",
"// Query we need to resolve first so stop traversing.",
"if",
"(",
"visitor",
"(",
"element",
",",
"null",
",",
"context",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"child",
"=",
"Component",
"(",
"props",
",",
"context",
")",
";",
"}",
"if",
"(",
"child",
")",
"{",
"walkTree",
"(",
"child",
",",
"childContext",
",",
"null",
",",
"visitor",
")",
";",
"}",
"}",
"else",
"{",
"// a basic string or dom element, just get children",
"// Query we need to resolve first so stop traversing.",
"if",
"(",
"visitor",
"(",
"element",
",",
"null",
",",
"context",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"// Multiple children, traverse each one.",
"if",
"(",
"element",
".",
"props",
"&&",
"element",
".",
"props",
".",
"children",
")",
"{",
"React",
".",
"Children",
".",
"forEach",
"(",
"element",
".",
"props",
".",
"children",
",",
"(",
"child",
")",
"=>",
"{",
"if",
"(",
"child",
")",
"{",
"walkTree",
"(",
"child",
",",
"context",
",",
"null",
",",
"visitor",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}"
]
| Recurse an React Element tree, running visitor on each element. If visitor returns `false`, don't call the element's render function or recurse into its child elements | [
"Recurse",
"an",
"React",
"Element",
"tree",
"running",
"visitor",
"on",
"each",
"element",
".",
"If",
"visitor",
"returns",
"false",
"don",
"t",
"call",
"the",
"element",
"s",
"render",
"function",
"or",
"recurse",
"into",
"its",
"child",
"elements"
]
| 788397f133e4d327e074689f17b3f8e47abdaf2e | https://github.com/gragland/react-component-data/blob/788397f133e4d327e074689f17b3f8e47abdaf2e/src/resolveRecursive.js#L10-L88 |
45,836 | gragland/react-component-data | src/resolveRecursive.js | getDataFromTree | function getDataFromTree(rootElement, rootContext, fetchRoot, mergeProps, isTopLevel){
//console.log(`Now searching element (${rootElement.type.name || rootElement.type.displayName}):`, rootElement);
// Get array of queries (fetchData promises) from tree
// This will traverse down recursively looking for fetchData() methods
let queries = getQueriesFromTree(rootElement, rootContext, fetchRoot, mergeProps);
// No queries found. We're done!
if (!queries.length) {
return Promise.resolve();
}
// We've traversed down as far as possible in thecurrent tree branch ...
// Wait on each query that we found, re-rendering the subtree when it's done.
const mappedQueries = queries.map(({ query, element, context }) => {
return query.then((newProps) => {
const displayName = element.type.displayName;
if (!displayName){
// TODO: Use Promise.reject and catch()
throw new Error('[React Component Data] When resolving component data recursively each component must have a displayName set.');
}
// Add to finalData array that will be returned
finalData[displayName] = newProps;
// Traverse children
// Component will use newProps returned by the query so we can find any children it might have as a result
return getDataFromTree(element, context, false, newProps);
})
});
return Promise.all(mappedQueries).then((values) => {
// Only return final data at top level
// Not inside recursive getDataFromTree calls
if (isTopLevel){
return finalData;
}
});
} | javascript | function getDataFromTree(rootElement, rootContext, fetchRoot, mergeProps, isTopLevel){
//console.log(`Now searching element (${rootElement.type.name || rootElement.type.displayName}):`, rootElement);
// Get array of queries (fetchData promises) from tree
// This will traverse down recursively looking for fetchData() methods
let queries = getQueriesFromTree(rootElement, rootContext, fetchRoot, mergeProps);
// No queries found. We're done!
if (!queries.length) {
return Promise.resolve();
}
// We've traversed down as far as possible in thecurrent tree branch ...
// Wait on each query that we found, re-rendering the subtree when it's done.
const mappedQueries = queries.map(({ query, element, context }) => {
return query.then((newProps) => {
const displayName = element.type.displayName;
if (!displayName){
// TODO: Use Promise.reject and catch()
throw new Error('[React Component Data] When resolving component data recursively each component must have a displayName set.');
}
// Add to finalData array that will be returned
finalData[displayName] = newProps;
// Traverse children
// Component will use newProps returned by the query so we can find any children it might have as a result
return getDataFromTree(element, context, false, newProps);
})
});
return Promise.all(mappedQueries).then((values) => {
// Only return final data at top level
// Not inside recursive getDataFromTree calls
if (isTopLevel){
return finalData;
}
});
} | [
"function",
"getDataFromTree",
"(",
"rootElement",
",",
"rootContext",
",",
"fetchRoot",
",",
"mergeProps",
",",
"isTopLevel",
")",
"{",
"//console.log(`Now searching element (${rootElement.type.name || rootElement.type.displayName}):`, rootElement);",
"// Get array of queries (fetchData promises) from tree",
"// This will traverse down recursively looking for fetchData() methods",
"let",
"queries",
"=",
"getQueriesFromTree",
"(",
"rootElement",
",",
"rootContext",
",",
"fetchRoot",
",",
"mergeProps",
")",
";",
"// No queries found. We're done!",
"if",
"(",
"!",
"queries",
".",
"length",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"// We've traversed down as far as possible in thecurrent tree branch ...",
"// Wait on each query that we found, re-rendering the subtree when it's done.",
"const",
"mappedQueries",
"=",
"queries",
".",
"map",
"(",
"(",
"{",
"query",
",",
"element",
",",
"context",
"}",
")",
"=>",
"{",
"return",
"query",
".",
"then",
"(",
"(",
"newProps",
")",
"=>",
"{",
"const",
"displayName",
"=",
"element",
".",
"type",
".",
"displayName",
";",
"if",
"(",
"!",
"displayName",
")",
"{",
"// TODO: Use Promise.reject and catch()",
"throw",
"new",
"Error",
"(",
"'[React Component Data] When resolving component data recursively each component must have a displayName set.'",
")",
";",
"}",
"// Add to finalData array that will be returned",
"finalData",
"[",
"displayName",
"]",
"=",
"newProps",
";",
"// Traverse children",
"// Component will use newProps returned by the query so we can find any children it might have as a result",
"return",
"getDataFromTree",
"(",
"element",
",",
"context",
",",
"false",
",",
"newProps",
")",
";",
"}",
")",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"mappedQueries",
")",
".",
"then",
"(",
"(",
"values",
")",
"=>",
"{",
"// Only return final data at top level",
"// Not inside recursive getDataFromTree calls",
"if",
"(",
"isTopLevel",
")",
"{",
"return",
"finalData",
";",
"}",
"}",
")",
";",
"}"
]
| XXX component Cache | [
"XXX",
"component",
"Cache"
]
| 788397f133e4d327e074689f17b3f8e47abdaf2e | https://github.com/gragland/react-component-data/blob/788397f133e4d327e074689f17b3f8e47abdaf2e/src/resolveRecursive.js#L130-L169 |
45,837 | rksm/estree-to-js | bin/estree-to-js.js | jsonSpec | function jsonSpec() {
return parsedArgs.specFile ?
read(parsedArgs.specFile).then(JSON.parse) :
require("../index").fetch(parsedArgs.urls)
.then(mdSource => require("../index").parse(mdSource))
} | javascript | function jsonSpec() {
return parsedArgs.specFile ?
read(parsedArgs.specFile).then(JSON.parse) :
require("../index").fetch(parsedArgs.urls)
.then(mdSource => require("../index").parse(mdSource))
} | [
"function",
"jsonSpec",
"(",
")",
"{",
"return",
"parsedArgs",
".",
"specFile",
"?",
"read",
"(",
"parsedArgs",
".",
"specFile",
")",
".",
"then",
"(",
"JSON",
".",
"parse",
")",
":",
"require",
"(",
"\"../index\"",
")",
".",
"fetch",
"(",
"parsedArgs",
".",
"urls",
")",
".",
"then",
"(",
"mdSource",
"=>",
"require",
"(",
"\"../index\"",
")",
".",
"parse",
"(",
"mdSource",
")",
")",
"}"
]
| -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- helpers | [
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"=",
"-",
"helpers"
]
| 3cb21c9c63ff329651f08197d353965e80551bd2 | https://github.com/rksm/estree-to-js/blob/3cb21c9c63ff329651f08197d353965e80551bd2/bin/estree-to-js.js#L53-L58 |
45,838 | cettia/cettia-protocol | lib/transport-websocket-server.js | createWebSocketTransport | function createWebSocketTransport(ws) {
// A transport object.
var self = new events.EventEmitter();
// Transport URI contains information like protocol header as query.
self.uri = ws.upgradeReq.url;
// Simply delegates WebSocket's events to transport and transport's behaviors to WebSocket.
ws.onmessage = function(event) {
// `event.data` is a message. It is string if text frame is sent and Buffer if binary frame
// is sent.
if (typeof event.data === "string") {
self.emit("text", event.data);
} else {
self.emit("binary", event.data);
}
};
ws.onerror = function(error) {
self.emit("error", error);
};
// A flag to check the transport is opened.
var opened = true;
ws.onclose = function() {
opened = false;
self.emit("close");
};
self.send = function(data) {
// Allows to send data only it is opened. If not, fires an error.
if (opened) {
// If `data` is string, a text frame is sent, and if it's Buffer, a binary frame is sent.
ws.send(data);
} else {
self.emit("error", new Error("notopened"));
}
return this;
};
self.close = function() {
ws.close();
return this;
};
return self;
} | javascript | function createWebSocketTransport(ws) {
// A transport object.
var self = new events.EventEmitter();
// Transport URI contains information like protocol header as query.
self.uri = ws.upgradeReq.url;
// Simply delegates WebSocket's events to transport and transport's behaviors to WebSocket.
ws.onmessage = function(event) {
// `event.data` is a message. It is string if text frame is sent and Buffer if binary frame
// is sent.
if (typeof event.data === "string") {
self.emit("text", event.data);
} else {
self.emit("binary", event.data);
}
};
ws.onerror = function(error) {
self.emit("error", error);
};
// A flag to check the transport is opened.
var opened = true;
ws.onclose = function() {
opened = false;
self.emit("close");
};
self.send = function(data) {
// Allows to send data only it is opened. If not, fires an error.
if (opened) {
// If `data` is string, a text frame is sent, and if it's Buffer, a binary frame is sent.
ws.send(data);
} else {
self.emit("error", new Error("notopened"));
}
return this;
};
self.close = function() {
ws.close();
return this;
};
return self;
} | [
"function",
"createWebSocketTransport",
"(",
"ws",
")",
"{",
"// A transport object.",
"var",
"self",
"=",
"new",
"events",
".",
"EventEmitter",
"(",
")",
";",
"// Transport URI contains information like protocol header as query.",
"self",
".",
"uri",
"=",
"ws",
".",
"upgradeReq",
".",
"url",
";",
"// Simply delegates WebSocket's events to transport and transport's behaviors to WebSocket.",
"ws",
".",
"onmessage",
"=",
"function",
"(",
"event",
")",
"{",
"// `event.data` is a message. It is string if text frame is sent and Buffer if binary frame",
"// is sent.",
"if",
"(",
"typeof",
"event",
".",
"data",
"===",
"\"string\"",
")",
"{",
"self",
".",
"emit",
"(",
"\"text\"",
",",
"event",
".",
"data",
")",
";",
"}",
"else",
"{",
"self",
".",
"emit",
"(",
"\"binary\"",
",",
"event",
".",
"data",
")",
";",
"}",
"}",
";",
"ws",
".",
"onerror",
"=",
"function",
"(",
"error",
")",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"error",
")",
";",
"}",
";",
"// A flag to check the transport is opened.",
"var",
"opened",
"=",
"true",
";",
"ws",
".",
"onclose",
"=",
"function",
"(",
")",
"{",
"opened",
"=",
"false",
";",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"}",
";",
"self",
".",
"send",
"=",
"function",
"(",
"data",
")",
"{",
"// Allows to send data only it is opened. If not, fires an error.",
"if",
"(",
"opened",
")",
"{",
"// If `data` is string, a text frame is sent, and if it's Buffer, a binary frame is sent.",
"ws",
".",
"send",
"(",
"data",
")",
";",
"}",
"else",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"new",
"Error",
"(",
"\"notopened\"",
")",
")",
";",
"}",
"return",
"this",
";",
"}",
";",
"self",
".",
"close",
"=",
"function",
"(",
")",
"{",
"ws",
".",
"close",
"(",
")",
";",
"return",
"this",
";",
"}",
";",
"return",
"self",
";",
"}"
]
| WebSocket is a protocol designed for a full-duplex communications over a TCP connection. | [
"WebSocket",
"is",
"a",
"protocol",
"designed",
"for",
"a",
"full",
"-",
"duplex",
"communications",
"over",
"a",
"TCP",
"connection",
"."
]
| 9af3b578a9ae7b33099932903b52faeb2ca92528 | https://github.com/cettia/cettia-protocol/blob/9af3b578a9ae7b33099932903b52faeb2ca92528/lib/transport-websocket-server.js#L30-L69 |
45,839 | flightjs/flight-with-state | src/index.js | cloneStateDef | function cloneStateDef(stateDef) {
stateDef = (stateDef || {});
return function () {
var ctx = this;
return Object.keys(stateDef).reduce((state, k) => {
var value = stateDef[k];
state[k] = (typeof value === 'function' ? value.call(ctx) : value);
return state;
}, {});
};
} | javascript | function cloneStateDef(stateDef) {
stateDef = (stateDef || {});
return function () {
var ctx = this;
return Object.keys(stateDef).reduce((state, k) => {
var value = stateDef[k];
state[k] = (typeof value === 'function' ? value.call(ctx) : value);
return state;
}, {});
};
} | [
"function",
"cloneStateDef",
"(",
"stateDef",
")",
"{",
"stateDef",
"=",
"(",
"stateDef",
"||",
"{",
"}",
")",
";",
"return",
"function",
"(",
")",
"{",
"var",
"ctx",
"=",
"this",
";",
"return",
"Object",
".",
"keys",
"(",
"stateDef",
")",
".",
"reduce",
"(",
"(",
"state",
",",
"k",
")",
"=>",
"{",
"var",
"value",
"=",
"stateDef",
"[",
"k",
"]",
";",
"state",
"[",
"k",
"]",
"=",
"(",
"typeof",
"value",
"===",
"'function'",
"?",
"value",
".",
"call",
"(",
"ctx",
")",
":",
"value",
")",
";",
"return",
"state",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
";",
"}"
]
| Returns a function that returns a clone of the object passed to it initially | [
"Returns",
"a",
"function",
"that",
"returns",
"a",
"clone",
"of",
"the",
"object",
"passed",
"to",
"it",
"initially"
]
| 3ccf726bdeff9778aabb04adab351eff3f852f46 | https://github.com/flightjs/flight-with-state/blob/3ccf726bdeff9778aabb04adab351eff3f852f46/src/index.js#L8-L18 |
45,840 | aholstenson/amounts | lib/quantity.js | createUnits | function createUnits(conversions, withNames=false) {
const result = {};
conversions.forEach(c => c.names.forEach(name =>
result[unitToLower(normalizeUnitName(name))] = {
name: c.names[0],
prefix: c.prefix,
scale: c.scale,
toBase: c.toBase,
fromBase: c.fromBase,
names: withNames ? c.names : null
}
));
return result;
} | javascript | function createUnits(conversions, withNames=false) {
const result = {};
conversions.forEach(c => c.names.forEach(name =>
result[unitToLower(normalizeUnitName(name))] = {
name: c.names[0],
prefix: c.prefix,
scale: c.scale,
toBase: c.toBase,
fromBase: c.fromBase,
names: withNames ? c.names : null
}
));
return result;
} | [
"function",
"createUnits",
"(",
"conversions",
",",
"withNames",
"=",
"false",
")",
"{",
"const",
"result",
"=",
"{",
"}",
";",
"conversions",
".",
"forEach",
"(",
"c",
"=>",
"c",
".",
"names",
".",
"forEach",
"(",
"name",
"=>",
"result",
"[",
"unitToLower",
"(",
"normalizeUnitName",
"(",
"name",
")",
")",
"]",
"=",
"{",
"name",
":",
"c",
".",
"names",
"[",
"0",
"]",
",",
"prefix",
":",
"c",
".",
"prefix",
",",
"scale",
":",
"c",
".",
"scale",
",",
"toBase",
":",
"c",
".",
"toBase",
",",
"fromBase",
":",
"c",
".",
"fromBase",
",",
"names",
":",
"withNames",
"?",
"c",
".",
"names",
":",
"null",
"}",
")",
")",
";",
"return",
"result",
";",
"}"
]
| Map a list of conversions into an object where each name is represented
as a key. | [
"Map",
"a",
"list",
"of",
"conversions",
"into",
"an",
"object",
"where",
"each",
"name",
"is",
"represented",
"as",
"a",
"key",
"."
]
| 04fdc68b782918eeaeae62bfcdcb0f20f7afb527 | https://github.com/aholstenson/amounts/blob/04fdc68b782918eeaeae62bfcdcb0f20f7afb527/lib/quantity.js#L113-L129 |
45,841 | aholstenson/amounts | lib/quantity.js | createUnitRegex | function createUnitRegex(units) {
return Object.keys(units)
.sort((a, b) => b.length - a.length)
.map(unit => unit.length > 2 ? caseInsensitivePart(unit) : unit)
.join('|');
} | javascript | function createUnitRegex(units) {
return Object.keys(units)
.sort((a, b) => b.length - a.length)
.map(unit => unit.length > 2 ? caseInsensitivePart(unit) : unit)
.join('|');
} | [
"function",
"createUnitRegex",
"(",
"units",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"units",
")",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"b",
".",
"length",
"-",
"a",
".",
"length",
")",
".",
"map",
"(",
"unit",
"=>",
"unit",
".",
"length",
">",
"2",
"?",
"caseInsensitivePart",
"(",
"unit",
")",
":",
"unit",
")",
".",
"join",
"(",
"'|'",
")",
";",
"}"
]
| Create a regex for the given associative object. | [
"Create",
"a",
"regex",
"for",
"the",
"given",
"associative",
"object",
"."
]
| 04fdc68b782918eeaeae62bfcdcb0f20f7afb527 | https://github.com/aholstenson/amounts/blob/04fdc68b782918eeaeae62bfcdcb0f20f7afb527/lib/quantity.js#L154-L159 |
45,842 | EspressoLogicCafe/APICreatorSDK | APICreatorSDK.js | function (url, key, password) {
var deferred, options, headers, liveapicreator;
liveapicreator = _.extend({}, SDK);
liveapicreator.url = this.stripWrappingSlashes(url);
liveapicreator.params = _.pick(URL.parse(url), 'host', 'path', 'port');
liveapicreator.params.headers = {};
if (url.match('https')) {
liveapicreator.req = https;
}
//passed a url with a defined port
if (liveapicreator.isUrlWithPort(liveapicreator.params.host)) {
liveapicreator.params.host = liveapicreator.stripUrlPort(liveapicreator.params.host);
}
deferred = Q.defer();
liveapicreator.connection = deferred.promise;
//Is this a username/password combo
if (password) {
options = liveapicreator.setOptions({method: 'POST'});
options.headers['Content-Type'] ='application/json';
options.path += liveapicreator.authEndpoint;
var req = liveapicreator.req.request(options, function (res) {
if (res.statusCode == 503) {
deferred.reject(res.statusCode);
}
res.setEncoding('utf8');
res.on('data', function (data) {
data = JSON.parse(data);
liveapicreator.apiKey = data.apikey;
liveapicreator.params.headers.Authorization = 'CALiveAPICreator ' + data.apikey + ':1';
deferred.resolve();
});
});
req.end(JSON.stringify({username: key, password: password}));
req.on('error', function(e) {
deferred.reject('Authentication failed, please confirm the username and/or password');
});
} else {
//liveapicreatorsdk.connect() was directly passed an API key
liveapicreator.apiKey = key;
liveapicreator.params.headers.Authorization = 'CALiveAPICreator ' + key + ':1';
deferred.resolve();
}
return liveapicreator;
} | javascript | function (url, key, password) {
var deferred, options, headers, liveapicreator;
liveapicreator = _.extend({}, SDK);
liveapicreator.url = this.stripWrappingSlashes(url);
liveapicreator.params = _.pick(URL.parse(url), 'host', 'path', 'port');
liveapicreator.params.headers = {};
if (url.match('https')) {
liveapicreator.req = https;
}
//passed a url with a defined port
if (liveapicreator.isUrlWithPort(liveapicreator.params.host)) {
liveapicreator.params.host = liveapicreator.stripUrlPort(liveapicreator.params.host);
}
deferred = Q.defer();
liveapicreator.connection = deferred.promise;
//Is this a username/password combo
if (password) {
options = liveapicreator.setOptions({method: 'POST'});
options.headers['Content-Type'] ='application/json';
options.path += liveapicreator.authEndpoint;
var req = liveapicreator.req.request(options, function (res) {
if (res.statusCode == 503) {
deferred.reject(res.statusCode);
}
res.setEncoding('utf8');
res.on('data', function (data) {
data = JSON.parse(data);
liveapicreator.apiKey = data.apikey;
liveapicreator.params.headers.Authorization = 'CALiveAPICreator ' + data.apikey + ':1';
deferred.resolve();
});
});
req.end(JSON.stringify({username: key, password: password}));
req.on('error', function(e) {
deferred.reject('Authentication failed, please confirm the username and/or password');
});
} else {
//liveapicreatorsdk.connect() was directly passed an API key
liveapicreator.apiKey = key;
liveapicreator.params.headers.Authorization = 'CALiveAPICreator ' + key + ':1';
deferred.resolve();
}
return liveapicreator;
} | [
"function",
"(",
"url",
",",
"key",
",",
"password",
")",
"{",
"var",
"deferred",
",",
"options",
",",
"headers",
",",
"liveapicreator",
";",
"liveapicreator",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"SDK",
")",
";",
"liveapicreator",
".",
"url",
"=",
"this",
".",
"stripWrappingSlashes",
"(",
"url",
")",
";",
"liveapicreator",
".",
"params",
"=",
"_",
".",
"pick",
"(",
"URL",
".",
"parse",
"(",
"url",
")",
",",
"'host'",
",",
"'path'",
",",
"'port'",
")",
";",
"liveapicreator",
".",
"params",
".",
"headers",
"=",
"{",
"}",
";",
"if",
"(",
"url",
".",
"match",
"(",
"'https'",
")",
")",
"{",
"liveapicreator",
".",
"req",
"=",
"https",
";",
"}",
"//passed a url with a defined port",
"if",
"(",
"liveapicreator",
".",
"isUrlWithPort",
"(",
"liveapicreator",
".",
"params",
".",
"host",
")",
")",
"{",
"liveapicreator",
".",
"params",
".",
"host",
"=",
"liveapicreator",
".",
"stripUrlPort",
"(",
"liveapicreator",
".",
"params",
".",
"host",
")",
";",
"}",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"liveapicreator",
".",
"connection",
"=",
"deferred",
".",
"promise",
";",
"//Is this a username/password combo",
"if",
"(",
"password",
")",
"{",
"options",
"=",
"liveapicreator",
".",
"setOptions",
"(",
"{",
"method",
":",
"'POST'",
"}",
")",
";",
"options",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
";",
"options",
".",
"path",
"+=",
"liveapicreator",
".",
"authEndpoint",
";",
"var",
"req",
"=",
"liveapicreator",
".",
"req",
".",
"request",
"(",
"options",
",",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"statusCode",
"==",
"503",
")",
"{",
"deferred",
".",
"reject",
"(",
"res",
".",
"statusCode",
")",
";",
"}",
"res",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"data",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"liveapicreator",
".",
"apiKey",
"=",
"data",
".",
"apikey",
";",
"liveapicreator",
".",
"params",
".",
"headers",
".",
"Authorization",
"=",
"'CALiveAPICreator '",
"+",
"data",
".",
"apikey",
"+",
"':1'",
";",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"end",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"username",
":",
"key",
",",
"password",
":",
"password",
"}",
")",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"deferred",
".",
"reject",
"(",
"'Authentication failed, please confirm the username and/or password'",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"//liveapicreatorsdk.connect() was directly passed an API key",
"liveapicreator",
".",
"apiKey",
"=",
"key",
";",
"liveapicreator",
".",
"params",
".",
"headers",
".",
"Authorization",
"=",
"'CALiveAPICreator '",
"+",
"key",
"+",
"':1'",
";",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
"return",
"liveapicreator",
";",
"}"
]
| The default method of connecting to an API. Returns an instance of this library
and initializes a promise used to make requests on API endpoints.
@param string url the API url base e.g. http://localhost:8080/rest/default/demo/v1
@param string key an API key, typically found in Logic Designer's Security section.
When connecting with a username/password, this second argument (key) is a username
When connecting with an APIKey - set the password to null or omit.
@param string password an optional argument when using liveapicreatorsdk.connect() with a user/password combination | [
"The",
"default",
"method",
"of",
"connecting",
"to",
"an",
"API",
".",
"Returns",
"an",
"instance",
"of",
"this",
"library",
"and",
"initializes",
"a",
"promise",
"used",
"to",
"make",
"requests",
"on",
"API",
"endpoints",
"."
]
| ada0acf7c9e91807bcb781ba233282915ed13770 | https://github.com/EspressoLogicCafe/APICreatorSDK/blob/ada0acf7c9e91807bcb781ba233282915ed13770/APICreatorSDK.js#L102-L149 |
|
45,843 | EspressoLogicCafe/APICreatorSDK | APICreatorSDK.js | function (options, headers) {
if (!headers) { headers = {}; }
if (options.headers) {
var headers = options.headers;
headers = _.extend(headers, this.headers, headers);
}
return options;
} | javascript | function (options, headers) {
if (!headers) { headers = {}; }
if (options.headers) {
var headers = options.headers;
headers = _.extend(headers, this.headers, headers);
}
return options;
} | [
"function",
"(",
"options",
",",
"headers",
")",
"{",
"if",
"(",
"!",
"headers",
")",
"{",
"headers",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"options",
".",
"headers",
")",
"{",
"var",
"headers",
"=",
"options",
".",
"headers",
";",
"headers",
"=",
"_",
".",
"extend",
"(",
"headers",
",",
"this",
".",
"headers",
",",
"headers",
")",
";",
"}",
"return",
"options",
";",
"}"
]
| Internal method for merging liveapicreatorsdk.headers attributes with those passed in via headers.
@param object options a collection of URL.parse(url) attributes, which may or may not contain options.headers
@param object headers a collection of header attributes to be appended to the request | [
"Internal",
"method",
"for",
"merging",
"liveapicreatorsdk",
".",
"headers",
"attributes",
"with",
"those",
"passed",
"in",
"via",
"headers",
"."
]
| ada0acf7c9e91807bcb781ba233282915ed13770 | https://github.com/EspressoLogicCafe/APICreatorSDK/blob/ada0acf7c9e91807bcb781ba233282915ed13770/APICreatorSDK.js#L173-L180 |
|
45,844 | stehefan/postcss-env-replace | index.js | verifyParameters | function verifyParameters(replacements, value, decl, environment) {
if (undefined === replacements[value]) {
throw decl.error(
'Unknown variable ' + value,
{ plugin: plugin.name }
);
}
if (undefined === replacements[value][environment]) {
throw decl.error(
'No suitable replacement for "' + value +
'" in environment "' + environment + '"',
{ plugin: plugin.name }
);
}
} | javascript | function verifyParameters(replacements, value, decl, environment) {
if (undefined === replacements[value]) {
throw decl.error(
'Unknown variable ' + value,
{ plugin: plugin.name }
);
}
if (undefined === replacements[value][environment]) {
throw decl.error(
'No suitable replacement for "' + value +
'" in environment "' + environment + '"',
{ plugin: plugin.name }
);
}
} | [
"function",
"verifyParameters",
"(",
"replacements",
",",
"value",
",",
"decl",
",",
"environment",
")",
"{",
"if",
"(",
"undefined",
"===",
"replacements",
"[",
"value",
"]",
")",
"{",
"throw",
"decl",
".",
"error",
"(",
"'Unknown variable '",
"+",
"value",
",",
"{",
"plugin",
":",
"plugin",
".",
"name",
"}",
")",
";",
"}",
"if",
"(",
"undefined",
"===",
"replacements",
"[",
"value",
"]",
"[",
"environment",
"]",
")",
"{",
"throw",
"decl",
".",
"error",
"(",
"'No suitable replacement for \"'",
"+",
"value",
"+",
"'\" in environment \"'",
"+",
"environment",
"+",
"'\"'",
",",
"{",
"plugin",
":",
"plugin",
".",
"name",
"}",
")",
";",
"}",
"}"
]
| Verifies the found options and checks whether they are configured or not
@param {Object} replacements - Object containing replacement information
per environment
@param {String} value - String found inside the declaration that should
be replaced
@param {Declaration} decl - Declaration currently examined
@param {String} environment - Name of the current environment | [
"Verifies",
"the",
"found",
"options",
"and",
"checks",
"whether",
"they",
"are",
"configured",
"or",
"not"
]
| f6f879dbcc2cb7268f16d9e2bc6a931f609ead13 | https://github.com/stehefan/postcss-env-replace/blob/f6f879dbcc2cb7268f16d9e2bc6a931f609ead13/index.js#L19-L34 |
45,845 | stehefan/postcss-env-replace | index.js | walkDeclaration | function walkDeclaration(decl, environment, replacements) {
decl.value = decl.value.replace(functionRegex, function (match, value) {
verifyParameters(replacements, value, decl, environment);
return replacements[value][environment];
});
} | javascript | function walkDeclaration(decl, environment, replacements) {
decl.value = decl.value.replace(functionRegex, function (match, value) {
verifyParameters(replacements, value, decl, environment);
return replacements[value][environment];
});
} | [
"function",
"walkDeclaration",
"(",
"decl",
",",
"environment",
",",
"replacements",
")",
"{",
"decl",
".",
"value",
"=",
"decl",
".",
"value",
".",
"replace",
"(",
"functionRegex",
",",
"function",
"(",
"match",
",",
"value",
")",
"{",
"verifyParameters",
"(",
"replacements",
",",
"value",
",",
"decl",
",",
"environment",
")",
";",
"return",
"replacements",
"[",
"value",
"]",
"[",
"environment",
"]",
";",
"}",
")",
";",
"}"
]
| Parses one CSS-declaration from the given AST and checks for
possible replacements
@param {Declaration} decl - one CSS-Declaration from the AST
@param {String} environment - current environment
@param {String} replacements - Object containing all replacements that we
have inside the options | [
"Parses",
"one",
"CSS",
"-",
"declaration",
"from",
"the",
"given",
"AST",
"and",
"checks",
"for",
"possible",
"replacements"
]
| f6f879dbcc2cb7268f16d9e2bc6a931f609ead13 | https://github.com/stehefan/postcss-env-replace/blob/f6f879dbcc2cb7268f16d9e2bc6a931f609ead13/index.js#L45-L51 |
45,846 | silas/node-mesos | lib/chronos.js | Chronos | function Chronos(opts) {
if (!(this instanceof Chronos)) {
return new Chronos(opts);
}
opts = opts || {};
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || '4400') + '/scheduler';
}
opts.name = 'chronos';
opts.type = 'json';
papi.Client.call(this, opts);
this.job = new Job(this);
this.task = new Task(this);
} | javascript | function Chronos(opts) {
if (!(this instanceof Chronos)) {
return new Chronos(opts);
}
opts = opts || {};
if (!opts.baseUrl) {
opts.baseUrl = (opts.secure ? 'https:' : 'http:') + '//' +
(opts.host || '127.0.0.1') + ':' +
(opts.port || '4400') + '/scheduler';
}
opts.name = 'chronos';
opts.type = 'json';
papi.Client.call(this, opts);
this.job = new Job(this);
this.task = new Task(this);
} | [
"function",
"Chronos",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Chronos",
")",
")",
"{",
"return",
"new",
"Chronos",
"(",
"opts",
")",
";",
"}",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"opts",
".",
"baseUrl",
")",
"{",
"opts",
".",
"baseUrl",
"=",
"(",
"opts",
".",
"secure",
"?",
"'https:'",
":",
"'http:'",
")",
"+",
"'//'",
"+",
"(",
"opts",
".",
"host",
"||",
"'127.0.0.1'",
")",
"+",
"':'",
"+",
"(",
"opts",
".",
"port",
"||",
"'4400'",
")",
"+",
"'/scheduler'",
";",
"}",
"opts",
".",
"name",
"=",
"'chronos'",
";",
"opts",
".",
"type",
"=",
"'json'",
";",
"papi",
".",
"Client",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"this",
".",
"job",
"=",
"new",
"Job",
"(",
"this",
")",
";",
"this",
".",
"task",
"=",
"new",
"Task",
"(",
"this",
")",
";",
"}"
]
| Initialize a new `Chronos` client.
@param {Object} opts | [
"Initialize",
"a",
"new",
"Chronos",
"client",
"."
]
| 157ca9fa9cfeb13def49cf8f6ef53ff7e708da95 | https://github.com/silas/node-mesos/blob/157ca9fa9cfeb13def49cf8f6ef53ff7e708da95/lib/chronos.js#L23-L42 |
45,847 | Kong/galileo-agent-node | lib/helpers.js | function (testOverride) {
var ret = '127.0.0.1'
os = testOverride || os
var interfaces = os.networkInterfaces()
Object.keys(interfaces).forEach(function (el) {
interfaces[el].forEach(function (el2) {
if (!el2.internal && el2.family === 'IPv4') {
ret = el2.address
}
})
})
return ret
} | javascript | function (testOverride) {
var ret = '127.0.0.1'
os = testOverride || os
var interfaces = os.networkInterfaces()
Object.keys(interfaces).forEach(function (el) {
interfaces[el].forEach(function (el2) {
if (!el2.internal && el2.family === 'IPv4') {
ret = el2.address
}
})
})
return ret
} | [
"function",
"(",
"testOverride",
")",
"{",
"var",
"ret",
"=",
"'127.0.0.1'",
"os",
"=",
"testOverride",
"||",
"os",
"var",
"interfaces",
"=",
"os",
".",
"networkInterfaces",
"(",
")",
"Object",
".",
"keys",
"(",
"interfaces",
")",
".",
"forEach",
"(",
"function",
"(",
"el",
")",
"{",
"interfaces",
"[",
"el",
"]",
".",
"forEach",
"(",
"function",
"(",
"el2",
")",
"{",
"if",
"(",
"!",
"el2",
".",
"internal",
"&&",
"el2",
".",
"family",
"===",
"'IPv4'",
")",
"{",
"ret",
"=",
"el2",
".",
"address",
"}",
"}",
")",
"}",
")",
"return",
"ret",
"}"
]
| get server address from network interface | [
"get",
"server",
"address",
"from",
"network",
"interface"
]
| 651626bbf82c66e0b1786992a7fd7e18845f076b | https://github.com/Kong/galileo-agent-node/blob/651626bbf82c66e0b1786992a7fd7e18845f076b/lib/helpers.js#L20-L34 |
|
45,848 | Kong/galileo-agent-node | lib/helpers.js | function (string) {
if (!string || string === '' || string.indexOf('\r\n') === -1) {
return {
version: 'HTTP/1.1',
statusText: ''
}
}
var lines = string.split('\r\n')
var status = lines.shift()
// Remove empty strings
lines = lines.filter(Boolean)
// Parse status line
var output = this.parseStartLine(status)
// init headers object & array
output.headersObj = {}
output.headersArr = []
// Parse headers
var header
for (var i = lines.length; i--;) {
header = this.parseHeaderLine(lines[i])
output.headersArr.push(header)
output.headersObj[header.name] = header.value
}
return output
} | javascript | function (string) {
if (!string || string === '' || string.indexOf('\r\n') === -1) {
return {
version: 'HTTP/1.1',
statusText: ''
}
}
var lines = string.split('\r\n')
var status = lines.shift()
// Remove empty strings
lines = lines.filter(Boolean)
// Parse status line
var output = this.parseStartLine(status)
// init headers object & array
output.headersObj = {}
output.headersArr = []
// Parse headers
var header
for (var i = lines.length; i--;) {
header = this.parseHeaderLine(lines[i])
output.headersArr.push(header)
output.headersObj[header.name] = header.value
}
return output
} | [
"function",
"(",
"string",
")",
"{",
"if",
"(",
"!",
"string",
"||",
"string",
"===",
"''",
"||",
"string",
".",
"indexOf",
"(",
"'\\r\\n'",
")",
"===",
"-",
"1",
")",
"{",
"return",
"{",
"version",
":",
"'HTTP/1.1'",
",",
"statusText",
":",
"''",
"}",
"}",
"var",
"lines",
"=",
"string",
".",
"split",
"(",
"'\\r\\n'",
")",
"var",
"status",
"=",
"lines",
".",
"shift",
"(",
")",
"// Remove empty strings",
"lines",
"=",
"lines",
".",
"filter",
"(",
"Boolean",
")",
"// Parse status line",
"var",
"output",
"=",
"this",
".",
"parseStartLine",
"(",
"status",
")",
"// init headers object & array",
"output",
".",
"headersObj",
"=",
"{",
"}",
"output",
".",
"headersArr",
"=",
"[",
"]",
"// Parse headers",
"var",
"header",
"for",
"(",
"var",
"i",
"=",
"lines",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"header",
"=",
"this",
".",
"parseHeaderLine",
"(",
"lines",
"[",
"i",
"]",
")",
"output",
".",
"headersArr",
".",
"push",
"(",
"header",
")",
"output",
".",
"headersObj",
"[",
"header",
".",
"name",
"]",
"=",
"header",
".",
"value",
"}",
"return",
"output",
"}"
]
| convert header string to assoc array | [
"convert",
"header",
"string",
"to",
"assoc",
"array"
]
| 651626bbf82c66e0b1786992a7fd7e18845f076b | https://github.com/Kong/galileo-agent-node/blob/651626bbf82c66e0b1786992a7fd7e18845f076b/lib/helpers.js#L61-L92 |
|
45,849 | Kong/galileo-agent-node | lib/helpers.js | function (line) {
var pieces = line.split(' ')
// Header string pieces
var output = {
version: pieces.shift(),
status: parseFloat(pieces.shift()),
statusText: pieces.join(' ')
}
return output
} | javascript | function (line) {
var pieces = line.split(' ')
// Header string pieces
var output = {
version: pieces.shift(),
status: parseFloat(pieces.shift()),
statusText: pieces.join(' ')
}
return output
} | [
"function",
"(",
"line",
")",
"{",
"var",
"pieces",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"// Header string pieces",
"var",
"output",
"=",
"{",
"version",
":",
"pieces",
".",
"shift",
"(",
")",
",",
"status",
":",
"parseFloat",
"(",
"pieces",
".",
"shift",
"(",
")",
")",
",",
"statusText",
":",
"pieces",
".",
"join",
"(",
"' '",
")",
"}",
"return",
"output",
"}"
]
| parse status line into an object | [
"parse",
"status",
"line",
"into",
"an",
"object"
]
| 651626bbf82c66e0b1786992a7fd7e18845f076b | https://github.com/Kong/galileo-agent-node/blob/651626bbf82c66e0b1786992a7fd7e18845f076b/lib/helpers.js#L97-L108 |
|
45,850 | Kong/galileo-agent-node | lib/helpers.js | function (obj) {
// sanity check
if (!obj || typeof obj !== 'object') {
return []
}
var results = []
Object.keys(obj).forEach(function (name) {
// nested values in query string
if (typeof obj[name] === 'object') {
obj[name].forEach(function (value) {
results.push({
name: name,
value: value
})
})
return
}
results.push({
name: name,
value: obj[name]
})
})
return results
} | javascript | function (obj) {
// sanity check
if (!obj || typeof obj !== 'object') {
return []
}
var results = []
Object.keys(obj).forEach(function (name) {
// nested values in query string
if (typeof obj[name] === 'object') {
obj[name].forEach(function (value) {
results.push({
name: name,
value: value
})
})
return
}
results.push({
name: name,
value: obj[name]
})
})
return results
} | [
"function",
"(",
"obj",
")",
"{",
"// sanity check",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
")",
"{",
"return",
"[",
"]",
"}",
"var",
"results",
"=",
"[",
"]",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"// nested values in query string",
"if",
"(",
"typeof",
"obj",
"[",
"name",
"]",
"===",
"'object'",
")",
"{",
"obj",
"[",
"name",
"]",
".",
"forEach",
"(",
"function",
"(",
"value",
")",
"{",
"results",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"value",
":",
"value",
"}",
")",
"}",
")",
"return",
"}",
"results",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"value",
":",
"obj",
"[",
"name",
"]",
"}",
")",
"}",
")",
"return",
"results",
"}"
]
| Transform objects into an array of key value pairs. | [
"Transform",
"objects",
"into",
"an",
"array",
"of",
"key",
"value",
"pairs",
"."
]
| 651626bbf82c66e0b1786992a7fd7e18845f076b | https://github.com/Kong/galileo-agent-node/blob/651626bbf82c66e0b1786992a7fd7e18845f076b/lib/helpers.js#L127-L154 |
|
45,851 | Kong/galileo-agent-node | lib/helpers.js | function (headers, key, def) {
if (headers instanceof Array) {
var regex = new RegExp(key, 'i')
for (var i = 0; i < headers.length; i++) {
if (regex.test(headers[i].name)) {
return headers[i].value
}
}
}
return def !== undefined ? def : false
} | javascript | function (headers, key, def) {
if (headers instanceof Array) {
var regex = new RegExp(key, 'i')
for (var i = 0; i < headers.length; i++) {
if (regex.test(headers[i].name)) {
return headers[i].value
}
}
}
return def !== undefined ? def : false
} | [
"function",
"(",
"headers",
",",
"key",
",",
"def",
")",
"{",
"if",
"(",
"headers",
"instanceof",
"Array",
")",
"{",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"key",
",",
"'i'",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"headers",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"regex",
".",
"test",
"(",
"headers",
"[",
"i",
"]",
".",
"name",
")",
")",
"{",
"return",
"headers",
"[",
"i",
"]",
".",
"value",
"}",
"}",
"}",
"return",
"def",
"!==",
"undefined",
"?",
"def",
":",
"false",
"}"
]
| uses regex to match a header value | [
"uses",
"regex",
"to",
"match",
"a",
"header",
"value"
]
| 651626bbf82c66e0b1786992a7fd7e18845f076b | https://github.com/Kong/galileo-agent-node/blob/651626bbf82c66e0b1786992a7fd7e18845f076b/lib/helpers.js#L159-L170 |
|
45,852 | Kong/galileo-agent-node | lib/helpers.js | function (req) {
var keys = Object.keys(req.headers)
var values = keys.map(function (key) {
return req.headers[key]
})
var headers = req.method + req.url + keys.join() + values.join()
// startline: [method] [url] HTTP/1.1\r\n = 12
// endline: \r\n = 2
// every header + \r\n = * 2
// add 2 for each combined header
return new Buffer(headers).length + (keys.length * 2) + 2 + 12 + 2
} | javascript | function (req) {
var keys = Object.keys(req.headers)
var values = keys.map(function (key) {
return req.headers[key]
})
var headers = req.method + req.url + keys.join() + values.join()
// startline: [method] [url] HTTP/1.1\r\n = 12
// endline: \r\n = 2
// every header + \r\n = * 2
// add 2 for each combined header
return new Buffer(headers).length + (keys.length * 2) + 2 + 12 + 2
} | [
"function",
"(",
"req",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"req",
".",
"headers",
")",
"var",
"values",
"=",
"keys",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"req",
".",
"headers",
"[",
"key",
"]",
"}",
")",
"var",
"headers",
"=",
"req",
".",
"method",
"+",
"req",
".",
"url",
"+",
"keys",
".",
"join",
"(",
")",
"+",
"values",
".",
"join",
"(",
")",
"// startline: [method] [url] HTTP/1.1\\r\\n = 12",
"// endline: \\r\\n = 2",
"// every header + \\r\\n = * 2",
"// add 2 for each combined header",
"return",
"new",
"Buffer",
"(",
"headers",
")",
".",
"length",
"+",
"(",
"keys",
".",
"length",
"*",
"2",
")",
"+",
"2",
"+",
"12",
"+",
"2",
"}"
]
| quickly calculates the header size in bytes for a given array of headers | [
"quickly",
"calculates",
"the",
"header",
"size",
"in",
"bytes",
"for",
"a",
"given",
"array",
"of",
"headers"
]
| 651626bbf82c66e0b1786992a7fd7e18845f076b | https://github.com/Kong/galileo-agent-node/blob/651626bbf82c66e0b1786992a7fd7e18845f076b/lib/helpers.js#L175-L189 |
|
45,853 | rakuten-frontend/generator-rff | generators/app/index.js | function () {
var done = this.async();
var questions = [];
var choices = [
{
name: 'Standard Preset',
value: 'standard'
},
{
name: 'Minimum Preset',
value: 'minimum'
},
{
name: 'Custom Configuration (Advanced)',
value: 'custom'
}
];
var defaultType = 'standard';
if (!this.skipWelcomeMessage) {
this.log(yosay('Welcome to ' + this.pkg.name + ' v' + this.pkg.version));
}
if (!this.configType) {
if (this.config.existed) {
choices.splice(2, 0, {
name: 'User Preset',
value: 'user'
});
defaultType = 'user';
}
questions.push({
type: 'list',
name: 'configType',
message: 'Setup Type',
choices: choices,
default: defaultType
});
}
this.prompt(questions, function (answers) {
if (typeof answers.configType !== 'undefined') {
this.configType = answers.configType;
}
// Preset for skipping prompt
switch (this.configType) {
case 'standard':
this.preset = standardPreset;
break;
case 'minimum':
this.preset = minimumPreset;
break;
case 'user':
this.preset = this.config.getAll();
break;
case 'custom':
this.preset = {};
break;
}
// Initial settings
this.settings = _.assign({}, defaultConfig, this.config.getAll());
done();
}.bind(this));
} | javascript | function () {
var done = this.async();
var questions = [];
var choices = [
{
name: 'Standard Preset',
value: 'standard'
},
{
name: 'Minimum Preset',
value: 'minimum'
},
{
name: 'Custom Configuration (Advanced)',
value: 'custom'
}
];
var defaultType = 'standard';
if (!this.skipWelcomeMessage) {
this.log(yosay('Welcome to ' + this.pkg.name + ' v' + this.pkg.version));
}
if (!this.configType) {
if (this.config.existed) {
choices.splice(2, 0, {
name: 'User Preset',
value: 'user'
});
defaultType = 'user';
}
questions.push({
type: 'list',
name: 'configType',
message: 'Setup Type',
choices: choices,
default: defaultType
});
}
this.prompt(questions, function (answers) {
if (typeof answers.configType !== 'undefined') {
this.configType = answers.configType;
}
// Preset for skipping prompt
switch (this.configType) {
case 'standard':
this.preset = standardPreset;
break;
case 'minimum':
this.preset = minimumPreset;
break;
case 'user':
this.preset = this.config.getAll();
break;
case 'custom':
this.preset = {};
break;
}
// Initial settings
this.settings = _.assign({}, defaultConfig, this.config.getAll());
done();
}.bind(this));
} | [
"function",
"(",
")",
"{",
"var",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"var",
"questions",
"=",
"[",
"]",
";",
"var",
"choices",
"=",
"[",
"{",
"name",
":",
"'Standard Preset'",
",",
"value",
":",
"'standard'",
"}",
",",
"{",
"name",
":",
"'Minimum Preset'",
",",
"value",
":",
"'minimum'",
"}",
",",
"{",
"name",
":",
"'Custom Configuration (Advanced)'",
",",
"value",
":",
"'custom'",
"}",
"]",
";",
"var",
"defaultType",
"=",
"'standard'",
";",
"if",
"(",
"!",
"this",
".",
"skipWelcomeMessage",
")",
"{",
"this",
".",
"log",
"(",
"yosay",
"(",
"'Welcome to '",
"+",
"this",
".",
"pkg",
".",
"name",
"+",
"' v'",
"+",
"this",
".",
"pkg",
".",
"version",
")",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"configType",
")",
"{",
"if",
"(",
"this",
".",
"config",
".",
"existed",
")",
"{",
"choices",
".",
"splice",
"(",
"2",
",",
"0",
",",
"{",
"name",
":",
"'User Preset'",
",",
"value",
":",
"'user'",
"}",
")",
";",
"defaultType",
"=",
"'user'",
";",
"}",
"questions",
".",
"push",
"(",
"{",
"type",
":",
"'list'",
",",
"name",
":",
"'configType'",
",",
"message",
":",
"'Setup Type'",
",",
"choices",
":",
"choices",
",",
"default",
":",
"defaultType",
"}",
")",
";",
"}",
"this",
".",
"prompt",
"(",
"questions",
",",
"function",
"(",
"answers",
")",
"{",
"if",
"(",
"typeof",
"answers",
".",
"configType",
"!==",
"'undefined'",
")",
"{",
"this",
".",
"configType",
"=",
"answers",
".",
"configType",
";",
"}",
"// Preset for skipping prompt",
"switch",
"(",
"this",
".",
"configType",
")",
"{",
"case",
"'standard'",
":",
"this",
".",
"preset",
"=",
"standardPreset",
";",
"break",
";",
"case",
"'minimum'",
":",
"this",
".",
"preset",
"=",
"minimumPreset",
";",
"break",
";",
"case",
"'user'",
":",
"this",
".",
"preset",
"=",
"this",
".",
"config",
".",
"getAll",
"(",
")",
";",
"break",
";",
"case",
"'custom'",
":",
"this",
".",
"preset",
"=",
"{",
"}",
";",
"break",
";",
"}",
"// Initial settings",
"this",
".",
"settings",
"=",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"defaultConfig",
",",
"this",
".",
"config",
".",
"getAll",
"(",
")",
")",
";",
"done",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Setup prompting type | [
"Setup",
"prompting",
"type"
]
| f0621e5b2a042036599d2126701af6a2f59e563f | https://github.com/rakuten-frontend/generator-rff/blob/f0621e5b2a042036599d2126701af6a2f59e563f/generators/app/index.js#L43-L109 |
|
45,854 | rakuten-frontend/generator-rff | generators/app/index.js | function () {
this.cfg = {};
// Copy from prompt settings
Object.keys(this.settings).forEach(function (key) {
this.cfg[key] = this.settings[key];
}.bind(this));
// Boolean config
options.forEach(function (option) {
var name = option.name;
option.choices.forEach(function (choice) {
var value = choice.value;
switch (option.type) {
case 'list':
this.cfg[value] = value === this.cfg[name];
break;
case 'checkbox':
this.cfg[value] = _.includes(this.cfg[name], value);
break;
}
}.bind(this));
}.bind(this));
// Extra config
this.cfg.slugName = _s.slugify(this.cfg.name);
this.cfg.testing = this.cfg.mocha || this.cfg.jasmine;
this.cfg.cssSourceMap = (this.cfg.css && this.cfg.autoprefixer) ||
this.cfg.sass ||
(this.cfg.less && (this.cfg.autoprefixer || this.cfg.cssmin));
this.cfg.jsSourceMap = this.cfg.coffee;
} | javascript | function () {
this.cfg = {};
// Copy from prompt settings
Object.keys(this.settings).forEach(function (key) {
this.cfg[key] = this.settings[key];
}.bind(this));
// Boolean config
options.forEach(function (option) {
var name = option.name;
option.choices.forEach(function (choice) {
var value = choice.value;
switch (option.type) {
case 'list':
this.cfg[value] = value === this.cfg[name];
break;
case 'checkbox':
this.cfg[value] = _.includes(this.cfg[name], value);
break;
}
}.bind(this));
}.bind(this));
// Extra config
this.cfg.slugName = _s.slugify(this.cfg.name);
this.cfg.testing = this.cfg.mocha || this.cfg.jasmine;
this.cfg.cssSourceMap = (this.cfg.css && this.cfg.autoprefixer) ||
this.cfg.sass ||
(this.cfg.less && (this.cfg.autoprefixer || this.cfg.cssmin));
this.cfg.jsSourceMap = this.cfg.coffee;
} | [
"function",
"(",
")",
"{",
"this",
".",
"cfg",
"=",
"{",
"}",
";",
"// Copy from prompt settings",
"Object",
".",
"keys",
"(",
"this",
".",
"settings",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"this",
".",
"cfg",
"[",
"key",
"]",
"=",
"this",
".",
"settings",
"[",
"key",
"]",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// Boolean config",
"options",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"var",
"name",
"=",
"option",
".",
"name",
";",
"option",
".",
"choices",
".",
"forEach",
"(",
"function",
"(",
"choice",
")",
"{",
"var",
"value",
"=",
"choice",
".",
"value",
";",
"switch",
"(",
"option",
".",
"type",
")",
"{",
"case",
"'list'",
":",
"this",
".",
"cfg",
"[",
"value",
"]",
"=",
"value",
"===",
"this",
".",
"cfg",
"[",
"name",
"]",
";",
"break",
";",
"case",
"'checkbox'",
":",
"this",
".",
"cfg",
"[",
"value",
"]",
"=",
"_",
".",
"includes",
"(",
"this",
".",
"cfg",
"[",
"name",
"]",
",",
"value",
")",
";",
"break",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// Extra config",
"this",
".",
"cfg",
".",
"slugName",
"=",
"_s",
".",
"slugify",
"(",
"this",
".",
"cfg",
".",
"name",
")",
";",
"this",
".",
"cfg",
".",
"testing",
"=",
"this",
".",
"cfg",
".",
"mocha",
"||",
"this",
".",
"cfg",
".",
"jasmine",
";",
"this",
".",
"cfg",
".",
"cssSourceMap",
"=",
"(",
"this",
".",
"cfg",
".",
"css",
"&&",
"this",
".",
"cfg",
".",
"autoprefixer",
")",
"||",
"this",
".",
"cfg",
".",
"sass",
"||",
"(",
"this",
".",
"cfg",
".",
"less",
"&&",
"(",
"this",
".",
"cfg",
".",
"autoprefixer",
"||",
"this",
".",
"cfg",
".",
"cssmin",
")",
")",
";",
"this",
".",
"cfg",
".",
"jsSourceMap",
"=",
"this",
".",
"cfg",
".",
"coffee",
";",
"}"
]
| Config for template generator | [
"Config",
"for",
"template",
"generator"
]
| f0621e5b2a042036599d2126701af6a2f59e563f | https://github.com/rakuten-frontend/generator-rff/blob/f0621e5b2a042036599d2126701af6a2f59e563f/generators/app/index.js#L187-L218 |
|
45,855 | tradle/simple-wallet | index.js | Wallet | function Wallet (options) {
this.priv = typeof options.priv === 'string' ?
bitcoin.ECKey.fromWIF(options.priv) :
options.priv
typeforce(typeforce.Object, this.priv)
typeforce({
blockchain: typeforce.Object,
networkName: typeforce.String
}, options)
assert(options.networkName in bitcoin.networks, 'unknown network: ' + options.networkName)
this.txs = []
this.pub = this.priv.pub
this.networkName = options.networkName
this.address = this.pub.getAddress(bitcoin.networks[this.networkName])
this.addressString = this.address.toString()
this.blockchain = options.blockchain
} | javascript | function Wallet (options) {
this.priv = typeof options.priv === 'string' ?
bitcoin.ECKey.fromWIF(options.priv) :
options.priv
typeforce(typeforce.Object, this.priv)
typeforce({
blockchain: typeforce.Object,
networkName: typeforce.String
}, options)
assert(options.networkName in bitcoin.networks, 'unknown network: ' + options.networkName)
this.txs = []
this.pub = this.priv.pub
this.networkName = options.networkName
this.address = this.pub.getAddress(bitcoin.networks[this.networkName])
this.addressString = this.address.toString()
this.blockchain = options.blockchain
} | [
"function",
"Wallet",
"(",
"options",
")",
"{",
"this",
".",
"priv",
"=",
"typeof",
"options",
".",
"priv",
"===",
"'string'",
"?",
"bitcoin",
".",
"ECKey",
".",
"fromWIF",
"(",
"options",
".",
"priv",
")",
":",
"options",
".",
"priv",
"typeforce",
"(",
"typeforce",
".",
"Object",
",",
"this",
".",
"priv",
")",
"typeforce",
"(",
"{",
"blockchain",
":",
"typeforce",
".",
"Object",
",",
"networkName",
":",
"typeforce",
".",
"String",
"}",
",",
"options",
")",
"assert",
"(",
"options",
".",
"networkName",
"in",
"bitcoin",
".",
"networks",
",",
"'unknown network: '",
"+",
"options",
".",
"networkName",
")",
"this",
".",
"txs",
"=",
"[",
"]",
"this",
".",
"pub",
"=",
"this",
".",
"priv",
".",
"pub",
"this",
".",
"networkName",
"=",
"options",
".",
"networkName",
"this",
".",
"address",
"=",
"this",
".",
"pub",
".",
"getAddress",
"(",
"bitcoin",
".",
"networks",
"[",
"this",
".",
"networkName",
"]",
")",
"this",
".",
"addressString",
"=",
"this",
".",
"address",
".",
"toString",
"(",
")",
"this",
".",
"blockchain",
"=",
"options",
".",
"blockchain",
"}"
]
| primitive one key common blockchain wallet
@param {Object} options
@param {String|ECKey} options.priv
@param {CommonBlockchain impl} options.blockchain common-blockchain api | [
"primitive",
"one",
"key",
"common",
"blockchain",
"wallet"
]
| de0c8d5d932aab08c93688b6565a25c793ee9915 | https://github.com/tradle/simple-wallet/blob/de0c8d5d932aab08c93688b6565a25c793ee9915/index.js#L18-L37 |
45,856 | gcanti/flowcheck | visitors.js | visitTypedVariableDeclarator | function visitTypedVariableDeclarator(traverse, node, path, state) {
var ctx = new Context(state);
if (node.init) {
utils.catchup(node.init.range[0], state);
utils.append(ctx.getProperty('check') + '(', state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
utils.append(', ' + ctx.getType(node.id.typeAnnotation.typeAnnotation) + ')', state);
}
utils.catchup(node.range[1], state);
return false;
} | javascript | function visitTypedVariableDeclarator(traverse, node, path, state) {
var ctx = new Context(state);
if (node.init) {
utils.catchup(node.init.range[0], state);
utils.append(ctx.getProperty('check') + '(', state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
utils.append(', ' + ctx.getType(node.id.typeAnnotation.typeAnnotation) + ')', state);
}
utils.catchup(node.range[1], state);
return false;
} | [
"function",
"visitTypedVariableDeclarator",
"(",
"traverse",
",",
"node",
",",
"path",
",",
"state",
")",
"{",
"var",
"ctx",
"=",
"new",
"Context",
"(",
"state",
")",
";",
"if",
"(",
"node",
".",
"init",
")",
"{",
"utils",
".",
"catchup",
"(",
"node",
".",
"init",
".",
"range",
"[",
"0",
"]",
",",
"state",
")",
";",
"utils",
".",
"append",
"(",
"ctx",
".",
"getProperty",
"(",
"'check'",
")",
"+",
"'('",
",",
"state",
")",
";",
"traverse",
"(",
"node",
".",
"init",
",",
"path",
",",
"state",
")",
";",
"utils",
".",
"catchup",
"(",
"node",
".",
"init",
".",
"range",
"[",
"1",
"]",
",",
"state",
")",
";",
"utils",
".",
"append",
"(",
"', '",
"+",
"ctx",
".",
"getType",
"(",
"node",
".",
"id",
".",
"typeAnnotation",
".",
"typeAnnotation",
")",
"+",
"')'",
",",
"state",
")",
";",
"}",
"utils",
".",
"catchup",
"(",
"node",
".",
"range",
"[",
"1",
"]",
",",
"state",
")",
";",
"return",
"false",
";",
"}"
]
| handle variable declarations | [
"handle",
"variable",
"declarations"
]
| 7c29f7ebdd962b4cc3b26771a1b3c1319b5137c5 | https://github.com/gcanti/flowcheck/blob/7c29f7ebdd962b4cc3b26771a1b3c1319b5137c5/visitors.js#L171-L182 |
45,857 | gcanti/flowcheck | visitors.js | visitTypedFunction | function visitTypedFunction(traverse, node, path, state) {
var klass = getParentClassDeclaration(path);
var generics = klass && klass.typeParameters ? toLookup(klass.typeParameters.params.map(getName)) : {};
if (node.typeParameters) {
generics = mixin(generics, toLookup(node.typeParameters.params.map(getName)));
}
var ctx = new Context(state, generics);
var rest = node.rest ? ', ' + ctx.getType(node.rest.typeAnnotation.typeAnnotation) : '';
var types = [];
var params = [];
node.params.forEach(function (param) {
var type = ctx.getType(param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null);
types.push(param.optional ? ctx.getProperty('optional') + '(' + type + ')' : type);
params.push(param.name);
});
utils.catchup(node.body.range[0] + 1, state);
if (params.length || rest) {
utils.append(ctx.getProperty('check') + '(arguments, ' + ctx.getProperty('arguments') + '([' + types.join(', ') + ']' + rest + '));', state);
}
if (node.returnType) {
var returnType = ctx.getType(node.returnType.typeAnnotation);
utils.append(' var ret = (function (' + params.join(', ') + ') {', state);
traverse(node.body, path, state);
utils.catchup(node.body.range[1] - 1, state);
utils.append('}).apply(this, arguments); return ' + ctx.getProperty('check') + '(ret, ' + returnType + ');', state);
} else {
traverse(node.body, path, state);
}
return false;
} | javascript | function visitTypedFunction(traverse, node, path, state) {
var klass = getParentClassDeclaration(path);
var generics = klass && klass.typeParameters ? toLookup(klass.typeParameters.params.map(getName)) : {};
if (node.typeParameters) {
generics = mixin(generics, toLookup(node.typeParameters.params.map(getName)));
}
var ctx = new Context(state, generics);
var rest = node.rest ? ', ' + ctx.getType(node.rest.typeAnnotation.typeAnnotation) : '';
var types = [];
var params = [];
node.params.forEach(function (param) {
var type = ctx.getType(param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null);
types.push(param.optional ? ctx.getProperty('optional') + '(' + type + ')' : type);
params.push(param.name);
});
utils.catchup(node.body.range[0] + 1, state);
if (params.length || rest) {
utils.append(ctx.getProperty('check') + '(arguments, ' + ctx.getProperty('arguments') + '([' + types.join(', ') + ']' + rest + '));', state);
}
if (node.returnType) {
var returnType = ctx.getType(node.returnType.typeAnnotation);
utils.append(' var ret = (function (' + params.join(', ') + ') {', state);
traverse(node.body, path, state);
utils.catchup(node.body.range[1] - 1, state);
utils.append('}).apply(this, arguments); return ' + ctx.getProperty('check') + '(ret, ' + returnType + ');', state);
} else {
traverse(node.body, path, state);
}
return false;
} | [
"function",
"visitTypedFunction",
"(",
"traverse",
",",
"node",
",",
"path",
",",
"state",
")",
"{",
"var",
"klass",
"=",
"getParentClassDeclaration",
"(",
"path",
")",
";",
"var",
"generics",
"=",
"klass",
"&&",
"klass",
".",
"typeParameters",
"?",
"toLookup",
"(",
"klass",
".",
"typeParameters",
".",
"params",
".",
"map",
"(",
"getName",
")",
")",
":",
"{",
"}",
";",
"if",
"(",
"node",
".",
"typeParameters",
")",
"{",
"generics",
"=",
"mixin",
"(",
"generics",
",",
"toLookup",
"(",
"node",
".",
"typeParameters",
".",
"params",
".",
"map",
"(",
"getName",
")",
")",
")",
";",
"}",
"var",
"ctx",
"=",
"new",
"Context",
"(",
"state",
",",
"generics",
")",
";",
"var",
"rest",
"=",
"node",
".",
"rest",
"?",
"', '",
"+",
"ctx",
".",
"getType",
"(",
"node",
".",
"rest",
".",
"typeAnnotation",
".",
"typeAnnotation",
")",
":",
"''",
";",
"var",
"types",
"=",
"[",
"]",
";",
"var",
"params",
"=",
"[",
"]",
";",
"node",
".",
"params",
".",
"forEach",
"(",
"function",
"(",
"param",
")",
"{",
"var",
"type",
"=",
"ctx",
".",
"getType",
"(",
"param",
".",
"typeAnnotation",
"?",
"param",
".",
"typeAnnotation",
".",
"typeAnnotation",
":",
"null",
")",
";",
"types",
".",
"push",
"(",
"param",
".",
"optional",
"?",
"ctx",
".",
"getProperty",
"(",
"'optional'",
")",
"+",
"'('",
"+",
"type",
"+",
"')'",
":",
"type",
")",
";",
"params",
".",
"push",
"(",
"param",
".",
"name",
")",
";",
"}",
")",
";",
"utils",
".",
"catchup",
"(",
"node",
".",
"body",
".",
"range",
"[",
"0",
"]",
"+",
"1",
",",
"state",
")",
";",
"if",
"(",
"params",
".",
"length",
"||",
"rest",
")",
"{",
"utils",
".",
"append",
"(",
"ctx",
".",
"getProperty",
"(",
"'check'",
")",
"+",
"'(arguments, '",
"+",
"ctx",
".",
"getProperty",
"(",
"'arguments'",
")",
"+",
"'(['",
"+",
"types",
".",
"join",
"(",
"', '",
")",
"+",
"']'",
"+",
"rest",
"+",
"'));'",
",",
"state",
")",
";",
"}",
"if",
"(",
"node",
".",
"returnType",
")",
"{",
"var",
"returnType",
"=",
"ctx",
".",
"getType",
"(",
"node",
".",
"returnType",
".",
"typeAnnotation",
")",
";",
"utils",
".",
"append",
"(",
"' var ret = (function ('",
"+",
"params",
".",
"join",
"(",
"', '",
")",
"+",
"') {'",
",",
"state",
")",
";",
"traverse",
"(",
"node",
".",
"body",
",",
"path",
",",
"state",
")",
";",
"utils",
".",
"catchup",
"(",
"node",
".",
"body",
".",
"range",
"[",
"1",
"]",
"-",
"1",
",",
"state",
")",
";",
"utils",
".",
"append",
"(",
"'}).apply(this, arguments); return '",
"+",
"ctx",
".",
"getProperty",
"(",
"'check'",
")",
"+",
"'(ret, '",
"+",
"returnType",
"+",
"');'",
",",
"state",
")",
";",
"}",
"else",
"{",
"traverse",
"(",
"node",
".",
"body",
",",
"path",
",",
"state",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| handle typed functions a typed function is a function such that at least one param or the return value is typed | [
"handle",
"typed",
"functions",
"a",
"typed",
"function",
"is",
"a",
"function",
"such",
"that",
"at",
"least",
"one",
"param",
"or",
"the",
"return",
"value",
"is",
"typed"
]
| 7c29f7ebdd962b4cc3b26771a1b3c1319b5137c5 | https://github.com/gcanti/flowcheck/blob/7c29f7ebdd962b4cc3b26771a1b3c1319b5137c5/visitors.js#L193-L226 |
45,858 | gcanti/flowcheck | visitors.js | visitTypeAlias | function visitTypeAlias(traverse, node, path, state) {
var ctx = new Context(state);
utils.catchup(node.range[1], state);
utils.append('var ' + node.id.name + ' = ' + ctx.getType(node.right) + ';', state);
return false;
} | javascript | function visitTypeAlias(traverse, node, path, state) {
var ctx = new Context(state);
utils.catchup(node.range[1], state);
utils.append('var ' + node.id.name + ' = ' + ctx.getType(node.right) + ';', state);
return false;
} | [
"function",
"visitTypeAlias",
"(",
"traverse",
",",
"node",
",",
"path",
",",
"state",
")",
"{",
"var",
"ctx",
"=",
"new",
"Context",
"(",
"state",
")",
";",
"utils",
".",
"catchup",
"(",
"node",
".",
"range",
"[",
"1",
"]",
",",
"state",
")",
";",
"utils",
".",
"append",
"(",
"'var '",
"+",
"node",
".",
"id",
".",
"name",
"+",
"' = '",
"+",
"ctx",
".",
"getType",
"(",
"node",
".",
"right",
")",
"+",
"';'",
",",
"state",
")",
";",
"return",
"false",
";",
"}"
]
| handle type aliases | [
"handle",
"type",
"aliases"
]
| 7c29f7ebdd962b4cc3b26771a1b3c1319b5137c5 | https://github.com/gcanti/flowcheck/blob/7c29f7ebdd962b4cc3b26771a1b3c1319b5137c5/visitors.js#L240-L245 |
45,859 | tomaszczechowski/jsbeautify-loader | index.js | function (type) {
var handlers = { 'html': beautify.html, 'css': beautify.css, 'js': beautify.js };
if (type === undefined) {
return beautify;
}
if (type in handlers) {
return handlers[type];
}
throw new Error('Unrecognized beautifier type:', type);
} | javascript | function (type) {
var handlers = { 'html': beautify.html, 'css': beautify.css, 'js': beautify.js };
if (type === undefined) {
return beautify;
}
if (type in handlers) {
return handlers[type];
}
throw new Error('Unrecognized beautifier type:', type);
} | [
"function",
"(",
"type",
")",
"{",
"var",
"handlers",
"=",
"{",
"'html'",
":",
"beautify",
".",
"html",
",",
"'css'",
":",
"beautify",
".",
"css",
",",
"'js'",
":",
"beautify",
".",
"js",
"}",
";",
"if",
"(",
"type",
"===",
"undefined",
")",
"{",
"return",
"beautify",
";",
"}",
"if",
"(",
"type",
"in",
"handlers",
")",
"{",
"return",
"handlers",
"[",
"type",
"]",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Unrecognized beautifier type:'",
",",
"type",
")",
";",
"}"
]
| Method returns beautify handler for specific type of file.
@param {String} type - type of file e.g. html or js.
@return {Object} - beautify object. | [
"Method",
"returns",
"beautify",
"handler",
"for",
"specific",
"type",
"of",
"file",
"."
]
| a896ee6c348d779c27694e3225cf5355f88b2e74 | https://github.com/tomaszczechowski/jsbeautify-loader/blob/a896ee6c348d779c27694e3225cf5355f88b2e74/index.js#L25-L37 |
|
45,860 | tomaszczechowski/jsbeautify-loader | index.js | function (options, fileExtension) {
var getOptionsKey = function (options, fileExtension) {
for (var prop in options) {
var _prop = prop.toLowerCase();
if ((options[_prop].hasOwnProperty('allowed_file_extensions') && options[_prop].allowed_file_extensions.indexOf(fileExtension) > -1) || (!options[_prop].hasOwnProperty('allowed_file_extensions') && _prop === fileExtension)) {
return prop;
}
}
return null;
};
if (isNestedStructure(options)) {
var optionsKey = getOptionsKey(options, fileExtension);
return optionsKey !== null ? options[optionsKey]: {};
}
return options;
} | javascript | function (options, fileExtension) {
var getOptionsKey = function (options, fileExtension) {
for (var prop in options) {
var _prop = prop.toLowerCase();
if ((options[_prop].hasOwnProperty('allowed_file_extensions') && options[_prop].allowed_file_extensions.indexOf(fileExtension) > -1) || (!options[_prop].hasOwnProperty('allowed_file_extensions') && _prop === fileExtension)) {
return prop;
}
}
return null;
};
if (isNestedStructure(options)) {
var optionsKey = getOptionsKey(options, fileExtension);
return optionsKey !== null ? options[optionsKey]: {};
}
return options;
} | [
"function",
"(",
"options",
",",
"fileExtension",
")",
"{",
"var",
"getOptionsKey",
"=",
"function",
"(",
"options",
",",
"fileExtension",
")",
"{",
"for",
"(",
"var",
"prop",
"in",
"options",
")",
"{",
"var",
"_prop",
"=",
"prop",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"(",
"options",
"[",
"_prop",
"]",
".",
"hasOwnProperty",
"(",
"'allowed_file_extensions'",
")",
"&&",
"options",
"[",
"_prop",
"]",
".",
"allowed_file_extensions",
".",
"indexOf",
"(",
"fileExtension",
")",
">",
"-",
"1",
")",
"||",
"(",
"!",
"options",
"[",
"_prop",
"]",
".",
"hasOwnProperty",
"(",
"'allowed_file_extensions'",
")",
"&&",
"_prop",
"===",
"fileExtension",
")",
")",
"{",
"return",
"prop",
";",
"}",
"}",
"return",
"null",
";",
"}",
";",
"if",
"(",
"isNestedStructure",
"(",
"options",
")",
")",
"{",
"var",
"optionsKey",
"=",
"getOptionsKey",
"(",
"options",
",",
"fileExtension",
")",
";",
"return",
"optionsKey",
"!==",
"null",
"?",
"options",
"[",
"optionsKey",
"]",
":",
"{",
"}",
";",
"}",
"return",
"options",
";",
"}"
]
| Method checks whether file's extension has corresponded configuration object.
@param {Object} options - configuration object.
@param {String} fileExtension - file's extension.
@return {String|Object} - object key or null. | [
"Method",
"checks",
"whether",
"file",
"s",
"extension",
"has",
"corresponded",
"configuration",
"object",
"."
]
| a896ee6c348d779c27694e3225cf5355f88b2e74 | https://github.com/tomaszczechowski/jsbeautify-loader/blob/a896ee6c348d779c27694e3225cf5355f88b2e74/index.js#L73-L92 |
|
45,861 | tomaszczechowski/jsbeautify-loader | index.js | function (source, fileExtension, globalOptions, beautify) {
var path = rcFile.for(this.resourcePath)
, options = globalOptions || {};
if (globalOptions === null && typeof path === "string") {
this.addDependency(path);
options = JSON.parse(stripJsonComments(fs.readFileSync(path, "utf8")));
}
return beautify(source, getOptionsForExtension(options, fileExtension));
} | javascript | function (source, fileExtension, globalOptions, beautify) {
var path = rcFile.for(this.resourcePath)
, options = globalOptions || {};
if (globalOptions === null && typeof path === "string") {
this.addDependency(path);
options = JSON.parse(stripJsonComments(fs.readFileSync(path, "utf8")));
}
return beautify(source, getOptionsForExtension(options, fileExtension));
} | [
"function",
"(",
"source",
",",
"fileExtension",
",",
"globalOptions",
",",
"beautify",
")",
"{",
"var",
"path",
"=",
"rcFile",
".",
"for",
"(",
"this",
".",
"resourcePath",
")",
",",
"options",
"=",
"globalOptions",
"||",
"{",
"}",
";",
"if",
"(",
"globalOptions",
"===",
"null",
"&&",
"typeof",
"path",
"===",
"\"string\"",
")",
"{",
"this",
".",
"addDependency",
"(",
"path",
")",
";",
"options",
"=",
"JSON",
".",
"parse",
"(",
"stripJsonComments",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
",",
"\"utf8\"",
")",
")",
")",
";",
"}",
"return",
"beautify",
"(",
"source",
",",
"getOptionsForExtension",
"(",
"options",
",",
"fileExtension",
")",
")",
";",
"}"
]
| Method parses file synchronously
@param {String} source - file's content.
@param {String} fileExtension - file's extension.
@param {Object} globalOptions - configuration from weback file.
@return {String} - parsed content of file. | [
"Method",
"parses",
"file",
"synchronously"
]
| a896ee6c348d779c27694e3225cf5355f88b2e74 | https://github.com/tomaszczechowski/jsbeautify-loader/blob/a896ee6c348d779c27694e3225cf5355f88b2e74/index.js#L101-L111 |
|
45,862 | tomaszczechowski/jsbeautify-loader | index.js | function (source, fileExtension, globalOptions, beautify, callback) {
var _this = this;
if (globalOptions === null) {
rcFile.for(this.resourcePath, function (err, path) {
if (!err) {
if (typeof path === "string") {
_this.addDependency(path);
fs.readFile(path, "utf8", function (err, file) {
if (!err) {
var options = getOptionsForExtension(JSON.parse(stripJsonComments(file)), fileExtension);
callback(null, beautify(source, options));
} else {
callback(err);
}
});
} else {
callback(null, beautify(source, {}));
}
} else {
callback(err);
}
});
} else {
callback(null, beautify(source, getOptionsForExtension(globalOptions, fileExtension)));
}
} | javascript | function (source, fileExtension, globalOptions, beautify, callback) {
var _this = this;
if (globalOptions === null) {
rcFile.for(this.resourcePath, function (err, path) {
if (!err) {
if (typeof path === "string") {
_this.addDependency(path);
fs.readFile(path, "utf8", function (err, file) {
if (!err) {
var options = getOptionsForExtension(JSON.parse(stripJsonComments(file)), fileExtension);
callback(null, beautify(source, options));
} else {
callback(err);
}
});
} else {
callback(null, beautify(source, {}));
}
} else {
callback(err);
}
});
} else {
callback(null, beautify(source, getOptionsForExtension(globalOptions, fileExtension)));
}
} | [
"function",
"(",
"source",
",",
"fileExtension",
",",
"globalOptions",
",",
"beautify",
",",
"callback",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"if",
"(",
"globalOptions",
"===",
"null",
")",
"{",
"rcFile",
".",
"for",
"(",
"this",
".",
"resourcePath",
",",
"function",
"(",
"err",
",",
"path",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"if",
"(",
"typeof",
"path",
"===",
"\"string\"",
")",
"{",
"_this",
".",
"addDependency",
"(",
"path",
")",
";",
"fs",
".",
"readFile",
"(",
"path",
",",
"\"utf8\"",
",",
"function",
"(",
"err",
",",
"file",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"var",
"options",
"=",
"getOptionsForExtension",
"(",
"JSON",
".",
"parse",
"(",
"stripJsonComments",
"(",
"file",
")",
")",
",",
"fileExtension",
")",
";",
"callback",
"(",
"null",
",",
"beautify",
"(",
"source",
",",
"options",
")",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"beautify",
"(",
"source",
",",
"{",
"}",
")",
")",
";",
"}",
"}",
"else",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"beautify",
"(",
"source",
",",
"getOptionsForExtension",
"(",
"globalOptions",
",",
"fileExtension",
")",
")",
")",
";",
"}",
"}"
]
| Method parses file asynchronously
@param {String} source - file's content.
@param {String} fileExtension - file's extension.
@param {Object} globalOptions - configuration from weback file.
@param {Function} callback - callback function with processed file content or with error message. | [
"Method",
"parses",
"file",
"asynchronously"
]
| a896ee6c348d779c27694e3225cf5355f88b2e74 | https://github.com/tomaszczechowski/jsbeautify-loader/blob/a896ee6c348d779c27694e3225cf5355f88b2e74/index.js#L120-L147 |
|
45,863 | joelabair/Bracket-Templates | index.js | _extract | function _extract(keyStr, dataObj) {
var altkey,
_subKey,
_splitPoint,
_found = false,
dataValue = null,
_queryParts = [];
if (dataObj && typeof dataObj === 'object') {
dataValue = Object.create(dataObj);
_queryParts = keyStr.split(/[\-\_\.]/);
//console.warn("INIT:", keyStr, _queryParts);
// test whole query first
if (keyStr in dataValue) {
dataValue = dataValue[keyStr];
_queryParts.length = 0;
_found = true;
}
// search from smallest to largest possible keys
while(_queryParts.length) {
_splitPoint = _queryParts.shift();
_subKey = keyStr.split(new RegExp('('+_splitPoint+')')).slice(0,2).join("");
if (_subKey in dataValue) {
dataValue = dataValue[_subKey];
keyStr = keyStr.split(new RegExp('('+_subKey+'[\-\_\.])')).slice(2).join("");
_found = true;
} else {
_found = false;
}
//console.warn(_found, _subKey, dataValue);
}
if (!_found) {
// alternate support for delimiters in place of spaces as a key
altkey = keyStr.replace(/[\-\_\.]/,' ');
if (altkey in dataObj) {
dataValue = dataObj[altkey];
_found = true;
}
}
}
return _found ? dataValue : NaN;
} | javascript | function _extract(keyStr, dataObj) {
var altkey,
_subKey,
_splitPoint,
_found = false,
dataValue = null,
_queryParts = [];
if (dataObj && typeof dataObj === 'object') {
dataValue = Object.create(dataObj);
_queryParts = keyStr.split(/[\-\_\.]/);
//console.warn("INIT:", keyStr, _queryParts);
// test whole query first
if (keyStr in dataValue) {
dataValue = dataValue[keyStr];
_queryParts.length = 0;
_found = true;
}
// search from smallest to largest possible keys
while(_queryParts.length) {
_splitPoint = _queryParts.shift();
_subKey = keyStr.split(new RegExp('('+_splitPoint+')')).slice(0,2).join("");
if (_subKey in dataValue) {
dataValue = dataValue[_subKey];
keyStr = keyStr.split(new RegExp('('+_subKey+'[\-\_\.])')).slice(2).join("");
_found = true;
} else {
_found = false;
}
//console.warn(_found, _subKey, dataValue);
}
if (!_found) {
// alternate support for delimiters in place of spaces as a key
altkey = keyStr.replace(/[\-\_\.]/,' ');
if (altkey in dataObj) {
dataValue = dataObj[altkey];
_found = true;
}
}
}
return _found ? dataValue : NaN;
} | [
"function",
"_extract",
"(",
"keyStr",
",",
"dataObj",
")",
"{",
"var",
"altkey",
",",
"_subKey",
",",
"_splitPoint",
",",
"_found",
"=",
"false",
",",
"dataValue",
"=",
"null",
",",
"_queryParts",
"=",
"[",
"]",
";",
"if",
"(",
"dataObj",
"&&",
"typeof",
"dataObj",
"===",
"'object'",
")",
"{",
"dataValue",
"=",
"Object",
".",
"create",
"(",
"dataObj",
")",
";",
"_queryParts",
"=",
"keyStr",
".",
"split",
"(",
"/",
"[\\-\\_\\.]",
"/",
")",
";",
"//console.warn(\"INIT:\", keyStr, _queryParts);",
"// test whole query first",
"if",
"(",
"keyStr",
"in",
"dataValue",
")",
"{",
"dataValue",
"=",
"dataValue",
"[",
"keyStr",
"]",
";",
"_queryParts",
".",
"length",
"=",
"0",
";",
"_found",
"=",
"true",
";",
"}",
"// search from smallest to largest possible keys",
"while",
"(",
"_queryParts",
".",
"length",
")",
"{",
"_splitPoint",
"=",
"_queryParts",
".",
"shift",
"(",
")",
";",
"_subKey",
"=",
"keyStr",
".",
"split",
"(",
"new",
"RegExp",
"(",
"'('",
"+",
"_splitPoint",
"+",
"')'",
")",
")",
".",
"slice",
"(",
"0",
",",
"2",
")",
".",
"join",
"(",
"\"\"",
")",
";",
"if",
"(",
"_subKey",
"in",
"dataValue",
")",
"{",
"dataValue",
"=",
"dataValue",
"[",
"_subKey",
"]",
";",
"keyStr",
"=",
"keyStr",
".",
"split",
"(",
"new",
"RegExp",
"(",
"'('",
"+",
"_subKey",
"+",
"'[\\-\\_\\.])'",
")",
")",
".",
"slice",
"(",
"2",
")",
".",
"join",
"(",
"\"\"",
")",
";",
"_found",
"=",
"true",
";",
"}",
"else",
"{",
"_found",
"=",
"false",
";",
"}",
"//console.warn(_found, _subKey, dataValue);",
"}",
"if",
"(",
"!",
"_found",
")",
"{",
"// alternate support for delimiters in place of spaces as a key",
"altkey",
"=",
"keyStr",
".",
"replace",
"(",
"/",
"[\\-\\_\\.]",
"/",
",",
"' '",
")",
";",
"if",
"(",
"altkey",
"in",
"dataObj",
")",
"{",
"dataValue",
"=",
"dataObj",
"[",
"altkey",
"]",
";",
"_found",
"=",
"true",
";",
"}",
"}",
"}",
"return",
"_found",
"?",
"dataValue",
":",
"NaN",
";",
"}"
]
| key notation value extraction
@param {String} keyStr The key string, including sub-key notation (i.e. this.prop.key or thing-prop).
@param {Object} dataObj The data object an array or object.
@returns {Mixed} | [
"key",
"notation",
"value",
"extraction"
]
| 6a2025b900e1dde68bf20820c3dec7c48bf98c7d | https://github.com/joelabair/Bracket-Templates/blob/6a2025b900e1dde68bf20820c3dec7c48bf98c7d/index.js#L50-L96 |
45,864 | joelabair/Bracket-Templates | index.js | renderData | function renderData(textString, options, data, doSpecials) {
var replacer = function replacer(match, $1, $2) {
var extracted,
dataValue,
key = String($1 || '').trim(),
defaultValue = String($2 || '').trim();
// literal bracket excaping via \[ text ]
if(match.substr(0, 1) === "\\") {
return match.substr(1);
}
if (options && typeof options === 'object' && options.strictKeys) {
extracted = _extract(key, data);
dataValue = !Number.isNaN(extracted) ? extracted : match;
} else {
extracted = _extract(key, data);
dataValue = !Number.isNaN(extracted) ? extracted : defaultValue;
}
if (defaultValue) {
if (null === dataValue || typeof dataValue === 'object' || typeof dataValue === 'function' ) {
dataValue = '';
}
}
return String(dataValue) || String(defaultValue);
};
var pattern = new RegExp('\\\\?\\[(?:\\s*([\\w\\-\\.]+)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g');
var spPattern = new RegExp('\\\\?\\[(?:\\s*(KEY|INDEX|VALUE)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g');
if(typeof data === 'object' && data !== null) {
if (options && typeof options === 'object' && options.prefix) {
pattern = new RegExp('\\\\?\\[(?:\\s*'+rxquote(String(options.prefix))+'[\\.\\-\\_]([\\w\\-\\.]+)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g');
}
if (doSpecials) {
textString = textString.replace(spPattern, replacer);
}
textString = textString.replace(pattern, replacer);
} else {
throw new Error('No data to render!');
}
// clean any uncaught bracket-escape sequences
return textString.replace(/(?:\\+)\[(.+)(?:\\+)\]/g, "[$1]").replace(/(?:\\+)\[(.+)(?:\\*)\]/g, "[$1]");
} | javascript | function renderData(textString, options, data, doSpecials) {
var replacer = function replacer(match, $1, $2) {
var extracted,
dataValue,
key = String($1 || '').trim(),
defaultValue = String($2 || '').trim();
// literal bracket excaping via \[ text ]
if(match.substr(0, 1) === "\\") {
return match.substr(1);
}
if (options && typeof options === 'object' && options.strictKeys) {
extracted = _extract(key, data);
dataValue = !Number.isNaN(extracted) ? extracted : match;
} else {
extracted = _extract(key, data);
dataValue = !Number.isNaN(extracted) ? extracted : defaultValue;
}
if (defaultValue) {
if (null === dataValue || typeof dataValue === 'object' || typeof dataValue === 'function' ) {
dataValue = '';
}
}
return String(dataValue) || String(defaultValue);
};
var pattern = new RegExp('\\\\?\\[(?:\\s*([\\w\\-\\.]+)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g');
var spPattern = new RegExp('\\\\?\\[(?:\\s*(KEY|INDEX|VALUE)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g');
if(typeof data === 'object' && data !== null) {
if (options && typeof options === 'object' && options.prefix) {
pattern = new RegExp('\\\\?\\[(?:\\s*'+rxquote(String(options.prefix))+'[\\.\\-\\_]([\\w\\-\\.]+)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g');
}
if (doSpecials) {
textString = textString.replace(spPattern, replacer);
}
textString = textString.replace(pattern, replacer);
} else {
throw new Error('No data to render!');
}
// clean any uncaught bracket-escape sequences
return textString.replace(/(?:\\+)\[(.+)(?:\\+)\]/g, "[$1]").replace(/(?:\\+)\[(.+)(?:\\*)\]/g, "[$1]");
} | [
"function",
"renderData",
"(",
"textString",
",",
"options",
",",
"data",
",",
"doSpecials",
")",
"{",
"var",
"replacer",
"=",
"function",
"replacer",
"(",
"match",
",",
"$1",
",",
"$2",
")",
"{",
"var",
"extracted",
",",
"dataValue",
",",
"key",
"=",
"String",
"(",
"$1",
"||",
"''",
")",
".",
"trim",
"(",
")",
",",
"defaultValue",
"=",
"String",
"(",
"$2",
"||",
"''",
")",
".",
"trim",
"(",
")",
";",
"// literal bracket excaping via \\[ text ]",
"if",
"(",
"match",
".",
"substr",
"(",
"0",
",",
"1",
")",
"===",
"\"\\\\\"",
")",
"{",
"return",
"match",
".",
"substr",
"(",
"1",
")",
";",
"}",
"if",
"(",
"options",
"&&",
"typeof",
"options",
"===",
"'object'",
"&&",
"options",
".",
"strictKeys",
")",
"{",
"extracted",
"=",
"_extract",
"(",
"key",
",",
"data",
")",
";",
"dataValue",
"=",
"!",
"Number",
".",
"isNaN",
"(",
"extracted",
")",
"?",
"extracted",
":",
"match",
";",
"}",
"else",
"{",
"extracted",
"=",
"_extract",
"(",
"key",
",",
"data",
")",
";",
"dataValue",
"=",
"!",
"Number",
".",
"isNaN",
"(",
"extracted",
")",
"?",
"extracted",
":",
"defaultValue",
";",
"}",
"if",
"(",
"defaultValue",
")",
"{",
"if",
"(",
"null",
"===",
"dataValue",
"||",
"typeof",
"dataValue",
"===",
"'object'",
"||",
"typeof",
"dataValue",
"===",
"'function'",
")",
"{",
"dataValue",
"=",
"''",
";",
"}",
"}",
"return",
"String",
"(",
"dataValue",
")",
"||",
"String",
"(",
"defaultValue",
")",
";",
"}",
";",
"var",
"pattern",
"=",
"new",
"RegExp",
"(",
"'\\\\\\\\?\\\\[(?:\\\\s*([\\\\w\\\\-\\\\.]+)\\\\s*)(?:\\\\:([^\\\\[\\\\]]+))?\\\\]'",
",",
"'g'",
")",
";",
"var",
"spPattern",
"=",
"new",
"RegExp",
"(",
"'\\\\\\\\?\\\\[(?:\\\\s*(KEY|INDEX|VALUE)\\\\s*)(?:\\\\:([^\\\\[\\\\]]+))?\\\\]'",
",",
"'g'",
")",
";",
"if",
"(",
"typeof",
"data",
"===",
"'object'",
"&&",
"data",
"!==",
"null",
")",
"{",
"if",
"(",
"options",
"&&",
"typeof",
"options",
"===",
"'object'",
"&&",
"options",
".",
"prefix",
")",
"{",
"pattern",
"=",
"new",
"RegExp",
"(",
"'\\\\\\\\?\\\\[(?:\\\\s*'",
"+",
"rxquote",
"(",
"String",
"(",
"options",
".",
"prefix",
")",
")",
"+",
"'[\\\\.\\\\-\\\\_]([\\\\w\\\\-\\\\.]+)\\\\s*)(?:\\\\:([^\\\\[\\\\]]+))?\\\\]'",
",",
"'g'",
")",
";",
"}",
"if",
"(",
"doSpecials",
")",
"{",
"textString",
"=",
"textString",
".",
"replace",
"(",
"spPattern",
",",
"replacer",
")",
";",
"}",
"textString",
"=",
"textString",
".",
"replace",
"(",
"pattern",
",",
"replacer",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'No data to render!'",
")",
";",
"}",
"// clean any uncaught bracket-escape sequences",
"return",
"textString",
".",
"replace",
"(",
"/",
"(?:\\\\+)\\[(.+)(?:\\\\+)\\]",
"/",
"g",
",",
"\"[$1]\"",
")",
".",
"replace",
"(",
"/",
"(?:\\\\+)\\[(.+)(?:\\\\*)\\]",
"/",
"g",
",",
"\"[$1]\"",
")",
";",
"}"
]
| Text tag renderer
@param {String} textString The template string.
@param {Object} options The current options config.
@param {Object} data The source keys and values as an object.
@param {Bool} doSpecials Optional - render plain special keys [KEY, INDEX, VALUE]
@returns {String} | [
"Text",
"tag",
"renderer"
]
| 6a2025b900e1dde68bf20820c3dec7c48bf98c7d | https://github.com/joelabair/Bracket-Templates/blob/6a2025b900e1dde68bf20820c3dec7c48bf98c7d/index.js#L199-L244 |
45,865 | joelabair/Bracket-Templates | index.js | getOptions | function getOptions(opts) {
var obj = Object.create(_options);
obj = util._extend(obj, opts);
return obj;
} | javascript | function getOptions(opts) {
var obj = Object.create(_options);
obj = util._extend(obj, opts);
return obj;
} | [
"function",
"getOptions",
"(",
"opts",
")",
"{",
"var",
"obj",
"=",
"Object",
".",
"create",
"(",
"_options",
")",
";",
"obj",
"=",
"util",
".",
"_extend",
"(",
"obj",
",",
"opts",
")",
";",
"return",
"obj",
";",
"}"
]
| Return options inheriting form the module defaults.
@param {Object} options Custom options passed in.
@returns {Object} | [
"Return",
"options",
"inheriting",
"form",
"the",
"module",
"defaults",
"."
]
| 6a2025b900e1dde68bf20820c3dec7c48bf98c7d | https://github.com/joelabair/Bracket-Templates/blob/6a2025b900e1dde68bf20820c3dec7c48bf98c7d/index.js#L253-L257 |
45,866 | mkormendy/node-alarm-dot-com | index.js | getCurrentState | function getCurrentState(systemID, authOpts) {
return authenticatedGet(SYSTEM_URL + systemID, authOpts).then(res => {
const rels = res.data.relationships
const partTasks = rels.partitions.data.map(p =>
getPartition(p.id, authOpts)
)
const sensorIDs = rels.sensors.data.map(s => s.id)
return Promise.all([
Promise.all(partTasks),
getSensors(sensorIDs, authOpts)
]).then(partitionsAndSensors => {
const [partitions, sensors] = partitionsAndSensors
return {
id: res.data.id,
attributes: res.data.attributes,
partitions: partitions.map(p => p.data),
sensors: sensors.data,
relationships: rels
}
})
})
} | javascript | function getCurrentState(systemID, authOpts) {
return authenticatedGet(SYSTEM_URL + systemID, authOpts).then(res => {
const rels = res.data.relationships
const partTasks = rels.partitions.data.map(p =>
getPartition(p.id, authOpts)
)
const sensorIDs = rels.sensors.data.map(s => s.id)
return Promise.all([
Promise.all(partTasks),
getSensors(sensorIDs, authOpts)
]).then(partitionsAndSensors => {
const [partitions, sensors] = partitionsAndSensors
return {
id: res.data.id,
attributes: res.data.attributes,
partitions: partitions.map(p => p.data),
sensors: sensors.data,
relationships: rels
}
})
})
} | [
"function",
"getCurrentState",
"(",
"systemID",
",",
"authOpts",
")",
"{",
"return",
"authenticatedGet",
"(",
"SYSTEM_URL",
"+",
"systemID",
",",
"authOpts",
")",
".",
"then",
"(",
"res",
"=>",
"{",
"const",
"rels",
"=",
"res",
".",
"data",
".",
"relationships",
"const",
"partTasks",
"=",
"rels",
".",
"partitions",
".",
"data",
".",
"map",
"(",
"p",
"=>",
"getPartition",
"(",
"p",
".",
"id",
",",
"authOpts",
")",
")",
"const",
"sensorIDs",
"=",
"rels",
".",
"sensors",
".",
"data",
".",
"map",
"(",
"s",
"=>",
"s",
".",
"id",
")",
"return",
"Promise",
".",
"all",
"(",
"[",
"Promise",
".",
"all",
"(",
"partTasks",
")",
",",
"getSensors",
"(",
"sensorIDs",
",",
"authOpts",
")",
"]",
")",
".",
"then",
"(",
"partitionsAndSensors",
"=>",
"{",
"const",
"[",
"partitions",
",",
"sensors",
"]",
"=",
"partitionsAndSensors",
"return",
"{",
"id",
":",
"res",
".",
"data",
".",
"id",
",",
"attributes",
":",
"res",
".",
"data",
".",
"attributes",
",",
"partitions",
":",
"partitions",
".",
"map",
"(",
"p",
"=>",
"p",
".",
"data",
")",
",",
"sensors",
":",
"sensors",
".",
"data",
",",
"relationships",
":",
"rels",
"}",
"}",
")",
"}",
")",
"}"
]
| Retrieve information about the current state of a security system including
attributes, partitions, sensors, and relationships.
@param {string} systemID ID of the system to query. The Authentication object
returned from the `login` method contains a `systems` property which is an
array of system IDs.
@param {Object} authOpts Authentication object returned from the `login`
method.
@returns {Promise} | [
"Retrieve",
"information",
"about",
"the",
"current",
"state",
"of",
"a",
"security",
"system",
"including",
"attributes",
"partitions",
"sensors",
"and",
"relationships",
"."
]
| b4ac45886eaddd5e739cd49b7aa8f9189c0124cc | https://github.com/mkormendy/node-alarm-dot-com/blob/b4ac45886eaddd5e739cd49b7aa8f9189c0124cc/index.js#L167-L189 |
45,867 | mkormendy/node-alarm-dot-com | index.js | getSensors | function getSensors(sensorIDs, authOpts) {
if (!Array.isArray(sensorIDs)) sensorIDs = [sensorIDs]
const query = sensorIDs.map(id => `ids%5B%5D=${id}`).join('&')
const url = `${SENSORS_URL}?${query}`
return authenticatedGet(url, authOpts)
} | javascript | function getSensors(sensorIDs, authOpts) {
if (!Array.isArray(sensorIDs)) sensorIDs = [sensorIDs]
const query = sensorIDs.map(id => `ids%5B%5D=${id}`).join('&')
const url = `${SENSORS_URL}?${query}`
return authenticatedGet(url, authOpts)
} | [
"function",
"getSensors",
"(",
"sensorIDs",
",",
"authOpts",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"sensorIDs",
")",
")",
"sensorIDs",
"=",
"[",
"sensorIDs",
"]",
"const",
"query",
"=",
"sensorIDs",
".",
"map",
"(",
"id",
"=>",
"`",
"${",
"id",
"}",
"`",
")",
".",
"join",
"(",
"'&'",
")",
"const",
"url",
"=",
"`",
"${",
"SENSORS_URL",
"}",
"${",
"query",
"}",
"`",
"return",
"authenticatedGet",
"(",
"url",
",",
"authOpts",
")",
"}"
]
| Get information for one or more sensors.
@param {string|string[]} sensorIDs Array of sensor ID strings.
@param {Object} authOpts Authentication object returned from the `login`
method.
@returns {Promise} | [
"Get",
"information",
"for",
"one",
"or",
"more",
"sensors",
"."
]
| b4ac45886eaddd5e739cd49b7aa8f9189c0124cc | https://github.com/mkormendy/node-alarm-dot-com/blob/b4ac45886eaddd5e739cd49b7aa8f9189c0124cc/index.js#L211-L216 |
45,868 | buttercup/buttercup-core-web | source/StorageInterface.js | function(key, defaultValue) {
var value = window.localStorage.getItem(key);
return value ? JSON.parse(value) : defaultValue;
} | javascript | function(key, defaultValue) {
var value = window.localStorage.getItem(key);
return value ? JSON.parse(value) : defaultValue;
} | [
"function",
"(",
"key",
",",
"defaultValue",
")",
"{",
"var",
"value",
"=",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"key",
")",
";",
"return",
"value",
"?",
"JSON",
".",
"parse",
"(",
"value",
")",
":",
"defaultValue",
";",
"}"
]
| Get data from storage
@memberof StorageInterface
@name getData
@static
@param {String} key The key to fetch for
@param {*} defaultValue The default value if the key is not found
@returns {*} The fetched data | [
"Get",
"data",
"from",
"storage"
]
| 40b6ff7ee4b04a085720dbb013782be8e921f864 | https://github.com/buttercup/buttercup-core-web/blob/40b6ff7ee4b04a085720dbb013782be8e921f864/source/StorageInterface.js#L18-L21 |
|
45,869 | cgalvarez/atom-coverage | lib/util.js | writeConfig | function writeConfig(filePath, data, fileFormat) {
if (!filePath || !data) {
throw new Error('No file/data to save!');
}
const ext = rgxExt.exec(filePath) || [];
const format = fileFormat || ext[1];
if (format === 'yaml' || format === 'yml') {
return writeFileSync(filePath, yaml.safeDump(data), { encoding: 'utf8' });
}
return outputJSONSync(filePath, data, { spaces: 2 });
} | javascript | function writeConfig(filePath, data, fileFormat) {
if (!filePath || !data) {
throw new Error('No file/data to save!');
}
const ext = rgxExt.exec(filePath) || [];
const format = fileFormat || ext[1];
if (format === 'yaml' || format === 'yml') {
return writeFileSync(filePath, yaml.safeDump(data), { encoding: 'utf8' });
}
return outputJSONSync(filePath, data, { spaces: 2 });
} | [
"function",
"writeConfig",
"(",
"filePath",
",",
"data",
",",
"fileFormat",
")",
"{",
"if",
"(",
"!",
"filePath",
"||",
"!",
"data",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No file/data to save!'",
")",
";",
"}",
"const",
"ext",
"=",
"rgxExt",
".",
"exec",
"(",
"filePath",
")",
"||",
"[",
"]",
";",
"const",
"format",
"=",
"fileFormat",
"||",
"ext",
"[",
"1",
"]",
";",
"if",
"(",
"format",
"===",
"'yaml'",
"||",
"format",
"===",
"'yml'",
")",
"{",
"return",
"writeFileSync",
"(",
"filePath",
",",
"yaml",
".",
"safeDump",
"(",
"data",
")",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"}",
"return",
"outputJSONSync",
"(",
"filePath",
",",
"data",
",",
"{",
"spaces",
":",
"2",
"}",
")",
";",
"}"
]
| Writes a given JSON object `data` to a `filePath` with the requested `format`.
@param {String} filePath The path where to write the file.
@param {Object} data The object to write into the file contents.
@param {String} fileFormat One of "yaml", "yml", "json". | [
"Writes",
"a",
"given",
"JSON",
"object",
"data",
"to",
"a",
"filePath",
"with",
"the",
"requested",
"format",
"."
]
| c0f9f621bad474079f809b56b532ab2f4004c151 | https://github.com/cgalvarez/atom-coverage/blob/c0f9f621bad474079f809b56b532ab2f4004c151/lib/util.js#L35-L48 |
45,870 | cgalvarez/atom-coverage | lib/util.js | readConfig | function readConfig(globPattern, fileFormat) {
const filepath = findConfigFile(globPattern);
if (!filepath) {
this.settings = {};
return;
}
const ext = rgxExt.exec(filepath) || [];
const format = fileFormat || ext[1];
const settings = (format === 'yaml' || format === 'yml')
? yaml.safeLoad(readFileSync(filepath, 'utf8'))
: readJSONSync(filepath);
this.filepath = filepath;
this.settings = settings;
} | javascript | function readConfig(globPattern, fileFormat) {
const filepath = findConfigFile(globPattern);
if (!filepath) {
this.settings = {};
return;
}
const ext = rgxExt.exec(filepath) || [];
const format = fileFormat || ext[1];
const settings = (format === 'yaml' || format === 'yml')
? yaml.safeLoad(readFileSync(filepath, 'utf8'))
: readJSONSync(filepath);
this.filepath = filepath;
this.settings = settings;
} | [
"function",
"readConfig",
"(",
"globPattern",
",",
"fileFormat",
")",
"{",
"const",
"filepath",
"=",
"findConfigFile",
"(",
"globPattern",
")",
";",
"if",
"(",
"!",
"filepath",
")",
"{",
"this",
".",
"settings",
"=",
"{",
"}",
";",
"return",
";",
"}",
"const",
"ext",
"=",
"rgxExt",
".",
"exec",
"(",
"filepath",
")",
"||",
"[",
"]",
";",
"const",
"format",
"=",
"fileFormat",
"||",
"ext",
"[",
"1",
"]",
";",
"const",
"settings",
"=",
"(",
"format",
"===",
"'yaml'",
"||",
"format",
"===",
"'yml'",
")",
"?",
"yaml",
".",
"safeLoad",
"(",
"readFileSync",
"(",
"filepath",
",",
"'utf8'",
")",
")",
":",
"readJSONSync",
"(",
"filepath",
")",
";",
"this",
".",
"filepath",
"=",
"filepath",
";",
"this",
".",
"settings",
"=",
"settings",
";",
"}"
]
| Searches a config file under current working dir, using the provided glob
pattern `globPattern`.
If found, parses its contents based on the provided `fileFormat`. Currently
only supports YAML or JSON formats (defaults to JSON if format not
provided and cannot be inferred from file extension).
NOTE This function is meant to be called with the transpiler/instrumenter
config object as context.
@param {String} globPattern The glob pattern to find the config file.
@param {String} [fileFormat] One of "yaml", "yml", "json".
@return {Object} The parsed contents of the requested config file. | [
"Searches",
"a",
"config",
"file",
"under",
"current",
"working",
"dir",
"using",
"the",
"provided",
"glob",
"pattern",
"globPattern",
"."
]
| c0f9f621bad474079f809b56b532ab2f4004c151 | https://github.com/cgalvarez/atom-coverage/blob/c0f9f621bad474079f809b56b532ab2f4004c151/lib/util.js#L79-L96 |
45,871 | Marketcloud/marketcloud-js | src/request.js | createXMLHTTPObject | function createXMLHTTPObject () {
var xmlhttp = false
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]()
} catch (e) {
continue
}
break
}
return xmlhttp
} | javascript | function createXMLHTTPObject () {
var xmlhttp = false
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]()
} catch (e) {
continue
}
break
}
return xmlhttp
} | [
"function",
"createXMLHTTPObject",
"(",
")",
"{",
"var",
"xmlhttp",
"=",
"false",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"XMLHttpFactories",
".",
"length",
";",
"i",
"++",
")",
"{",
"try",
"{",
"xmlhttp",
"=",
"XMLHttpFactories",
"[",
"i",
"]",
"(",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"continue",
"}",
"break",
"}",
"return",
"xmlhttp",
"}"
]
| Builds an AJAX request in a cross browser fashion
@returns {XMLHttpRequest|ActiveXObject} The crafted request | [
"Builds",
"an",
"AJAX",
"request",
"in",
"a",
"cross",
"browser",
"fashion"
]
| b41faa9b26445c39422aa167a5cc804ef00d9552 | https://github.com/Marketcloud/marketcloud-js/blob/b41faa9b26445c39422aa167a5cc804ef00d9552/src/request.js#L20-L31 |
45,872 | sydneystockholm/jpegmini | index.js | optionString | function optionString(options) {
return Object.keys(options).map(function (key) {
var value = options[key];
if (value === null) {
return '-' + key;
} else if (typeof value === 'number') {
value += '';
} else if (typeof value === 'string') {
value = '"' + value.replace(/"/g, '\\"') + '"';
}
return '-' + key + '=' + value.replace(/`/g, '');
}).join(' ');
} | javascript | function optionString(options) {
return Object.keys(options).map(function (key) {
var value = options[key];
if (value === null) {
return '-' + key;
} else if (typeof value === 'number') {
value += '';
} else if (typeof value === 'string') {
value = '"' + value.replace(/"/g, '\\"') + '"';
}
return '-' + key + '=' + value.replace(/`/g, '');
}).join(' ');
} | [
"function",
"optionString",
"(",
"options",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"options",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
"'-'",
"+",
"key",
";",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'number'",
")",
"{",
"value",
"+=",
"''",
";",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"value",
"=",
"'\"'",
"+",
"value",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'\\\\\"'",
")",
"+",
"'\"'",
";",
"}",
"return",
"'-'",
"+",
"key",
"+",
"'='",
"+",
"value",
".",
"replace",
"(",
"/",
"`",
"/",
"g",
",",
"''",
")",
";",
"}",
")",
".",
"join",
"(",
"' '",
")",
";",
"}"
]
| Convert an options object to a string. | [
"Convert",
"an",
"options",
"object",
"to",
"a",
"string",
"."
]
| 4ac2377286510817a079dcc84c9d8b1db9a746f6 | https://github.com/sydneystockholm/jpegmini/blob/4ac2377286510817a079dcc84c9d8b1db9a746f6/index.js#L168-L180 |
45,873 | sydneystockholm/jpegmini | index.js | randomString | function randomString() {
var str = '', length = 32;
while (length--) {
str += String.fromCharCode(Math.random() * 26 | 97);
}
return str;
} | javascript | function randomString() {
var str = '', length = 32;
while (length--) {
str += String.fromCharCode(Math.random() * 26 | 97);
}
return str;
} | [
"function",
"randomString",
"(",
")",
"{",
"var",
"str",
"=",
"''",
",",
"length",
"=",
"32",
";",
"while",
"(",
"length",
"--",
")",
"{",
"str",
"+=",
"String",
".",
"fromCharCode",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"26",
"|",
"97",
")",
";",
"}",
"return",
"str",
";",
"}"
]
| Get a random 32 byte string. | [
"Get",
"a",
"random",
"32",
"byte",
"string",
"."
]
| 4ac2377286510817a079dcc84c9d8b1db9a746f6 | https://github.com/sydneystockholm/jpegmini/blob/4ac2377286510817a079dcc84c9d8b1db9a746f6/index.js#L186-L192 |
45,874 | kotfire/jquery-clockpicker | dist/jquery-clockpicker.js | function() {
var element = this.element,
template = this.template,
offset = element.offset(),
width = element.outerWidth(),
height = element.outerHeight(),
position = this.options.position,
alignment = this.options.alignment,
styles = {},
self = this;
template.show();
// Place the template
switch (position) {
case 'bottom':
styles.top = offset.top + height;
break;
case 'right':
styles.left = offset.left + width;
break;
case 'top':
styles.top = offset.top - template.outerHeight();
break;
case 'left':
styles.left = offset.left - template.outerWidth();
break;
}
// Align the template arrow
switch (alignment) {
case 'left':
styles.left = offset.left;
break;
case 'right':
styles.left = offset.left + width - template.outerWidth();
break;
}
template.css(styles);
} | javascript | function() {
var element = this.element,
template = this.template,
offset = element.offset(),
width = element.outerWidth(),
height = element.outerHeight(),
position = this.options.position,
alignment = this.options.alignment,
styles = {},
self = this;
template.show();
// Place the template
switch (position) {
case 'bottom':
styles.top = offset.top + height;
break;
case 'right':
styles.left = offset.left + width;
break;
case 'top':
styles.top = offset.top - template.outerHeight();
break;
case 'left':
styles.left = offset.left - template.outerWidth();
break;
}
// Align the template arrow
switch (alignment) {
case 'left':
styles.left = offset.left;
break;
case 'right':
styles.left = offset.left + width - template.outerWidth();
break;
}
template.css(styles);
} | [
"function",
"(",
")",
"{",
"var",
"element",
"=",
"this",
".",
"element",
",",
"template",
"=",
"this",
".",
"template",
",",
"offset",
"=",
"element",
".",
"offset",
"(",
")",
",",
"width",
"=",
"element",
".",
"outerWidth",
"(",
")",
",",
"height",
"=",
"element",
".",
"outerHeight",
"(",
")",
",",
"position",
"=",
"this",
".",
"options",
".",
"position",
",",
"alignment",
"=",
"this",
".",
"options",
".",
"alignment",
",",
"styles",
"=",
"{",
"}",
",",
"self",
"=",
"this",
";",
"template",
".",
"show",
"(",
")",
";",
"// Place the template",
"switch",
"(",
"position",
")",
"{",
"case",
"'bottom'",
":",
"styles",
".",
"top",
"=",
"offset",
".",
"top",
"+",
"height",
";",
"break",
";",
"case",
"'right'",
":",
"styles",
".",
"left",
"=",
"offset",
".",
"left",
"+",
"width",
";",
"break",
";",
"case",
"'top'",
":",
"styles",
".",
"top",
"=",
"offset",
".",
"top",
"-",
"template",
".",
"outerHeight",
"(",
")",
";",
"break",
";",
"case",
"'left'",
":",
"styles",
".",
"left",
"=",
"offset",
".",
"left",
"-",
"template",
".",
"outerWidth",
"(",
")",
";",
"break",
";",
"}",
"// Align the template arrow",
"switch",
"(",
"alignment",
")",
"{",
"case",
"'left'",
":",
"styles",
".",
"left",
"=",
"offset",
".",
"left",
";",
"break",
";",
"case",
"'right'",
":",
"styles",
".",
"left",
"=",
"offset",
".",
"left",
"+",
"width",
"-",
"template",
".",
"outerWidth",
"(",
")",
";",
"break",
";",
"}",
"template",
".",
"css",
"(",
"styles",
")",
";",
"}"
]
| Set template position | [
"Set",
"template",
"position"
]
| dc41cc5efb1dcd5a583db25cd92fb9f62933a92a | https://github.com/kotfire/jquery-clockpicker/blob/dc41cc5efb1dcd5a583db25cd92fb9f62933a92a/dist/jquery-clockpicker.js#L451-L491 |
|
45,875 | kotfire/jquery-clockpicker | dist/jquery-clockpicker.js | function(view, delay) {
var self = this;
var raiseAfterShowHours = false;
var raiseAfterShowMinutes = false;
if (view === 'hours') {
raiseCallback(this.options.beforeShowHours);
raiseAfterShowHours = true;
}
if (view === 'minutes') {
raiseCallback(this.options.beforeShowMinutes);
raiseAfterShowMinutes = true;
}
var isHours = view === 'hours',
nextView = isHours ? this.hoursView : this.minutesView,
hideView = isHours ? this.minutesView : this.hoursView;
this.currentView = view;
this._checkTimeLimits();
this.hoursLabel.toggleClass('jqclockpicker-active', isHours);
this.minutesLabel.toggleClass('jqclockpicker-active', !isHours);
// Let's make transitions
hideView.addClass('jqclockpicker-dial-out');
nextView.css('visibility', 'visible').removeClass('jqclockpicker-dial-out');
// Reset clock hand
this.resetClock(delay);
// After transitions ended
clearTimeout(this.toggleViewTimer);
this.toggleViewTimer = setTimeout(function() {
hideView.css('visibility', 'hidden');
}, duration);
if (raiseAfterShowHours) {
raiseCallback(this.options.afterShowHours);
}
if (raiseAfterShowMinutes) {
raiseCallback(this.options.afterShowMinutes);
}
} | javascript | function(view, delay) {
var self = this;
var raiseAfterShowHours = false;
var raiseAfterShowMinutes = false;
if (view === 'hours') {
raiseCallback(this.options.beforeShowHours);
raiseAfterShowHours = true;
}
if (view === 'minutes') {
raiseCallback(this.options.beforeShowMinutes);
raiseAfterShowMinutes = true;
}
var isHours = view === 'hours',
nextView = isHours ? this.hoursView : this.minutesView,
hideView = isHours ? this.minutesView : this.hoursView;
this.currentView = view;
this._checkTimeLimits();
this.hoursLabel.toggleClass('jqclockpicker-active', isHours);
this.minutesLabel.toggleClass('jqclockpicker-active', !isHours);
// Let's make transitions
hideView.addClass('jqclockpicker-dial-out');
nextView.css('visibility', 'visible').removeClass('jqclockpicker-dial-out');
// Reset clock hand
this.resetClock(delay);
// After transitions ended
clearTimeout(this.toggleViewTimer);
this.toggleViewTimer = setTimeout(function() {
hideView.css('visibility', 'hidden');
}, duration);
if (raiseAfterShowHours) {
raiseCallback(this.options.afterShowHours);
}
if (raiseAfterShowMinutes) {
raiseCallback(this.options.afterShowMinutes);
}
} | [
"function",
"(",
"view",
",",
"delay",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"raiseAfterShowHours",
"=",
"false",
";",
"var",
"raiseAfterShowMinutes",
"=",
"false",
";",
"if",
"(",
"view",
"===",
"'hours'",
")",
"{",
"raiseCallback",
"(",
"this",
".",
"options",
".",
"beforeShowHours",
")",
";",
"raiseAfterShowHours",
"=",
"true",
";",
"}",
"if",
"(",
"view",
"===",
"'minutes'",
")",
"{",
"raiseCallback",
"(",
"this",
".",
"options",
".",
"beforeShowMinutes",
")",
";",
"raiseAfterShowMinutes",
"=",
"true",
";",
"}",
"var",
"isHours",
"=",
"view",
"===",
"'hours'",
",",
"nextView",
"=",
"isHours",
"?",
"this",
".",
"hoursView",
":",
"this",
".",
"minutesView",
",",
"hideView",
"=",
"isHours",
"?",
"this",
".",
"minutesView",
":",
"this",
".",
"hoursView",
";",
"this",
".",
"currentView",
"=",
"view",
";",
"this",
".",
"_checkTimeLimits",
"(",
")",
";",
"this",
".",
"hoursLabel",
".",
"toggleClass",
"(",
"'jqclockpicker-active'",
",",
"isHours",
")",
";",
"this",
".",
"minutesLabel",
".",
"toggleClass",
"(",
"'jqclockpicker-active'",
",",
"!",
"isHours",
")",
";",
"// Let's make transitions",
"hideView",
".",
"addClass",
"(",
"'jqclockpicker-dial-out'",
")",
";",
"nextView",
".",
"css",
"(",
"'visibility'",
",",
"'visible'",
")",
".",
"removeClass",
"(",
"'jqclockpicker-dial-out'",
")",
";",
"// Reset clock hand",
"this",
".",
"resetClock",
"(",
"delay",
")",
";",
"// After transitions ended",
"clearTimeout",
"(",
"this",
".",
"toggleViewTimer",
")",
";",
"this",
".",
"toggleViewTimer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"hideView",
".",
"css",
"(",
"'visibility'",
",",
"'hidden'",
")",
";",
"}",
",",
"duration",
")",
";",
"if",
"(",
"raiseAfterShowHours",
")",
"{",
"raiseCallback",
"(",
"this",
".",
"options",
".",
"afterShowHours",
")",
";",
"}",
"if",
"(",
"raiseAfterShowMinutes",
")",
"{",
"raiseCallback",
"(",
"this",
".",
"options",
".",
"afterShowMinutes",
")",
";",
"}",
"}"
]
| Toggle to hours or minutes view | [
"Toggle",
"to",
"hours",
"or",
"minutes",
"view"
]
| dc41cc5efb1dcd5a583db25cd92fb9f62933a92a | https://github.com/kotfire/jquery-clockpicker/blob/dc41cc5efb1dcd5a583db25cd92fb9f62933a92a/dist/jquery-clockpicker.js#L575-L619 |
|
45,876 | kotfire/jquery-clockpicker | dist/jquery-clockpicker.js | function(delay) {
var view = this.currentView,
value = this[view],
isHours = view === 'hours',
unit = Math.PI / (isHours ? 6 : 30),
radian = value * unit,
radius = isHours && value > 0 && value < 13 ? innerRadius : outerRadius,
x = Math.sin(radian) * radius,
y = - Math.cos(radian) * radius,
self = this;
if (svgSupported && delay) {
self.canvas.addClass('jqclockpicker-canvas-out');
setTimeout(function() {
self.canvas.removeClass('jqclockpicker-canvas-out');
self.setHand(x, y);
}, delay);
} else {
this.setHand(x, y);
}
} | javascript | function(delay) {
var view = this.currentView,
value = this[view],
isHours = view === 'hours',
unit = Math.PI / (isHours ? 6 : 30),
radian = value * unit,
radius = isHours && value > 0 && value < 13 ? innerRadius : outerRadius,
x = Math.sin(radian) * radius,
y = - Math.cos(radian) * radius,
self = this;
if (svgSupported && delay) {
self.canvas.addClass('jqclockpicker-canvas-out');
setTimeout(function() {
self.canvas.removeClass('jqclockpicker-canvas-out');
self.setHand(x, y);
}, delay);
} else {
this.setHand(x, y);
}
} | [
"function",
"(",
"delay",
")",
"{",
"var",
"view",
"=",
"this",
".",
"currentView",
",",
"value",
"=",
"this",
"[",
"view",
"]",
",",
"isHours",
"=",
"view",
"===",
"'hours'",
",",
"unit",
"=",
"Math",
".",
"PI",
"/",
"(",
"isHours",
"?",
"6",
":",
"30",
")",
",",
"radian",
"=",
"value",
"*",
"unit",
",",
"radius",
"=",
"isHours",
"&&",
"value",
">",
"0",
"&&",
"value",
"<",
"13",
"?",
"innerRadius",
":",
"outerRadius",
",",
"x",
"=",
"Math",
".",
"sin",
"(",
"radian",
")",
"*",
"radius",
",",
"y",
"=",
"-",
"Math",
".",
"cos",
"(",
"radian",
")",
"*",
"radius",
",",
"self",
"=",
"this",
";",
"if",
"(",
"svgSupported",
"&&",
"delay",
")",
"{",
"self",
".",
"canvas",
".",
"addClass",
"(",
"'jqclockpicker-canvas-out'",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"canvas",
".",
"removeClass",
"(",
"'jqclockpicker-canvas-out'",
")",
";",
"self",
".",
"setHand",
"(",
"x",
",",
"y",
")",
";",
"}",
",",
"delay",
")",
";",
"}",
"else",
"{",
"this",
".",
"setHand",
"(",
"x",
",",
"y",
")",
";",
"}",
"}"
]
| Reset clock hand | [
"Reset",
"clock",
"hand"
]
| dc41cc5efb1dcd5a583db25cd92fb9f62933a92a | https://github.com/kotfire/jquery-clockpicker/blob/dc41cc5efb1dcd5a583db25cd92fb9f62933a92a/dist/jquery-clockpicker.js#L622-L642 |
|
45,877 | kotfire/jquery-clockpicker | dist/jquery-clockpicker.js | function(timeObject) {
this.hours = timeObject.hours;
this.minutes = timeObject.minutes;
this.amOrPm = timeObject.amOrPm;
this._checkTimeLimits();
this._updateLabels();
this.resetClock();
} | javascript | function(timeObject) {
this.hours = timeObject.hours;
this.minutes = timeObject.minutes;
this.amOrPm = timeObject.amOrPm;
this._checkTimeLimits();
this._updateLabels();
this.resetClock();
} | [
"function",
"(",
"timeObject",
")",
"{",
"this",
".",
"hours",
"=",
"timeObject",
".",
"hours",
";",
"this",
".",
"minutes",
"=",
"timeObject",
".",
"minutes",
";",
"this",
".",
"amOrPm",
"=",
"timeObject",
".",
"amOrPm",
";",
"this",
".",
"_checkTimeLimits",
"(",
")",
";",
"this",
".",
"_updateLabels",
"(",
")",
";",
"this",
".",
"resetClock",
"(",
")",
";",
"}"
]
| Set time from ClockTime object | [
"Set",
"time",
"from",
"ClockTime",
"object"
]
| dc41cc5efb1dcd5a583db25cd92fb9f62933a92a | https://github.com/kotfire/jquery-clockpicker/blob/dc41cc5efb1dcd5a583db25cd92fb9f62933a92a/dist/jquery-clockpicker.js#L848-L858 |
|
45,878 | vrest-io/vrunner | lib/replacingStrings.js | function(str, methodDec, methodName, method, methodsMap, options){
var methodValue = getMethodValue(methodDec, methodName, method, methodsMap, options);
if(str === methodDec) return methodValue;
return str.replace(methodDec, function(){ return methodValue; });
} | javascript | function(str, methodDec, methodName, method, methodsMap, options){
var methodValue = getMethodValue(methodDec, methodName, method, methodsMap, options);
if(str === methodDec) return methodValue;
return str.replace(methodDec, function(){ return methodValue; });
} | [
"function",
"(",
"str",
",",
"methodDec",
",",
"methodName",
",",
"method",
",",
"methodsMap",
",",
"options",
")",
"{",
"var",
"methodValue",
"=",
"getMethodValue",
"(",
"methodDec",
",",
"methodName",
",",
"method",
",",
"methodsMap",
",",
"options",
")",
";",
"if",
"(",
"str",
"===",
"methodDec",
")",
"return",
"methodValue",
";",
"return",
"str",
".",
"replace",
"(",
"methodDec",
",",
"function",
"(",
")",
"{",
"return",
"methodValue",
";",
"}",
")",
";",
"}"
]
| invokes a single method and replaces its value in the string | [
"invokes",
"a",
"single",
"method",
"and",
"replaces",
"its",
"value",
"in",
"the",
"string"
]
| cad70c21cb9a763e74dcffebad1c45ca11a63a1e | https://github.com/vrest-io/vrunner/blob/cad70c21cb9a763e74dcffebad1c45ca11a63a1e/lib/replacingStrings.js#L179-L183 |
|
45,879 | nickclaw/alexa-ssml | src/renderToString.js | renderNode | function renderNode(node, children = []) {
[...children].forEach(child => {
if (child && child.tag) {
node.ele(child.tag, child.props);
renderNode(node, child.children);
node.end();
} else {
node.text(child);
}
});
} | javascript | function renderNode(node, children = []) {
[...children].forEach(child => {
if (child && child.tag) {
node.ele(child.tag, child.props);
renderNode(node, child.children);
node.end();
} else {
node.text(child);
}
});
} | [
"function",
"renderNode",
"(",
"node",
",",
"children",
"=",
"[",
"]",
")",
"{",
"[",
"...",
"children",
"]",
".",
"forEach",
"(",
"child",
"=>",
"{",
"if",
"(",
"child",
"&&",
"child",
".",
"tag",
")",
"{",
"node",
".",
"ele",
"(",
"child",
".",
"tag",
",",
"child",
".",
"props",
")",
";",
"renderNode",
"(",
"node",
",",
"child",
".",
"children",
")",
";",
"node",
".",
"end",
"(",
")",
";",
"}",
"else",
"{",
"node",
".",
"text",
"(",
"child",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Recursively turns jsx children into xml nodes
@param {Array} children
@param {XMLNode} node | [
"Recursively",
"turns",
"jsx",
"children",
"into",
"xml",
"nodes"
]
| f857e2daa9e4e5d7ed1ff40b78fd56a66d9d228d | https://github.com/nickclaw/alexa-ssml/blob/f857e2daa9e4e5d7ed1ff40b78fd56a66d9d228d/src/renderToString.js#L21-L31 |
45,880 | naturalatlas/tilestrata-vtile-raster | index.js | initialize | function initialize(server, callback) {
source = new Backend(server, options);
source.initialize(callback);
} | javascript | function initialize(server, callback) {
source = new Backend(server, options);
source.initialize(callback);
} | [
"function",
"initialize",
"(",
"server",
",",
"callback",
")",
"{",
"source",
"=",
"new",
"Backend",
"(",
"server",
",",
"options",
")",
";",
"source",
".",
"initialize",
"(",
"callback",
")",
";",
"}"
]
| Initializes the mapnik datasource.
@param {TileServer} server
@param {function} callback(err, fn)
@return {void} | [
"Initializes",
"the",
"mapnik",
"datasource",
"."
]
| e97ae82894362023aed05f0391defd434f974aff | https://github.com/naturalatlas/tilestrata-vtile-raster/blob/e97ae82894362023aed05f0391defd434f974aff/index.js#L30-L33 |
45,881 | laurent22/joplin-turndown | src/turndown.js | replacementForNode | function replacementForNode (node) {
var rule = this.rules.forNode(node)
var content = process.call(this, node)
var whitespace = node.flankingWhitespace
if (whitespace.leading || whitespace.trailing) content = content.trim()
return (
whitespace.leading +
rule.replacement(content, node, this.options) +
whitespace.trailing
)
} | javascript | function replacementForNode (node) {
var rule = this.rules.forNode(node)
var content = process.call(this, node)
var whitespace = node.flankingWhitespace
if (whitespace.leading || whitespace.trailing) content = content.trim()
return (
whitespace.leading +
rule.replacement(content, node, this.options) +
whitespace.trailing
)
} | [
"function",
"replacementForNode",
"(",
"node",
")",
"{",
"var",
"rule",
"=",
"this",
".",
"rules",
".",
"forNode",
"(",
"node",
")",
"var",
"content",
"=",
"process",
".",
"call",
"(",
"this",
",",
"node",
")",
"var",
"whitespace",
"=",
"node",
".",
"flankingWhitespace",
"if",
"(",
"whitespace",
".",
"leading",
"||",
"whitespace",
".",
"trailing",
")",
"content",
"=",
"content",
".",
"trim",
"(",
")",
"return",
"(",
"whitespace",
".",
"leading",
"+",
"rule",
".",
"replacement",
"(",
"content",
",",
"node",
",",
"this",
".",
"options",
")",
"+",
"whitespace",
".",
"trailing",
")",
"}"
]
| Converts an element node to its Markdown equivalent
@private
@param {HTMLElement} node The node to convert
@returns A Markdown representation of the node
@type String | [
"Converts",
"an",
"element",
"node",
"to",
"its",
"Markdown",
"equivalent"
]
| 0ef389619b0b70e18e3d679c0fbed088591a3ab2 | https://github.com/laurent22/joplin-turndown/blob/0ef389619b0b70e18e3d679c0fbed088591a3ab2/src/turndown.js#L233-L243 |
45,882 | laurent22/joplin-turndown | src/turndown.js | separatingNewlines | function separatingNewlines (output, replacement) {
var newlines = [
output.match(trailingNewLinesRegExp)[0],
replacement.match(leadingNewLinesRegExp)[0]
].sort()
var maxNewlines = newlines[newlines.length - 1]
return maxNewlines.length < 2 ? maxNewlines : '\n\n'
} | javascript | function separatingNewlines (output, replacement) {
var newlines = [
output.match(trailingNewLinesRegExp)[0],
replacement.match(leadingNewLinesRegExp)[0]
].sort()
var maxNewlines = newlines[newlines.length - 1]
return maxNewlines.length < 2 ? maxNewlines : '\n\n'
} | [
"function",
"separatingNewlines",
"(",
"output",
",",
"replacement",
")",
"{",
"var",
"newlines",
"=",
"[",
"output",
".",
"match",
"(",
"trailingNewLinesRegExp",
")",
"[",
"0",
"]",
",",
"replacement",
".",
"match",
"(",
"leadingNewLinesRegExp",
")",
"[",
"0",
"]",
"]",
".",
"sort",
"(",
")",
"var",
"maxNewlines",
"=",
"newlines",
"[",
"newlines",
".",
"length",
"-",
"1",
"]",
"return",
"maxNewlines",
".",
"length",
"<",
"2",
"?",
"maxNewlines",
":",
"'\\n\\n'",
"}"
]
| Determines the new lines between the current output and the replacement
@private
@param {String} output The current conversion output
@param {String} replacement The string to append to the output
@returns The whitespace to separate the current output and the replacement
@type String | [
"Determines",
"the",
"new",
"lines",
"between",
"the",
"current",
"output",
"and",
"the",
"replacement"
]
| 0ef389619b0b70e18e3d679c0fbed088591a3ab2 | https://github.com/laurent22/joplin-turndown/blob/0ef389619b0b70e18e3d679c0fbed088591a3ab2/src/turndown.js#L254-L261 |
45,883 | mikolalysenko/mesh-geodesic | lib/geodesic.js | quadratic_distance | function quadratic_distance(a, b, c, dpa, dpb, orientation) {
var ab = new Array(3);
var ac = new Array(3);
var dab2 = 0.0;
for(var i=0; i<3; ++i) {
ab[i] = b[i] - a[i];
dab2 += ab[i] * ab[i];
ac[i] = c[i] - a[i];
}
if(dab2 < EPSILON) {
return 1e30;
}
//Transform c into triangle coordinate system
var dab = Math.sqrt(dab2);
var s = 1.0 / dab;
var c0 = 0.0;
for(var i=0; i<3; ++i) {
ab[i] *= s;
c0 += ab[i] * ac[i];
}
var c1 = 0.0;
for(var i=0; i<3; ++i) {
c1 += Math.pow(ac[i] - c0 * ab[i], 2);
}
c1 = Math.sqrt(c1);
//Compute center of distance field
var dpa2 = dpa*dpa;
var dpb2 = dpb*dpb;
var p0 = (dpa2 - dpb2 + dab2) / (2.0 * dab);
var p1 = dpa2 - p0*p0;
if(p1 < 0.0) {
return 1e30;
}
p1 = Math.sqrt(p1);
if(orientation < 0) {
p1 *= -1;
}
//Compute new distance bound
var d = Math.sqrt(Math.pow(c0 - p0, 2) + Math.pow(c1 - p1, 2));
//Return min
return d;
} | javascript | function quadratic_distance(a, b, c, dpa, dpb, orientation) {
var ab = new Array(3);
var ac = new Array(3);
var dab2 = 0.0;
for(var i=0; i<3; ++i) {
ab[i] = b[i] - a[i];
dab2 += ab[i] * ab[i];
ac[i] = c[i] - a[i];
}
if(dab2 < EPSILON) {
return 1e30;
}
//Transform c into triangle coordinate system
var dab = Math.sqrt(dab2);
var s = 1.0 / dab;
var c0 = 0.0;
for(var i=0; i<3; ++i) {
ab[i] *= s;
c0 += ab[i] * ac[i];
}
var c1 = 0.0;
for(var i=0; i<3; ++i) {
c1 += Math.pow(ac[i] - c0 * ab[i], 2);
}
c1 = Math.sqrt(c1);
//Compute center of distance field
var dpa2 = dpa*dpa;
var dpb2 = dpb*dpb;
var p0 = (dpa2 - dpb2 + dab2) / (2.0 * dab);
var p1 = dpa2 - p0*p0;
if(p1 < 0.0) {
return 1e30;
}
p1 = Math.sqrt(p1);
if(orientation < 0) {
p1 *= -1;
}
//Compute new distance bound
var d = Math.sqrt(Math.pow(c0 - p0, 2) + Math.pow(c1 - p1, 2));
//Return min
return d;
} | [
"function",
"quadratic_distance",
"(",
"a",
",",
"b",
",",
"c",
",",
"dpa",
",",
"dpb",
",",
"orientation",
")",
"{",
"var",
"ab",
"=",
"new",
"Array",
"(",
"3",
")",
";",
"var",
"ac",
"=",
"new",
"Array",
"(",
"3",
")",
";",
"var",
"dab2",
"=",
"0.0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"++",
"i",
")",
"{",
"ab",
"[",
"i",
"]",
"=",
"b",
"[",
"i",
"]",
"-",
"a",
"[",
"i",
"]",
";",
"dab2",
"+=",
"ab",
"[",
"i",
"]",
"*",
"ab",
"[",
"i",
"]",
";",
"ac",
"[",
"i",
"]",
"=",
"c",
"[",
"i",
"]",
"-",
"a",
"[",
"i",
"]",
";",
"}",
"if",
"(",
"dab2",
"<",
"EPSILON",
")",
"{",
"return",
"1e30",
";",
"}",
"//Transform c into triangle coordinate system",
"var",
"dab",
"=",
"Math",
".",
"sqrt",
"(",
"dab2",
")",
";",
"var",
"s",
"=",
"1.0",
"/",
"dab",
";",
"var",
"c0",
"=",
"0.0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"++",
"i",
")",
"{",
"ab",
"[",
"i",
"]",
"*=",
"s",
";",
"c0",
"+=",
"ab",
"[",
"i",
"]",
"*",
"ac",
"[",
"i",
"]",
";",
"}",
"var",
"c1",
"=",
"0.0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"++",
"i",
")",
"{",
"c1",
"+=",
"Math",
".",
"pow",
"(",
"ac",
"[",
"i",
"]",
"-",
"c0",
"*",
"ab",
"[",
"i",
"]",
",",
"2",
")",
";",
"}",
"c1",
"=",
"Math",
".",
"sqrt",
"(",
"c1",
")",
";",
"//Compute center of distance field",
"var",
"dpa2",
"=",
"dpa",
"*",
"dpa",
";",
"var",
"dpb2",
"=",
"dpb",
"*",
"dpb",
";",
"var",
"p0",
"=",
"(",
"dpa2",
"-",
"dpb2",
"+",
"dab2",
")",
"/",
"(",
"2.0",
"*",
"dab",
")",
";",
"var",
"p1",
"=",
"dpa2",
"-",
"p0",
"*",
"p0",
";",
"if",
"(",
"p1",
"<",
"0.0",
")",
"{",
"return",
"1e30",
";",
"}",
"p1",
"=",
"Math",
".",
"sqrt",
"(",
"p1",
")",
";",
"if",
"(",
"orientation",
"<",
"0",
")",
"{",
"p1",
"*=",
"-",
"1",
";",
"}",
"//Compute new distance bound",
"var",
"d",
"=",
"Math",
".",
"sqrt",
"(",
"Math",
".",
"pow",
"(",
"c0",
"-",
"p0",
",",
"2",
")",
"+",
"Math",
".",
"pow",
"(",
"c1",
"-",
"p1",
",",
"2",
")",
")",
";",
"//Return min",
"return",
"d",
";",
"}"
]
| Computes quadratic distance to point c | [
"Computes",
"quadratic",
"distance",
"to",
"point",
"c"
]
| 066d741f3b6f890e1c749e14fd42ff9a57294d14 | https://github.com/mikolalysenko/mesh-geodesic/blob/066d741f3b6f890e1c749e14fd42ff9a57294d14/lib/geodesic.js#L7-L54 |
45,884 | mikolalysenko/mesh-geodesic | lib/geodesic.js | geodesic_distance | function geodesic_distance(cells, positions, p, max_distance, tolerance, stars) {
if(typeof(max_distance) === "undefined") {
max_distance = Number.POSITIVE_INFINITY
}
if(typeof(tolerance) === "undefined") {
tolerance = 1e-4
}
if(typeof(dual) === "undefined") {
stars = top.dual(cells, positions.length)
}
//First, run Dijkstra's algorithm to get an initial bound on the distance from each vertex
// to the base point just using edge lengths
var distances = dijkstra(p, stars, cells, positions, max_distance);
//Then refine distances to acceptable threshold
refine_distances(p, distances, positions, stars, cells, max_distance, tolerance);
return distances;
} | javascript | function geodesic_distance(cells, positions, p, max_distance, tolerance, stars) {
if(typeof(max_distance) === "undefined") {
max_distance = Number.POSITIVE_INFINITY
}
if(typeof(tolerance) === "undefined") {
tolerance = 1e-4
}
if(typeof(dual) === "undefined") {
stars = top.dual(cells, positions.length)
}
//First, run Dijkstra's algorithm to get an initial bound on the distance from each vertex
// to the base point just using edge lengths
var distances = dijkstra(p, stars, cells, positions, max_distance);
//Then refine distances to acceptable threshold
refine_distances(p, distances, positions, stars, cells, max_distance, tolerance);
return distances;
} | [
"function",
"geodesic_distance",
"(",
"cells",
",",
"positions",
",",
"p",
",",
"max_distance",
",",
"tolerance",
",",
"stars",
")",
"{",
"if",
"(",
"typeof",
"(",
"max_distance",
")",
"===",
"\"undefined\"",
")",
"{",
"max_distance",
"=",
"Number",
".",
"POSITIVE_INFINITY",
"}",
"if",
"(",
"typeof",
"(",
"tolerance",
")",
"===",
"\"undefined\"",
")",
"{",
"tolerance",
"=",
"1e-4",
"}",
"if",
"(",
"typeof",
"(",
"dual",
")",
"===",
"\"undefined\"",
")",
"{",
"stars",
"=",
"top",
".",
"dual",
"(",
"cells",
",",
"positions",
".",
"length",
")",
"}",
"//First, run Dijkstra's algorithm to get an initial bound on the distance from each vertex",
"// to the base point just using edge lengths",
"var",
"distances",
"=",
"dijkstra",
"(",
"p",
",",
"stars",
",",
"cells",
",",
"positions",
",",
"max_distance",
")",
";",
"//Then refine distances to acceptable threshold",
"refine_distances",
"(",
"p",
",",
"distances",
",",
"positions",
",",
"stars",
",",
"cells",
",",
"max_distance",
",",
"tolerance",
")",
";",
"return",
"distances",
";",
"}"
]
| Computes a distances to a vertex p | [
"Computes",
"a",
"distances",
"to",
"a",
"vertex",
"p"
]
| 066d741f3b6f890e1c749e14fd42ff9a57294d14 | https://github.com/mikolalysenko/mesh-geodesic/blob/066d741f3b6f890e1c749e14fd42ff9a57294d14/lib/geodesic.js#L177-L197 |
45,885 | weexteam/weex-templater | index.js | walk | function walk(node, output, previousNode) {
// tag name
validator.checkTagName(node, output)
// attrs: id/class/style/if/repeat/append/event/attr
var attrs = node.attrs || []
attrs.forEach(function switchAttr(attr) {
var name = attr.name
var value = attr.value
var locationInfo = {line: 1, column: 1}
if (node.__location) {
locationInfo = {
line: node.__location.line,
column: node.__location.col
}
}
switch (name) {
case 'id':
validator.checkId(value, output)
break
case 'class':
validator.checkClass(value, output)
break
case 'style':
validator.checkStyle(value, output, locationInfo)
break
case 'if':
validator.checkIf(value, output)
break
case 'else':
previousNode && previousNode.attrs.forEach(function (attr) {
if (attr.name === 'if') {
validator.checkIf(attr.value, output, true)
}
})
break
case 'repeat':
validator.checkRepeat(value, output)
break
case 'append':
validator.checkAppend(value, output)
break
default:
if (name.match(/^on/)) {
validator.checkEvent(name, value, output)
}
else {
validator.checkAttr(name, value, output, node.tagName, locationInfo)
}
}
})
// children
var originResult = output.result
var childNodes = node.childNodes
if (childNodes && childNodes.length) {
var previous // FIXME: `parse5` has no previous sibling element information
childNodes.forEach(function (child, i) {
if (i > 0) {
previous = childNodes[i - 1]
}
if (child.nodeName.match(/^#/)) {
// special rules for text content in <text>
if (child.nodeName === '#text' && child.value.trim()) {
var tempResult = output.result
output.result = originResult
validator.checkAttr('value', child.value, output)
output.result = tempResult
}
return
}
var childResult = {}
output.result = childResult
originResult.children = originResult.children || []
originResult.children.push(childResult)
walk(child, output, previous)
})
}
output.result = originResult
} | javascript | function walk(node, output, previousNode) {
// tag name
validator.checkTagName(node, output)
// attrs: id/class/style/if/repeat/append/event/attr
var attrs = node.attrs || []
attrs.forEach(function switchAttr(attr) {
var name = attr.name
var value = attr.value
var locationInfo = {line: 1, column: 1}
if (node.__location) {
locationInfo = {
line: node.__location.line,
column: node.__location.col
}
}
switch (name) {
case 'id':
validator.checkId(value, output)
break
case 'class':
validator.checkClass(value, output)
break
case 'style':
validator.checkStyle(value, output, locationInfo)
break
case 'if':
validator.checkIf(value, output)
break
case 'else':
previousNode && previousNode.attrs.forEach(function (attr) {
if (attr.name === 'if') {
validator.checkIf(attr.value, output, true)
}
})
break
case 'repeat':
validator.checkRepeat(value, output)
break
case 'append':
validator.checkAppend(value, output)
break
default:
if (name.match(/^on/)) {
validator.checkEvent(name, value, output)
}
else {
validator.checkAttr(name, value, output, node.tagName, locationInfo)
}
}
})
// children
var originResult = output.result
var childNodes = node.childNodes
if (childNodes && childNodes.length) {
var previous // FIXME: `parse5` has no previous sibling element information
childNodes.forEach(function (child, i) {
if (i > 0) {
previous = childNodes[i - 1]
}
if (child.nodeName.match(/^#/)) {
// special rules for text content in <text>
if (child.nodeName === '#text' && child.value.trim()) {
var tempResult = output.result
output.result = originResult
validator.checkAttr('value', child.value, output)
output.result = tempResult
}
return
}
var childResult = {}
output.result = childResult
originResult.children = originResult.children || []
originResult.children.push(childResult)
walk(child, output, previous)
})
}
output.result = originResult
} | [
"function",
"walk",
"(",
"node",
",",
"output",
",",
"previousNode",
")",
"{",
"// tag name",
"validator",
".",
"checkTagName",
"(",
"node",
",",
"output",
")",
"// attrs: id/class/style/if/repeat/append/event/attr",
"var",
"attrs",
"=",
"node",
".",
"attrs",
"||",
"[",
"]",
"attrs",
".",
"forEach",
"(",
"function",
"switchAttr",
"(",
"attr",
")",
"{",
"var",
"name",
"=",
"attr",
".",
"name",
"var",
"value",
"=",
"attr",
".",
"value",
"var",
"locationInfo",
"=",
"{",
"line",
":",
"1",
",",
"column",
":",
"1",
"}",
"if",
"(",
"node",
".",
"__location",
")",
"{",
"locationInfo",
"=",
"{",
"line",
":",
"node",
".",
"__location",
".",
"line",
",",
"column",
":",
"node",
".",
"__location",
".",
"col",
"}",
"}",
"switch",
"(",
"name",
")",
"{",
"case",
"'id'",
":",
"validator",
".",
"checkId",
"(",
"value",
",",
"output",
")",
"break",
"case",
"'class'",
":",
"validator",
".",
"checkClass",
"(",
"value",
",",
"output",
")",
"break",
"case",
"'style'",
":",
"validator",
".",
"checkStyle",
"(",
"value",
",",
"output",
",",
"locationInfo",
")",
"break",
"case",
"'if'",
":",
"validator",
".",
"checkIf",
"(",
"value",
",",
"output",
")",
"break",
"case",
"'else'",
":",
"previousNode",
"&&",
"previousNode",
".",
"attrs",
".",
"forEach",
"(",
"function",
"(",
"attr",
")",
"{",
"if",
"(",
"attr",
".",
"name",
"===",
"'if'",
")",
"{",
"validator",
".",
"checkIf",
"(",
"attr",
".",
"value",
",",
"output",
",",
"true",
")",
"}",
"}",
")",
"break",
"case",
"'repeat'",
":",
"validator",
".",
"checkRepeat",
"(",
"value",
",",
"output",
")",
"break",
"case",
"'append'",
":",
"validator",
".",
"checkAppend",
"(",
"value",
",",
"output",
")",
"break",
"default",
":",
"if",
"(",
"name",
".",
"match",
"(",
"/",
"^on",
"/",
")",
")",
"{",
"validator",
".",
"checkEvent",
"(",
"name",
",",
"value",
",",
"output",
")",
"}",
"else",
"{",
"validator",
".",
"checkAttr",
"(",
"name",
",",
"value",
",",
"output",
",",
"node",
".",
"tagName",
",",
"locationInfo",
")",
"}",
"}",
"}",
")",
"// children",
"var",
"originResult",
"=",
"output",
".",
"result",
"var",
"childNodes",
"=",
"node",
".",
"childNodes",
"if",
"(",
"childNodes",
"&&",
"childNodes",
".",
"length",
")",
"{",
"var",
"previous",
"// FIXME: `parse5` has no previous sibling element information",
"childNodes",
".",
"forEach",
"(",
"function",
"(",
"child",
",",
"i",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"previous",
"=",
"childNodes",
"[",
"i",
"-",
"1",
"]",
"}",
"if",
"(",
"child",
".",
"nodeName",
".",
"match",
"(",
"/",
"^#",
"/",
")",
")",
"{",
"// special rules for text content in <text>",
"if",
"(",
"child",
".",
"nodeName",
"===",
"'#text'",
"&&",
"child",
".",
"value",
".",
"trim",
"(",
")",
")",
"{",
"var",
"tempResult",
"=",
"output",
".",
"result",
"output",
".",
"result",
"=",
"originResult",
"validator",
".",
"checkAttr",
"(",
"'value'",
",",
"child",
".",
"value",
",",
"output",
")",
"output",
".",
"result",
"=",
"tempResult",
"}",
"return",
"}",
"var",
"childResult",
"=",
"{",
"}",
"output",
".",
"result",
"=",
"childResult",
"originResult",
".",
"children",
"=",
"originResult",
".",
"children",
"||",
"[",
"]",
"originResult",
".",
"children",
".",
"push",
"(",
"childResult",
")",
"walk",
"(",
"child",
",",
"output",
",",
"previous",
")",
"}",
")",
"}",
"output",
".",
"result",
"=",
"originResult",
"}"
]
| walk all nodes
- tag name checking
- attrs checking
- children checking
@param {Node} node
@param {object} output{result, deps[], log[]}
@param {Node} previousNode | [
"walk",
"all",
"nodes",
"-",
"tag",
"name",
"checking",
"-",
"attrs",
"checking",
"-",
"children",
"checking"
]
| 200c1fbeb923b70e304193752fdf1db9802650c7 | https://github.com/weexteam/weex-templater/blob/200c1fbeb923b70e304193752fdf1db9802650c7/index.js#L15-L98 |
45,886 | sjonnet19/mocha-cobertura-reporter | lib/reporters/cobertura.js | Cobertura | function Cobertura(runner) {
var jade = require('jade')
jade.doctypes.cobertura = '<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-03.dtd">'
var file = __dirname + '/templates/cobertura.jade',
str = fs.readFileSync(file, 'utf8'),
fn = jade.compile(str, { filename: file }),
self = this
JSONCov.call(this, runner, false)
runner.on('end',
function(){
self.cov.src = __dirname.split('node_modules')[0]
process.stdout.write(fn({
cov: self.cov
}))
})
} | javascript | function Cobertura(runner) {
var jade = require('jade')
jade.doctypes.cobertura = '<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-03.dtd">'
var file = __dirname + '/templates/cobertura.jade',
str = fs.readFileSync(file, 'utf8'),
fn = jade.compile(str, { filename: file }),
self = this
JSONCov.call(this, runner, false)
runner.on('end',
function(){
self.cov.src = __dirname.split('node_modules')[0]
process.stdout.write(fn({
cov: self.cov
}))
})
} | [
"function",
"Cobertura",
"(",
"runner",
")",
"{",
"var",
"jade",
"=",
"require",
"(",
"'jade'",
")",
"jade",
".",
"doctypes",
".",
"cobertura",
"=",
"'<!DOCTYPE coverage SYSTEM \"http://cobertura.sourceforge.net/xml/coverage-03.dtd\">'",
"var",
"file",
"=",
"__dirname",
"+",
"'/templates/cobertura.jade'",
",",
"str",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"'utf8'",
")",
",",
"fn",
"=",
"jade",
".",
"compile",
"(",
"str",
",",
"{",
"filename",
":",
"file",
"}",
")",
",",
"self",
"=",
"this",
"JSONCov",
".",
"call",
"(",
"this",
",",
"runner",
",",
"false",
")",
"runner",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"self",
".",
"cov",
".",
"src",
"=",
"__dirname",
".",
"split",
"(",
"'node_modules'",
")",
"[",
"0",
"]",
"process",
".",
"stdout",
".",
"write",
"(",
"fn",
"(",
"{",
"cov",
":",
"self",
".",
"cov",
"}",
")",
")",
"}",
")",
"}"
]
| Initialize a new `Cobertura` reporter.
@param {Runner} runner
@api public | [
"Initialize",
"a",
"new",
"Cobertura",
"reporter",
"."
]
| c4f3c2c7820a35e665be42118767f1621f0923d3 | https://github.com/sjonnet19/mocha-cobertura-reporter/blob/c4f3c2c7820a35e665be42118767f1621f0923d3/lib/reporters/cobertura.js#L22-L39 |
45,887 | arve0/deep-reduce | index.js | deepReduce | function deepReduce(obj, reducer, reduced, path, thisArg) {
if (reduced === void 0) { reduced = {}; }
if (path === void 0) { path = ''; }
if (thisArg === void 0) { thisArg = {}; }
var pathArr = path === '' ? [] : path.split('.');
var root = obj; // keep value of root object, for recursion
if (pathArr.length) {
// called with path, traverse to that path
for (var _i = 0, pathArr_1 = pathArr; _i < pathArr_1.length; _i++) {
var key = pathArr_1[_i];
obj = obj[key];
if (obj === undefined) {
throw new Error("Path " + path + " not found in object.");
}
}
}
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
pathArr.push(key);
path = pathArr.join('.');
var value = obj[key];
reduced = reducer.call(thisArg, reduced, value, path, root);
if (typeof value === 'object') {
reduced = deepReduce(root, reducer, reduced, path, thisArg);
}
pathArr.pop();
}
return reduced;
} | javascript | function deepReduce(obj, reducer, reduced, path, thisArg) {
if (reduced === void 0) { reduced = {}; }
if (path === void 0) { path = ''; }
if (thisArg === void 0) { thisArg = {}; }
var pathArr = path === '' ? [] : path.split('.');
var root = obj; // keep value of root object, for recursion
if (pathArr.length) {
// called with path, traverse to that path
for (var _i = 0, pathArr_1 = pathArr; _i < pathArr_1.length; _i++) {
var key = pathArr_1[_i];
obj = obj[key];
if (obj === undefined) {
throw new Error("Path " + path + " not found in object.");
}
}
}
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
pathArr.push(key);
path = pathArr.join('.');
var value = obj[key];
reduced = reducer.call(thisArg, reduced, value, path, root);
if (typeof value === 'object') {
reduced = deepReduce(root, reducer, reduced, path, thisArg);
}
pathArr.pop();
}
return reduced;
} | [
"function",
"deepReduce",
"(",
"obj",
",",
"reducer",
",",
"reduced",
",",
"path",
",",
"thisArg",
")",
"{",
"if",
"(",
"reduced",
"===",
"void",
"0",
")",
"{",
"reduced",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"path",
"===",
"void",
"0",
")",
"{",
"path",
"=",
"''",
";",
"}",
"if",
"(",
"thisArg",
"===",
"void",
"0",
")",
"{",
"thisArg",
"=",
"{",
"}",
";",
"}",
"var",
"pathArr",
"=",
"path",
"===",
"''",
"?",
"[",
"]",
":",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"root",
"=",
"obj",
";",
"// keep value of root object, for recursion",
"if",
"(",
"pathArr",
".",
"length",
")",
"{",
"// called with path, traverse to that path",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"pathArr_1",
"=",
"pathArr",
";",
"_i",
"<",
"pathArr_1",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"key",
"=",
"pathArr_1",
"[",
"_i",
"]",
";",
"obj",
"=",
"obj",
"[",
"key",
"]",
";",
"if",
"(",
"obj",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Path \"",
"+",
"path",
"+",
"\" not found in object.\"",
")",
";",
"}",
"}",
"}",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"pathArr",
".",
"push",
"(",
"key",
")",
";",
"path",
"=",
"pathArr",
".",
"join",
"(",
"'.'",
")",
";",
"var",
"value",
"=",
"obj",
"[",
"key",
"]",
";",
"reduced",
"=",
"reducer",
".",
"call",
"(",
"thisArg",
",",
"reduced",
",",
"value",
",",
"path",
",",
"root",
")",
";",
"if",
"(",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"reduced",
"=",
"deepReduce",
"(",
"root",
",",
"reducer",
",",
"reduced",
",",
"path",
",",
"thisArg",
")",
";",
"}",
"pathArr",
".",
"pop",
"(",
")",
";",
"}",
"return",
"reduced",
";",
"}"
]
| Reduce objects deeply, like Array.prototype.reduce but for objects.
@param obj Object to traverse.
@param reducer Reducer function.
@param reduced Initial accumulated value.
@param path Root of traversal.
@param thisArg Binds `thisArg` as `this` on `reducer`.
@returns Accumulated value. | [
"Reduce",
"objects",
"deeply",
"like",
"Array",
".",
"prototype",
".",
"reduce",
"but",
"for",
"objects",
"."
]
| 375e1058b61671656dc602b2b58d742fe9dd95a2 | https://github.com/arve0/deep-reduce/blob/375e1058b61671656dc602b2b58d742fe9dd95a2/index.js#L12-L42 |
45,888 | dkozar/raycast-dom | build/lookup/evaluateID.js | evaluateID | function evaluateID(sub, element) {
var id = element.id;
return id && id.indexOf(sub) === 0;
} | javascript | function evaluateID(sub, element) {
var id = element.id;
return id && id.indexOf(sub) === 0;
} | [
"function",
"evaluateID",
"(",
"sub",
",",
"element",
")",
"{",
"var",
"id",
"=",
"element",
".",
"id",
";",
"return",
"id",
"&&",
"id",
".",
"indexOf",
"(",
"sub",
")",
"===",
"0",
";",
"}"
]
| Checks whether the substring is present within element ID
@param sub Substring to check for
@param element DOM element
@returns {*|boolean} | [
"Checks",
"whether",
"the",
"substring",
"is",
"present",
"within",
"element",
"ID"
]
| 91eb7ad1fbc4c91f8f3ccca69a33e1083f6d5d98 | https://github.com/dkozar/raycast-dom/blob/91eb7ad1fbc4c91f8f3ccca69a33e1083f6d5d98/build/lookup/evaluateID.js#L13-L17 |
45,889 | gaurav-nelson/retext-google-styleguide | index.js | removeA | function removeA(arr) {
var what,
a = arguments,
L = a.length,
ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax = arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
} | javascript | function removeA(arr) {
var what,
a = arguments,
L = a.length,
ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax = arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
} | [
"function",
"removeA",
"(",
"arr",
")",
"{",
"var",
"what",
",",
"a",
"=",
"arguments",
",",
"L",
"=",
"a",
".",
"length",
",",
"ax",
";",
"while",
"(",
"L",
">",
"1",
"&&",
"arr",
".",
"length",
")",
"{",
"what",
"=",
"a",
"[",
"--",
"L",
"]",
";",
"while",
"(",
"(",
"ax",
"=",
"arr",
".",
"indexOf",
"(",
"what",
")",
")",
"!==",
"-",
"1",
")",
"{",
"arr",
".",
"splice",
"(",
"ax",
",",
"1",
")",
";",
"}",
"}",
"return",
"arr",
";",
"}"
]
| to remove passed values from the array, used to find and remove empty vlaues | [
"to",
"remove",
"passed",
"values",
"from",
"the",
"array",
"used",
"to",
"find",
"and",
"remove",
"empty",
"vlaues"
]
| 9c601b11e2c4bed57376b78566bad26ecbbeadca | https://github.com/gaurav-nelson/retext-google-styleguide/blob/9c601b11e2c4bed57376b78566bad26ecbbeadca/index.js#L28-L40 |
45,890 | gaurav-nelson/retext-google-styleguide | index.js | countWords | function countWords(s) {
s = s.replace(/(^\s*)|(\s*$)/gi, ""); //exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, " "); //2 or more space to 1
s = s.replace(/\n /, "\n"); // exclude newline with a start spacing
return s.split(" ").length;
} | javascript | function countWords(s) {
s = s.replace(/(^\s*)|(\s*$)/gi, ""); //exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, " "); //2 or more space to 1
s = s.replace(/\n /, "\n"); // exclude newline with a start spacing
return s.split(" ").length;
} | [
"function",
"countWords",
"(",
"s",
")",
"{",
"s",
"=",
"s",
".",
"replace",
"(",
"/",
"(^\\s*)|(\\s*$)",
"/",
"gi",
",",
"\"\"",
")",
";",
"//exclude start and end white-space",
"s",
"=",
"s",
".",
"replace",
"(",
"/",
"[ ]{2,}",
"/",
"gi",
",",
"\" \"",
")",
";",
"//2 or more space to 1",
"s",
"=",
"s",
".",
"replace",
"(",
"/",
"\\n ",
"/",
",",
"\"\\n\"",
")",
";",
"// exclude newline with a start spacing",
"return",
"s",
".",
"split",
"(",
"\" \"",
")",
".",
"length",
";",
"}"
]
| to check number of words in an array | [
"to",
"check",
"number",
"of",
"words",
"in",
"an",
"array"
]
| 9c601b11e2c4bed57376b78566bad26ecbbeadca | https://github.com/gaurav-nelson/retext-google-styleguide/blob/9c601b11e2c4bed57376b78566bad26ecbbeadca/index.js#L43-L48 |
45,891 | gaurav-nelson/retext-google-styleguide | index.js | function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if (!findNaN && typeof Array.prototype.indexOf === "function") {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1,
index = -1;
for (i = 0; i < this.length; i++) {
var item = this[i];
if ((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
} | javascript | function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if (!findNaN && typeof Array.prototype.indexOf === "function") {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1,
index = -1;
for (i = 0; i < this.length; i++) {
var item = this[i];
if ((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
} | [
"function",
"(",
"needle",
")",
"{",
"// Per spec, the way to identify NaN is that it is not equal to itself",
"var",
"findNaN",
"=",
"needle",
"!==",
"needle",
";",
"var",
"indexOf",
";",
"if",
"(",
"!",
"findNaN",
"&&",
"typeof",
"Array",
".",
"prototype",
".",
"indexOf",
"===",
"\"function\"",
")",
"{",
"indexOf",
"=",
"Array",
".",
"prototype",
".",
"indexOf",
";",
"}",
"else",
"{",
"indexOf",
"=",
"function",
"(",
"needle",
")",
"{",
"var",
"i",
"=",
"-",
"1",
",",
"index",
"=",
"-",
"1",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"item",
"=",
"this",
"[",
"i",
"]",
";",
"if",
"(",
"(",
"findNaN",
"&&",
"item",
"!==",
"item",
")",
"||",
"item",
"===",
"needle",
")",
"{",
"index",
"=",
"i",
";",
"break",
";",
"}",
"}",
"return",
"index",
";",
"}",
";",
"}",
"return",
"indexOf",
".",
"call",
"(",
"this",
",",
"needle",
")",
">",
"-",
"1",
";",
"}"
]
| to check if all values in the array are same | [
"to",
"check",
"if",
"all",
"values",
"in",
"the",
"array",
"are",
"same"
]
| 9c601b11e2c4bed57376b78566bad26ecbbeadca | https://github.com/gaurav-nelson/retext-google-styleguide/blob/9c601b11e2c4bed57376b78566bad26ecbbeadca/index.js#L51-L77 |
|
45,892 | tdreyno/morlock.js | controllers/breakpoint-controller.js | BreakpointController | function BreakpointController(options) {
if (!(this instanceof BreakpointController)) {
return new BreakpointController(options);
}
Emitter.mixin(this);
var breakpointStream = BreakpointStream.create(options.breakpoints, {
throttleMs: options.throttleMs,
debounceMs: options.debounceMs
});
var activeBreakpoints = {};
var self = this;
Stream.onValue(breakpointStream, function(e) {
activeBreakpoints[e[0]] = e[1];
var namedState = e[1] ? 'enter' : 'exit';
self.trigger('breakpoint', [e[0], namedState]);
self.trigger('breakpoint:' + e[0], [e[0], namedState]);
});
this.getActiveBreakpoints = function getActiveBreakpoints() {
var isActive = Util.compose(Util.isTrue, Util.get(activeBreakpoints));
return Util.select(isActive, Util.objectKeys(activeBreakpoints));
};
} | javascript | function BreakpointController(options) {
if (!(this instanceof BreakpointController)) {
return new BreakpointController(options);
}
Emitter.mixin(this);
var breakpointStream = BreakpointStream.create(options.breakpoints, {
throttleMs: options.throttleMs,
debounceMs: options.debounceMs
});
var activeBreakpoints = {};
var self = this;
Stream.onValue(breakpointStream, function(e) {
activeBreakpoints[e[0]] = e[1];
var namedState = e[1] ? 'enter' : 'exit';
self.trigger('breakpoint', [e[0], namedState]);
self.trigger('breakpoint:' + e[0], [e[0], namedState]);
});
this.getActiveBreakpoints = function getActiveBreakpoints() {
var isActive = Util.compose(Util.isTrue, Util.get(activeBreakpoints));
return Util.select(isActive, Util.objectKeys(activeBreakpoints));
};
} | [
"function",
"BreakpointController",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"BreakpointController",
")",
")",
"{",
"return",
"new",
"BreakpointController",
"(",
"options",
")",
";",
"}",
"Emitter",
".",
"mixin",
"(",
"this",
")",
";",
"var",
"breakpointStream",
"=",
"BreakpointStream",
".",
"create",
"(",
"options",
".",
"breakpoints",
",",
"{",
"throttleMs",
":",
"options",
".",
"throttleMs",
",",
"debounceMs",
":",
"options",
".",
"debounceMs",
"}",
")",
";",
"var",
"activeBreakpoints",
"=",
"{",
"}",
";",
"var",
"self",
"=",
"this",
";",
"Stream",
".",
"onValue",
"(",
"breakpointStream",
",",
"function",
"(",
"e",
")",
"{",
"activeBreakpoints",
"[",
"e",
"[",
"0",
"]",
"]",
"=",
"e",
"[",
"1",
"]",
";",
"var",
"namedState",
"=",
"e",
"[",
"1",
"]",
"?",
"'enter'",
":",
"'exit'",
";",
"self",
".",
"trigger",
"(",
"'breakpoint'",
",",
"[",
"e",
"[",
"0",
"]",
",",
"namedState",
"]",
")",
";",
"self",
".",
"trigger",
"(",
"'breakpoint:'",
"+",
"e",
"[",
"0",
"]",
",",
"[",
"e",
"[",
"0",
"]",
",",
"namedState",
"]",
")",
";",
"}",
")",
";",
"this",
".",
"getActiveBreakpoints",
"=",
"function",
"getActiveBreakpoints",
"(",
")",
"{",
"var",
"isActive",
"=",
"Util",
".",
"compose",
"(",
"Util",
".",
"isTrue",
",",
"Util",
".",
"get",
"(",
"activeBreakpoints",
")",
")",
";",
"return",
"Util",
".",
"select",
"(",
"isActive",
",",
"Util",
".",
"objectKeys",
"(",
"activeBreakpoints",
")",
")",
";",
"}",
";",
"}"
]
| Provides a familiar OO-style API for tracking breakpoint events.
@constructor
@param {Object=} options The options passed to the breakpoint tracker.
@return {Object} The API with a `on` function to attach callbacks
to breakpoint changes. | [
"Provides",
"a",
"familiar",
"OO",
"-",
"style",
"API",
"for",
"tracking",
"breakpoint",
"events",
"."
]
| a1d3f1f177887485b084aa38c91189fd9f9cfedf | https://github.com/tdreyno/morlock.js/blob/a1d3f1f177887485b084aa38c91189fd9f9cfedf/controllers/breakpoint-controller.js#L13-L40 |
45,893 | mosaicjs/Leaflet.CanvasDataGrid | src/data/GridIndex.js | function(x, y) {
var array = this.getAllData(x, y);
return array && array.length ? array[0] : undefined;
} | javascript | function(x, y) {
var array = this.getAllData(x, y);
return array && array.length ? array[0] : undefined;
} | [
"function",
"(",
"x",
",",
"y",
")",
"{",
"var",
"array",
"=",
"this",
".",
"getAllData",
"(",
"x",
",",
"y",
")",
";",
"return",
"array",
"&&",
"array",
".",
"length",
"?",
"array",
"[",
"0",
"]",
":",
"undefined",
";",
"}"
]
| Returns data associated with the specified position on the canvas. | [
"Returns",
"data",
"associated",
"with",
"the",
"specified",
"position",
"on",
"the",
"canvas",
"."
]
| ebf193b12c390ef2b00b6faa2be878751d0b1fc3 | https://github.com/mosaicjs/Leaflet.CanvasDataGrid/blob/ebf193b12c390ef2b00b6faa2be878751d0b1fc3/src/data/GridIndex.js#L19-L22 |
|
45,894 | mosaicjs/Leaflet.CanvasDataGrid | src/data/GridIndex.js | function(x, y) {
var maskX = this._getMaskX(x);
var maskY = this._getMaskY(y);
var key = this._getIndexKey(maskX, maskY);
return this._dataIndex[key];
} | javascript | function(x, y) {
var maskX = this._getMaskX(x);
var maskY = this._getMaskY(y);
var key = this._getIndexKey(maskX, maskY);
return this._dataIndex[key];
} | [
"function",
"(",
"x",
",",
"y",
")",
"{",
"var",
"maskX",
"=",
"this",
".",
"_getMaskX",
"(",
"x",
")",
";",
"var",
"maskY",
"=",
"this",
".",
"_getMaskY",
"(",
"y",
")",
";",
"var",
"key",
"=",
"this",
".",
"_getIndexKey",
"(",
"maskX",
",",
"maskY",
")",
";",
"return",
"this",
".",
"_dataIndex",
"[",
"key",
"]",
";",
"}"
]
| Returns all data objects associated with the specified position on the
canvas. | [
"Returns",
"all",
"data",
"objects",
"associated",
"with",
"the",
"specified",
"position",
"on",
"the",
"canvas",
"."
]
| ebf193b12c390ef2b00b6faa2be878751d0b1fc3 | https://github.com/mosaicjs/Leaflet.CanvasDataGrid/blob/ebf193b12c390ef2b00b6faa2be878751d0b1fc3/src/data/GridIndex.js#L28-L33 |
|
45,895 | mosaicjs/Leaflet.CanvasDataGrid | src/data/GridIndex.js | function(x, y, options) {
var maskX = this._getMaskX(x);
var maskY = this._getMaskY(y);
var key = this._getIndexKey(maskX, maskY);
return this._addDataToIndex(key, options);
} | javascript | function(x, y, options) {
var maskX = this._getMaskX(x);
var maskY = this._getMaskY(y);
var key = this._getIndexKey(maskX, maskY);
return this._addDataToIndex(key, options);
} | [
"function",
"(",
"x",
",",
"y",
",",
"options",
")",
"{",
"var",
"maskX",
"=",
"this",
".",
"_getMaskX",
"(",
"x",
")",
";",
"var",
"maskY",
"=",
"this",
".",
"_getMaskY",
"(",
"y",
")",
";",
"var",
"key",
"=",
"this",
".",
"_getIndexKey",
"(",
"maskX",
",",
"maskY",
")",
";",
"return",
"this",
".",
"_addDataToIndex",
"(",
"key",
",",
"options",
")",
";",
"}"
]
| Sets data in the specified position on the canvas.
@param x
@param y
@param options.data
a data object to set | [
"Sets",
"data",
"in",
"the",
"specified",
"position",
"on",
"the",
"canvas",
"."
]
| ebf193b12c390ef2b00b6faa2be878751d0b1fc3 | https://github.com/mosaicjs/Leaflet.CanvasDataGrid/blob/ebf193b12c390ef2b00b6faa2be878751d0b1fc3/src/data/GridIndex.js#L43-L48 |
|
45,896 | dkozar/raycast-dom | build/lookup/evaluateReactID.js | evaluateReactID | function evaluateReactID(sub, element) {
var id = element.getAttribute && element.getAttribute('data-reactid');
return id && id.indexOf(sub) > -1;
} | javascript | function evaluateReactID(sub, element) {
var id = element.getAttribute && element.getAttribute('data-reactid');
return id && id.indexOf(sub) > -1;
} | [
"function",
"evaluateReactID",
"(",
"sub",
",",
"element",
")",
"{",
"var",
"id",
"=",
"element",
".",
"getAttribute",
"&&",
"element",
".",
"getAttribute",
"(",
"'data-reactid'",
")",
";",
"return",
"id",
"&&",
"id",
".",
"indexOf",
"(",
"sub",
")",
">",
"-",
"1",
";",
"}"
]
| Checks whether the substring is present within element's React ID
@param sub Substring to check for
@param element DOM element
@returns {*|boolean} | [
"Checks",
"whether",
"the",
"substring",
"is",
"present",
"within",
"element",
"s",
"React",
"ID"
]
| 91eb7ad1fbc4c91f8f3ccca69a33e1083f6d5d98 | https://github.com/dkozar/raycast-dom/blob/91eb7ad1fbc4c91f8f3ccca69a33e1083f6d5d98/build/lookup/evaluateReactID.js#L13-L17 |
45,897 | weexteam/weex-templater | lib/validator.js | checkTagName | function checkTagName(node, output) {
var result = output.result
var deps = output.deps
var log = output.log
var tagName = node.tagName
var childNodes = node.childNodes || []
var location = node.__location || {}
// alias
if (TAG_NAME_ALIAS_MAP[tagName]) {
if (tagName !== 'img') { // FIXME: `parse5` autofixes image to img silently
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'NOTE: tag name `' + tagName + '` is autofixed to `' + TAG_NAME_ALIAS_MAP[tagName] + '`'
})
}
tagName = TAG_NAME_ALIAS_MAP[tagName]
}
if (tagName === 'component') {
var indexOfIs = -1
if (node.attrs) {
node.attrs.forEach(function (attr, index) {
if (attr.name === 'is') {
indexOfIs = index
result.type = tagName = exp(attr.value)
}
})
}
if (indexOfIs > -1) {
node.attrs.splice(indexOfIs, 1) // delete `is`
}
else {
result.type = tagName = 'container'
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'WARNING: tag `component` should have an `is` attribute, otherwise it will be regarded as a `container`'
})
}
}
else {
result.type = tagName
}
// deps
if (deps.indexOf(tagName) < 0 && typeof tagName === 'string') { // FIXME: improve `require` to bundle dynamic binding components
deps.push(tagName)
}
// parent (no any rules yet)
// child (noChild, textContent)
if (NO_CHILD_TAG_NAME_LIST.indexOf(tagName) >= 0) {
if (childNodes.length > 0) {
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'ERROR: tag `' + tagName + '` should not have children'
})
}
}
if (TEXT_CONTENT_TAG_NAME_LIST.indexOf(tagName) >= 0) {
if (childNodes.length > 1 || (childNodes[0] && childNodes[0].nodeName !== '#text')) {
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'ERROR: tag name `' + tagName + '` should just have one text node only'
})
}
}
// default attr
if (TAG_DEFAULT_ATTR_MAP[tagName]) {
Object.keys(TAG_DEFAULT_ATTR_MAP[tagName]).forEach(function (attr) {
if (attr !== 'append') {
result.attr = result.attr || {}
result.attr[attr] = TAG_DEFAULT_ATTR_MAP[tagName][attr]
}
else {
result[attr] = TAG_DEFAULT_ATTR_MAP[tagName][attr]
}
})
}
} | javascript | function checkTagName(node, output) {
var result = output.result
var deps = output.deps
var log = output.log
var tagName = node.tagName
var childNodes = node.childNodes || []
var location = node.__location || {}
// alias
if (TAG_NAME_ALIAS_MAP[tagName]) {
if (tagName !== 'img') { // FIXME: `parse5` autofixes image to img silently
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'NOTE: tag name `' + tagName + '` is autofixed to `' + TAG_NAME_ALIAS_MAP[tagName] + '`'
})
}
tagName = TAG_NAME_ALIAS_MAP[tagName]
}
if (tagName === 'component') {
var indexOfIs = -1
if (node.attrs) {
node.attrs.forEach(function (attr, index) {
if (attr.name === 'is') {
indexOfIs = index
result.type = tagName = exp(attr.value)
}
})
}
if (indexOfIs > -1) {
node.attrs.splice(indexOfIs, 1) // delete `is`
}
else {
result.type = tagName = 'container'
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'WARNING: tag `component` should have an `is` attribute, otherwise it will be regarded as a `container`'
})
}
}
else {
result.type = tagName
}
// deps
if (deps.indexOf(tagName) < 0 && typeof tagName === 'string') { // FIXME: improve `require` to bundle dynamic binding components
deps.push(tagName)
}
// parent (no any rules yet)
// child (noChild, textContent)
if (NO_CHILD_TAG_NAME_LIST.indexOf(tagName) >= 0) {
if (childNodes.length > 0) {
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'ERROR: tag `' + tagName + '` should not have children'
})
}
}
if (TEXT_CONTENT_TAG_NAME_LIST.indexOf(tagName) >= 0) {
if (childNodes.length > 1 || (childNodes[0] && childNodes[0].nodeName !== '#text')) {
log.push({
line: location.line || 1,
column: location.col || 1,
reason: 'ERROR: tag name `' + tagName + '` should just have one text node only'
})
}
}
// default attr
if (TAG_DEFAULT_ATTR_MAP[tagName]) {
Object.keys(TAG_DEFAULT_ATTR_MAP[tagName]).forEach(function (attr) {
if (attr !== 'append') {
result.attr = result.attr || {}
result.attr[attr] = TAG_DEFAULT_ATTR_MAP[tagName][attr]
}
else {
result[attr] = TAG_DEFAULT_ATTR_MAP[tagName][attr]
}
})
}
} | [
"function",
"checkTagName",
"(",
"node",
",",
"output",
")",
"{",
"var",
"result",
"=",
"output",
".",
"result",
"var",
"deps",
"=",
"output",
".",
"deps",
"var",
"log",
"=",
"output",
".",
"log",
"var",
"tagName",
"=",
"node",
".",
"tagName",
"var",
"childNodes",
"=",
"node",
".",
"childNodes",
"||",
"[",
"]",
"var",
"location",
"=",
"node",
".",
"__location",
"||",
"{",
"}",
"// alias",
"if",
"(",
"TAG_NAME_ALIAS_MAP",
"[",
"tagName",
"]",
")",
"{",
"if",
"(",
"tagName",
"!==",
"'img'",
")",
"{",
"// FIXME: `parse5` autofixes image to img silently",
"log",
".",
"push",
"(",
"{",
"line",
":",
"location",
".",
"line",
"||",
"1",
",",
"column",
":",
"location",
".",
"col",
"||",
"1",
",",
"reason",
":",
"'NOTE: tag name `'",
"+",
"tagName",
"+",
"'` is autofixed to `'",
"+",
"TAG_NAME_ALIAS_MAP",
"[",
"tagName",
"]",
"+",
"'`'",
"}",
")",
"}",
"tagName",
"=",
"TAG_NAME_ALIAS_MAP",
"[",
"tagName",
"]",
"}",
"if",
"(",
"tagName",
"===",
"'component'",
")",
"{",
"var",
"indexOfIs",
"=",
"-",
"1",
"if",
"(",
"node",
".",
"attrs",
")",
"{",
"node",
".",
"attrs",
".",
"forEach",
"(",
"function",
"(",
"attr",
",",
"index",
")",
"{",
"if",
"(",
"attr",
".",
"name",
"===",
"'is'",
")",
"{",
"indexOfIs",
"=",
"index",
"result",
".",
"type",
"=",
"tagName",
"=",
"exp",
"(",
"attr",
".",
"value",
")",
"}",
"}",
")",
"}",
"if",
"(",
"indexOfIs",
">",
"-",
"1",
")",
"{",
"node",
".",
"attrs",
".",
"splice",
"(",
"indexOfIs",
",",
"1",
")",
"// delete `is`",
"}",
"else",
"{",
"result",
".",
"type",
"=",
"tagName",
"=",
"'container'",
"log",
".",
"push",
"(",
"{",
"line",
":",
"location",
".",
"line",
"||",
"1",
",",
"column",
":",
"location",
".",
"col",
"||",
"1",
",",
"reason",
":",
"'WARNING: tag `component` should have an `is` attribute, otherwise it will be regarded as a `container`'",
"}",
")",
"}",
"}",
"else",
"{",
"result",
".",
"type",
"=",
"tagName",
"}",
"// deps",
"if",
"(",
"deps",
".",
"indexOf",
"(",
"tagName",
")",
"<",
"0",
"&&",
"typeof",
"tagName",
"===",
"'string'",
")",
"{",
"// FIXME: improve `require` to bundle dynamic binding components",
"deps",
".",
"push",
"(",
"tagName",
")",
"}",
"// parent (no any rules yet)",
"// child (noChild, textContent)",
"if",
"(",
"NO_CHILD_TAG_NAME_LIST",
".",
"indexOf",
"(",
"tagName",
")",
">=",
"0",
")",
"{",
"if",
"(",
"childNodes",
".",
"length",
">",
"0",
")",
"{",
"log",
".",
"push",
"(",
"{",
"line",
":",
"location",
".",
"line",
"||",
"1",
",",
"column",
":",
"location",
".",
"col",
"||",
"1",
",",
"reason",
":",
"'ERROR: tag `'",
"+",
"tagName",
"+",
"'` should not have children'",
"}",
")",
"}",
"}",
"if",
"(",
"TEXT_CONTENT_TAG_NAME_LIST",
".",
"indexOf",
"(",
"tagName",
")",
">=",
"0",
")",
"{",
"if",
"(",
"childNodes",
".",
"length",
">",
"1",
"||",
"(",
"childNodes",
"[",
"0",
"]",
"&&",
"childNodes",
"[",
"0",
"]",
".",
"nodeName",
"!==",
"'#text'",
")",
")",
"{",
"log",
".",
"push",
"(",
"{",
"line",
":",
"location",
".",
"line",
"||",
"1",
",",
"column",
":",
"location",
".",
"col",
"||",
"1",
",",
"reason",
":",
"'ERROR: tag name `'",
"+",
"tagName",
"+",
"'` should just have one text node only'",
"}",
")",
"}",
"}",
"// default attr",
"if",
"(",
"TAG_DEFAULT_ATTR_MAP",
"[",
"tagName",
"]",
")",
"{",
"Object",
".",
"keys",
"(",
"TAG_DEFAULT_ATTR_MAP",
"[",
"tagName",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"attr",
")",
"{",
"if",
"(",
"attr",
"!==",
"'append'",
")",
"{",
"result",
".",
"attr",
"=",
"result",
".",
"attr",
"||",
"{",
"}",
"result",
".",
"attr",
"[",
"attr",
"]",
"=",
"TAG_DEFAULT_ATTR_MAP",
"[",
"tagName",
"]",
"[",
"attr",
"]",
"}",
"else",
"{",
"result",
"[",
"attr",
"]",
"=",
"TAG_DEFAULT_ATTR_MAP",
"[",
"tagName",
"]",
"[",
"attr",
"]",
"}",
"}",
")",
"}",
"}"
]
| tag name checking
- autofix alias
- append deps
- check parent requirements
- check children requirements
and the result, deps, log will be updated
@param {Node} node
@param {object} output{result, deps[], log[]} | [
"tag",
"name",
"checking",
"-",
"autofix",
"alias",
"-",
"append",
"deps",
"-",
"check",
"parent",
"requirements",
"-",
"check",
"children",
"requirements",
"and",
"the",
"result",
"deps",
"log",
"will",
"be",
"updated"
]
| 200c1fbeb923b70e304193752fdf1db9802650c7 | https://github.com/weexteam/weex-templater/blob/200c1fbeb923b70e304193752fdf1db9802650c7/lib/validator.js#L99-L185 |
45,898 | crcn/emailify | lib/index.js | _parse | function _parse(content, options, callback) {
if(typeof options == 'function') {
callback = options;
options.test = false;
}
var on = outcome.error(callback),
warnings,
window;
step(
/**
* load it.
*/
function() {
jsdom.env({
html: content,
scripts: [
__dirname + "/jquery-1.5.js"
],
done: this
});
},
/**
* set it.
*/
on.success(function(win) {
window = win;
_copyStyles(window);
this();
}),
/**
* test it.
*/
on.success(function() {
if(!options.test) {
return this();
}
test(window, {}, this);
}),
/**
* clean it.
*/
on.success(function(warn) {
warnings = warn;
//strip stuff that cannot be processed
window.$('script, link, style').remove();
if (!options.comments) {
//strip comments - sometimes gets rendered
window.$('*').contents().each(function(node) {
if(this.nodeType == 8) {
window.$(this).remove();
}
});
}
this();
}),
/**
* finish it.
*/
function() {
callback(null, window.document.documentElement.innerHTML, warnings || []);
}
);
} | javascript | function _parse(content, options, callback) {
if(typeof options == 'function') {
callback = options;
options.test = false;
}
var on = outcome.error(callback),
warnings,
window;
step(
/**
* load it.
*/
function() {
jsdom.env({
html: content,
scripts: [
__dirname + "/jquery-1.5.js"
],
done: this
});
},
/**
* set it.
*/
on.success(function(win) {
window = win;
_copyStyles(window);
this();
}),
/**
* test it.
*/
on.success(function() {
if(!options.test) {
return this();
}
test(window, {}, this);
}),
/**
* clean it.
*/
on.success(function(warn) {
warnings = warn;
//strip stuff that cannot be processed
window.$('script, link, style').remove();
if (!options.comments) {
//strip comments - sometimes gets rendered
window.$('*').contents().each(function(node) {
if(this.nodeType == 8) {
window.$(this).remove();
}
});
}
this();
}),
/**
* finish it.
*/
function() {
callback(null, window.document.documentElement.innerHTML, warnings || []);
}
);
} | [
"function",
"_parse",
"(",
"content",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"options",
".",
"test",
"=",
"false",
";",
"}",
"var",
"on",
"=",
"outcome",
".",
"error",
"(",
"callback",
")",
",",
"warnings",
",",
"window",
";",
"step",
"(",
"/**\n\t\t * load it.\n\t\t */",
"function",
"(",
")",
"{",
"jsdom",
".",
"env",
"(",
"{",
"html",
":",
"content",
",",
"scripts",
":",
"[",
"__dirname",
"+",
"\"/jquery-1.5.js\"",
"]",
",",
"done",
":",
"this",
"}",
")",
";",
"}",
",",
"/**\n\t\t * set it.\n\t\t */",
"on",
".",
"success",
"(",
"function",
"(",
"win",
")",
"{",
"window",
"=",
"win",
";",
"_copyStyles",
"(",
"window",
")",
";",
"this",
"(",
")",
";",
"}",
")",
",",
"/**\n\t\t * test it.\n\t\t */",
"on",
".",
"success",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"options",
".",
"test",
")",
"{",
"return",
"this",
"(",
")",
";",
"}",
"test",
"(",
"window",
",",
"{",
"}",
",",
"this",
")",
";",
"}",
")",
",",
"/**\n\t\t * clean it.\n\t\t */",
"on",
".",
"success",
"(",
"function",
"(",
"warn",
")",
"{",
"warnings",
"=",
"warn",
";",
"//strip stuff that cannot be processed",
"window",
".",
"$",
"(",
"'script, link, style'",
")",
".",
"remove",
"(",
")",
";",
"if",
"(",
"!",
"options",
".",
"comments",
")",
"{",
"//strip comments - sometimes gets rendered",
"window",
".",
"$",
"(",
"'*'",
")",
".",
"contents",
"(",
")",
".",
"each",
"(",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"this",
".",
"nodeType",
"==",
"8",
")",
"{",
"window",
".",
"$",
"(",
"this",
")",
".",
"remove",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"this",
"(",
")",
";",
"}",
")",
",",
"/**\n\t\t * finish it.\n\t\t */",
"function",
"(",
")",
"{",
"callback",
"(",
"null",
",",
"window",
".",
"document",
".",
"documentElement",
".",
"innerHTML",
",",
"warnings",
"||",
"[",
"]",
")",
";",
"}",
")",
";",
"}"
]
| parses content into email-safe HTML | [
"parses",
"content",
"into",
"email",
"-",
"safe",
"HTML"
]
| 9ef187d60828ce393195396e87326fdceb1d1d57 | https://github.com/crcn/emailify/blob/9ef187d60828ce393195396e87326fdceb1d1d57/lib/index.js#L30-L129 |
45,899 | tdreyno/morlock.js | core/stream.js | attachListener_ | function attachListener_() {
if (isListening) { return; }
isListening = true;
unsubFunc = Events.eventListener(target, eventName, function() {
if (outputStream.closed) {
detachListener_();
} else {
Util.apply(boundEmit, arguments);
}
});
onClose(outputStream, detachListener_);
} | javascript | function attachListener_() {
if (isListening) { return; }
isListening = true;
unsubFunc = Events.eventListener(target, eventName, function() {
if (outputStream.closed) {
detachListener_();
} else {
Util.apply(boundEmit, arguments);
}
});
onClose(outputStream, detachListener_);
} | [
"function",
"attachListener_",
"(",
")",
"{",
"if",
"(",
"isListening",
")",
"{",
"return",
";",
"}",
"isListening",
"=",
"true",
";",
"unsubFunc",
"=",
"Events",
".",
"eventListener",
"(",
"target",
",",
"eventName",
",",
"function",
"(",
")",
"{",
"if",
"(",
"outputStream",
".",
"closed",
")",
"{",
"detachListener_",
"(",
")",
";",
"}",
"else",
"{",
"Util",
".",
"apply",
"(",
"boundEmit",
",",
"arguments",
")",
";",
"}",
"}",
")",
";",
"onClose",
"(",
"outputStream",
",",
"detachListener_",
")",
";",
"}"
]
| Lazily subscribes to a dom event. | [
"Lazily",
"subscribes",
"to",
"a",
"dom",
"event",
"."
]
| a1d3f1f177887485b084aa38c91189fd9f9cfedf | https://github.com/tdreyno/morlock.js/blob/a1d3f1f177887485b084aa38c91189fd9f9cfedf/core/stream.js#L132-L145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.