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
44,600
cfpb/AtomicComponent
src/utilities/on-ready/index.js
onReady
function onReady( fn ) { // Ensure we passed a function as the argument if ( typeof fn !== 'function' ) { return []; } // If the ready state is already complete, run the passed function, // otherwise add it to our saved array. if ( document.readyState === 'complete' ) { fn(); } else { _readyFunctions.push( fn ); } // When the ready state changes to complete, run the passed function document.onreadystatechange = function() { if ( document.readyState === 'complete' ) { for ( let i = 0, l = _readyFunctions.length; i < l; i++ ) { _readyFunctions[i](); } _readyFunctions.length = 0; } }; return _readyFunctions; }
javascript
function onReady( fn ) { // Ensure we passed a function as the argument if ( typeof fn !== 'function' ) { return []; } // If the ready state is already complete, run the passed function, // otherwise add it to our saved array. if ( document.readyState === 'complete' ) { fn(); } else { _readyFunctions.push( fn ); } // When the ready state changes to complete, run the passed function document.onreadystatechange = function() { if ( document.readyState === 'complete' ) { for ( let i = 0, l = _readyFunctions.length; i < l; i++ ) { _readyFunctions[i](); } _readyFunctions.length = 0; } }; return _readyFunctions; }
[ "function", "onReady", "(", "fn", ")", "{", "// Ensure we passed a function as the argument", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "return", "[", "]", ";", "}", "// If the ready state is already complete, run the passed function,", "// otherwise add it to our saved array.", "if", "(", "document", ".", "readyState", "===", "'complete'", ")", "{", "fn", "(", ")", ";", "}", "else", "{", "_readyFunctions", ".", "push", "(", "fn", ")", ";", "}", "// When the ready state changes to complete, run the passed function", "document", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "document", ".", "readyState", "===", "'complete'", ")", "{", "for", "(", "let", "i", "=", "0", ",", "l", "=", "_readyFunctions", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "_readyFunctions", "[", "i", "]", "(", ")", ";", "}", "_readyFunctions", ".", "length", "=", "0", ";", "}", "}", ";", "return", "_readyFunctions", ";", "}" ]
Checks if the document is ready, if it is, trigger the passed function, if not, push the function to an array to be triggered after the page is loaded. @param {Function} fn - Function to run only after the DOM has completely loaded. @returns {Array} List of functions to run after the DOM has loaded.
[ "Checks", "if", "the", "document", "is", "ready", "if", "it", "is", "trigger", "the", "passed", "function", "if", "not", "push", "the", "function", "to", "an", "array", "to", "be", "triggered", "after", "the", "page", "is", "loaded", "." ]
f45d7ded6687672c8b701c9910ddfe90c7ede742
https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/on-ready/index.js#L20-L45
44,601
humantech/Hey
lib/hey.js
Hey
function Hey(options) { // force the use of new if (this.constructor !== Hey) { throw "Hey must be instantiated with \"new\"!"; } // we need some options, don't we? if (!options || !options.path) { throw "Option object must be set with a valid path to watch."; } // start EventEmitter EventEmitter.call(this); // folders and descriptors, just in case this.__paths = []; this.__descriptors = []; // helpful boolean this.__end_of_buffer = false; // some filepath properties this.__isDirectory = false; this.__isFile = false; Object.defineProperty(this, "isDirectory", { enumerable: true, get: function () { return this.__isDirectory; } }); Object.defineProperty(this, "isFile", { enumerable: true, get: function () { return this.__isFile; } }); // define options as "property" this.__options = options; Object.defineProperty(this, "options", { enumerable: true, get: function () { return this.__options; } }); // default mask Object.defineProperty(this, "defaultMask", { enumerable: true, get: function () { return Hey.FLAGS.MODIFY | Hey.FLAGS.CREATE | Hey.FLAGS.DELETE | Hey.FLAGS.SELF_DELETE | Hey.FLAGS.MOVE | Hey.FLAGS.SELF_MOVE; } }); this.initialize(); }
javascript
function Hey(options) { // force the use of new if (this.constructor !== Hey) { throw "Hey must be instantiated with \"new\"!"; } // we need some options, don't we? if (!options || !options.path) { throw "Option object must be set with a valid path to watch."; } // start EventEmitter EventEmitter.call(this); // folders and descriptors, just in case this.__paths = []; this.__descriptors = []; // helpful boolean this.__end_of_buffer = false; // some filepath properties this.__isDirectory = false; this.__isFile = false; Object.defineProperty(this, "isDirectory", { enumerable: true, get: function () { return this.__isDirectory; } }); Object.defineProperty(this, "isFile", { enumerable: true, get: function () { return this.__isFile; } }); // define options as "property" this.__options = options; Object.defineProperty(this, "options", { enumerable: true, get: function () { return this.__options; } }); // default mask Object.defineProperty(this, "defaultMask", { enumerable: true, get: function () { return Hey.FLAGS.MODIFY | Hey.FLAGS.CREATE | Hey.FLAGS.DELETE | Hey.FLAGS.SELF_DELETE | Hey.FLAGS.MOVE | Hey.FLAGS.SELF_MOVE; } }); this.initialize(); }
[ "function", "Hey", "(", "options", ")", "{", "// force the use of new", "if", "(", "this", ".", "constructor", "!==", "Hey", ")", "{", "throw", "\"Hey must be instantiated with \\\"new\\\"!\"", ";", "}", "// we need some options, don't we?", "if", "(", "!", "options", "||", "!", "options", ".", "path", ")", "{", "throw", "\"Option object must be set with a valid path to watch.\"", ";", "}", "// start EventEmitter", "EventEmitter", ".", "call", "(", "this", ")", ";", "// folders and descriptors, just in case", "this", ".", "__paths", "=", "[", "]", ";", "this", ".", "__descriptors", "=", "[", "]", ";", "// helpful boolean", "this", ".", "__end_of_buffer", "=", "false", ";", "// some filepath properties", "this", ".", "__isDirectory", "=", "false", ";", "this", ".", "__isFile", "=", "false", ";", "Object", ".", "defineProperty", "(", "this", ",", "\"isDirectory\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "__isDirectory", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "\"isFile\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "__isFile", ";", "}", "}", ")", ";", "// define options as \"property\"", "this", ".", "__options", "=", "options", ";", "Object", ".", "defineProperty", "(", "this", ",", "\"options\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "__options", ";", "}", "}", ")", ";", "// default mask", "Object", ".", "defineProperty", "(", "this", ",", "\"defaultMask\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "Hey", ".", "FLAGS", ".", "MODIFY", "|", "Hey", ".", "FLAGS", ".", "CREATE", "|", "Hey", ".", "FLAGS", ".", "DELETE", "|", "Hey", ".", "FLAGS", ".", "SELF_DELETE", "|", "Hey", ".", "FLAGS", ".", "MOVE", "|", "Hey", ".", "FLAGS", ".", "SELF_MOVE", ";", "}", "}", ")", ";", "this", ".", "initialize", "(", ")", ";", "}" ]
class for watching a path with custom events and options
[ "class", "for", "watching", "a", "path", "with", "custom", "events", "and", "options" ]
801972fc036d199f78a031e7a7444c8215e2b1e0
https://github.com/humantech/Hey/blob/801972fc036d199f78a031e7a7444c8215e2b1e0/lib/hey.js#L14-L75
44,602
throneteki/throneteki-deck-helper
lib/formatDeckAsFullCards.js
formatDeckAsFullCards
function formatDeckAsFullCards(deck, data) { var newDeck = { _id: deck._id, name: deck.name, username: deck.username, lastUpdated: deck.lastUpdated, faction: Object.assign({}, deck.faction) }; if (data.factions) { newDeck.faction = data.factions[deck.faction.value]; } if (deck.agenda) { newDeck.agenda = data.cards[deck.agenda.code]; } newDeck.bannerCards = (deck.bannerCards || []).map(function (card) { return data.cards[card.code]; }); newDeck.drawCards = processCardCounts(deck.drawCards || [], data.cards); newDeck.plotCards = processCardCounts(deck.plotCards || [], data.cards); newDeck.rookeryCards = processCardCounts(deck.rookeryCards || [], data.cards); return newDeck; }
javascript
function formatDeckAsFullCards(deck, data) { var newDeck = { _id: deck._id, name: deck.name, username: deck.username, lastUpdated: deck.lastUpdated, faction: Object.assign({}, deck.faction) }; if (data.factions) { newDeck.faction = data.factions[deck.faction.value]; } if (deck.agenda) { newDeck.agenda = data.cards[deck.agenda.code]; } newDeck.bannerCards = (deck.bannerCards || []).map(function (card) { return data.cards[card.code]; }); newDeck.drawCards = processCardCounts(deck.drawCards || [], data.cards); newDeck.plotCards = processCardCounts(deck.plotCards || [], data.cards); newDeck.rookeryCards = processCardCounts(deck.rookeryCards || [], data.cards); return newDeck; }
[ "function", "formatDeckAsFullCards", "(", "deck", ",", "data", ")", "{", "var", "newDeck", "=", "{", "_id", ":", "deck", ".", "_id", ",", "name", ":", "deck", ".", "name", ",", "username", ":", "deck", ".", "username", ",", "lastUpdated", ":", "deck", ".", "lastUpdated", ",", "faction", ":", "Object", ".", "assign", "(", "{", "}", ",", "deck", ".", "faction", ")", "}", ";", "if", "(", "data", ".", "factions", ")", "{", "newDeck", ".", "faction", "=", "data", ".", "factions", "[", "deck", ".", "faction", ".", "value", "]", ";", "}", "if", "(", "deck", ".", "agenda", ")", "{", "newDeck", ".", "agenda", "=", "data", ".", "cards", "[", "deck", ".", "agenda", ".", "code", "]", ";", "}", "newDeck", ".", "bannerCards", "=", "(", "deck", ".", "bannerCards", "||", "[", "]", ")", ".", "map", "(", "function", "(", "card", ")", "{", "return", "data", ".", "cards", "[", "card", ".", "code", "]", ";", "}", ")", ";", "newDeck", ".", "drawCards", "=", "processCardCounts", "(", "deck", ".", "drawCards", "||", "[", "]", ",", "data", ".", "cards", ")", ";", "newDeck", ".", "plotCards", "=", "processCardCounts", "(", "deck", ".", "plotCards", "||", "[", "]", ",", "data", ".", "cards", ")", ";", "newDeck", ".", "rookeryCards", "=", "processCardCounts", "(", "deck", ".", "rookeryCards", "||", "[", "]", ",", "data", ".", "cards", ")", ";", "return", "newDeck", ";", "}" ]
Creates a clone of the existing deck with full card data filled in instead of just card codes. @param {object} deck @param {object} data @param {object} data.cards - an index of card code to full card object @param {object} data.factions - an index of faction code to full faction object
[ "Creates", "a", "clone", "of", "the", "existing", "deck", "with", "full", "card", "data", "filled", "in", "instead", "of", "just", "card", "codes", "." ]
700280f5747b99d626c8ea6033064bd01f93da60
https://github.com/throneteki/throneteki-deck-helper/blob/700280f5747b99d626c8ea6033064bd01f93da60/lib/formatDeckAsFullCards.js#L12-L37
44,603
binduwavell/generator-alfresco-common
lib/dependency-versions.js
function (rawLine) { // Maven on the Travis-CI Ubunty Trusty container makes the version line bold. // Let's just say I'm pretty salty at this point. So we strip ANSI codes. var line = stripAnsi(rawLine); debug('Checking cmd output: ' + line); var match = line.match(re); if (match !== null) { retv = match; } }
javascript
function (rawLine) { // Maven on the Travis-CI Ubunty Trusty container makes the version line bold. // Let's just say I'm pretty salty at this point. So we strip ANSI codes. var line = stripAnsi(rawLine); debug('Checking cmd output: ' + line); var match = line.match(re); if (match !== null) { retv = match; } }
[ "function", "(", "rawLine", ")", "{", "// Maven on the Travis-CI Ubunty Trusty container makes the version line bold.", "// Let's just say I'm pretty salty at this point. So we strip ANSI codes.", "var", "line", "=", "stripAnsi", "(", "rawLine", ")", ";", "debug", "(", "'Checking cmd output: '", "+", "line", ")", ";", "var", "match", "=", "line", ".", "match", "(", "re", ")", ";", "if", "(", "match", "!==", "null", ")", "{", "retv", "=", "match", ";", "}", "}" ]
if line matches regex return line
[ "if", "line", "matches", "regex", "return", "line" ]
d9ba309a1b1d26a97268a07a49ac9e5d86b31dc4
https://github.com/binduwavell/generator-alfresco-common/blob/d9ba309a1b1d26a97268a07a49ac9e5d86b31dc4/lib/dependency-versions.js#L73-L82
44,604
vid/SenseBase
services/watch.js
processWatches
function processWatches(items) { // queue up matches // { "member" : { "uri" : [ "match", "match" ] } } var toSend = {}; GLOBAL.svc.indexer.retrieveWatches({}, function(err, res) { if (res.hits) { var watches = _.pluck(res.hits.hits, '_source'); // for each hit items.forEach(function(item) { var matches = watchLib.matches(item, watches); if (matches.length) { matches.forEach(function(match) { toSend[match.member] = toSend[match.member] || {}; toSend[match.member][item.uri] = toSend[match.member][item.uri] || []; toSend[match.member][item.uri].push(match.match); }); } }); send(toSend); } }); }
javascript
function processWatches(items) { // queue up matches // { "member" : { "uri" : [ "match", "match" ] } } var toSend = {}; GLOBAL.svc.indexer.retrieveWatches({}, function(err, res) { if (res.hits) { var watches = _.pluck(res.hits.hits, '_source'); // for each hit items.forEach(function(item) { var matches = watchLib.matches(item, watches); if (matches.length) { matches.forEach(function(match) { toSend[match.member] = toSend[match.member] || {}; toSend[match.member][item.uri] = toSend[match.member][item.uri] || []; toSend[match.member][item.uri].push(match.match); }); } }); send(toSend); } }); }
[ "function", "processWatches", "(", "items", ")", "{", "// queue up matches", "// { \"member\" : { \"uri\" : [ \"match\", \"match\" ] } }", "var", "toSend", "=", "{", "}", ";", "GLOBAL", ".", "svc", ".", "indexer", ".", "retrieveWatches", "(", "{", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "res", ".", "hits", ")", "{", "var", "watches", "=", "_", ".", "pluck", "(", "res", ".", "hits", ".", "hits", ",", "'_source'", ")", ";", "// for each hit", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "matches", "=", "watchLib", ".", "matches", "(", "item", ",", "watches", ")", ";", "if", "(", "matches", ".", "length", ")", "{", "matches", ".", "forEach", "(", "function", "(", "match", ")", "{", "toSend", "[", "match", ".", "member", "]", "=", "toSend", "[", "match", ".", "member", "]", "||", "{", "}", ";", "toSend", "[", "match", ".", "member", "]", "[", "item", ".", "uri", "]", "=", "toSend", "[", "match", ".", "member", "]", "[", "item", ".", "uri", "]", "||", "[", "]", ";", "toSend", "[", "match", ".", "member", "]", "[", "item", ".", "uri", "]", ".", "push", "(", "match", ".", "match", ")", ";", "}", ")", ";", "}", "}", ")", ";", "send", "(", "toSend", ")", ";", "}", "}", ")", ";", "}" ]
process any watches in the last time period
[ "process", "any", "watches", "in", "the", "last", "time", "period" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/services/watch.js#L21-L42
44,605
typoerr/quex
dist/index.js
createStore
function createStore(initialState, option) { let $state = initialState; let $listener = []; const $enhancer = option && option.enhancer; const $updater = (() => { const f1 = option && option.updater; const f2 = (s1, s2) => Object.assign({}, s1, s2); return f1 || f2; })(); return { get listenerCount() { return $listener.length; }, getState, setState, dispatch: usecase, usecase, subscribe, }; /** * Get state * * @returns {S} */ function getState() { return $state; } /** * Set state * this api depend on updater * * @param {Partial<S>} state * @returns {S} state */ function setState(state) { $state = $updater($state, state); return $state; } /** * Listen changing of state and exception of transition * * @param listener * @returns {Function} unsubscribe */ function subscribe(listener) { $listener.push(listener); return function unsubscribe() { $listener = $listener.filter(f => f !== listener); }; } /** * Publish changing of state to listener * * @private * @param {S} state * @param {Error} [error] * @returns {void} */ function publish(state, error) { $listener.forEach(f => f(state, error)); } /** * Compose queue * * @param {string} [name] * @returns {Use} * @example * usecase('name').use([f1, f2])(param) * usecase('name').use(f1).use(f2)(param) */ function usecase(name) { let $queue = []; let $run; return { use }; function use(arg) { let q = [].concat(arg); q = $enhancer ? q.map((t) => $enhancer(name, t)) : q; q.forEach(t => $queue.push(t)); return $run || (() => { $run = run; $run.use = use; return $run; })(); } function run() { next($queue[Symbol.iterator](), arguments[0]); } ; } /** * Execute one task from iterator then * mutation state and publishing * * @private * @param {Iterator<Function>} i * @param {*} p * @param {Function} [task] * @returns {void} */ function next(i, p, task) { let iResult = task ? { value: task, done: false } : i.next(); try { if (iResult.done) { publish($state); return; } const result = iResult.value($state, p); /* Promise(Like) */ if (result && typeof result.then === 'function') { result.then(resolved, rejected); publish($state); return; function resolved(t) { const _t = (typeof t === 'function') && t; next(i, p, _t); } ; function rejected(err) { publish($state, err); } } if (!iResult.done) { result && setState(result); next(i, p); return; } } catch (e) { publish($state, e); } } }
javascript
function createStore(initialState, option) { let $state = initialState; let $listener = []; const $enhancer = option && option.enhancer; const $updater = (() => { const f1 = option && option.updater; const f2 = (s1, s2) => Object.assign({}, s1, s2); return f1 || f2; })(); return { get listenerCount() { return $listener.length; }, getState, setState, dispatch: usecase, usecase, subscribe, }; /** * Get state * * @returns {S} */ function getState() { return $state; } /** * Set state * this api depend on updater * * @param {Partial<S>} state * @returns {S} state */ function setState(state) { $state = $updater($state, state); return $state; } /** * Listen changing of state and exception of transition * * @param listener * @returns {Function} unsubscribe */ function subscribe(listener) { $listener.push(listener); return function unsubscribe() { $listener = $listener.filter(f => f !== listener); }; } /** * Publish changing of state to listener * * @private * @param {S} state * @param {Error} [error] * @returns {void} */ function publish(state, error) { $listener.forEach(f => f(state, error)); } /** * Compose queue * * @param {string} [name] * @returns {Use} * @example * usecase('name').use([f1, f2])(param) * usecase('name').use(f1).use(f2)(param) */ function usecase(name) { let $queue = []; let $run; return { use }; function use(arg) { let q = [].concat(arg); q = $enhancer ? q.map((t) => $enhancer(name, t)) : q; q.forEach(t => $queue.push(t)); return $run || (() => { $run = run; $run.use = use; return $run; })(); } function run() { next($queue[Symbol.iterator](), arguments[0]); } ; } /** * Execute one task from iterator then * mutation state and publishing * * @private * @param {Iterator<Function>} i * @param {*} p * @param {Function} [task] * @returns {void} */ function next(i, p, task) { let iResult = task ? { value: task, done: false } : i.next(); try { if (iResult.done) { publish($state); return; } const result = iResult.value($state, p); /* Promise(Like) */ if (result && typeof result.then === 'function') { result.then(resolved, rejected); publish($state); return; function resolved(t) { const _t = (typeof t === 'function') && t; next(i, p, _t); } ; function rejected(err) { publish($state, err); } } if (!iResult.done) { result && setState(result); next(i, p); return; } } catch (e) { publish($state, e); } } }
[ "function", "createStore", "(", "initialState", ",", "option", ")", "{", "let", "$state", "=", "initialState", ";", "let", "$listener", "=", "[", "]", ";", "const", "$enhancer", "=", "option", "&&", "option", ".", "enhancer", ";", "const", "$updater", "=", "(", "(", ")", "=>", "{", "const", "f1", "=", "option", "&&", "option", ".", "updater", ";", "const", "f2", "=", "(", "s1", ",", "s2", ")", "=>", "Object", ".", "assign", "(", "{", "}", ",", "s1", ",", "s2", ")", ";", "return", "f1", "||", "f2", ";", "}", ")", "(", ")", ";", "return", "{", "get", "listenerCount", "(", ")", "{", "return", "$listener", ".", "length", ";", "}", ",", "getState", ",", "setState", ",", "dispatch", ":", "usecase", ",", "usecase", ",", "subscribe", ",", "}", ";", "/**\n * Get state\n *\n * @returns {S}\n */", "function", "getState", "(", ")", "{", "return", "$state", ";", "}", "/**\n * Set state\n * this api depend on updater\n *\n * @param {Partial<S>} state\n * @returns {S} state\n */", "function", "setState", "(", "state", ")", "{", "$state", "=", "$updater", "(", "$state", ",", "state", ")", ";", "return", "$state", ";", "}", "/**\n * Listen changing of state and exception of transition\n *\n * @param listener\n * @returns {Function} unsubscribe\n */", "function", "subscribe", "(", "listener", ")", "{", "$listener", ".", "push", "(", "listener", ")", ";", "return", "function", "unsubscribe", "(", ")", "{", "$listener", "=", "$listener", ".", "filter", "(", "f", "=>", "f", "!==", "listener", ")", ";", "}", ";", "}", "/**\n * Publish changing of state to listener\n *\n * @private\n * @param {S} state\n * @param {Error} [error]\n * @returns {void}\n */", "function", "publish", "(", "state", ",", "error", ")", "{", "$listener", ".", "forEach", "(", "f", "=>", "f", "(", "state", ",", "error", ")", ")", ";", "}", "/**\n * Compose queue\n *\n * @param {string} [name]\n * @returns {Use}\n * @example\n * usecase('name').use([f1, f2])(param)\n * usecase('name').use(f1).use(f2)(param)\n */", "function", "usecase", "(", "name", ")", "{", "let", "$queue", "=", "[", "]", ";", "let", "$run", ";", "return", "{", "use", "}", ";", "function", "use", "(", "arg", ")", "{", "let", "q", "=", "[", "]", ".", "concat", "(", "arg", ")", ";", "q", "=", "$enhancer", "?", "q", ".", "map", "(", "(", "t", ")", "=>", "$enhancer", "(", "name", ",", "t", ")", ")", ":", "q", ";", "q", ".", "forEach", "(", "t", "=>", "$queue", ".", "push", "(", "t", ")", ")", ";", "return", "$run", "||", "(", "(", ")", "=>", "{", "$run", "=", "run", ";", "$run", ".", "use", "=", "use", ";", "return", "$run", ";", "}", ")", "(", ")", ";", "}", "function", "run", "(", ")", "{", "next", "(", "$queue", "[", "Symbol", ".", "iterator", "]", "(", ")", ",", "arguments", "[", "0", "]", ")", ";", "}", ";", "}", "/**\n * Execute one task from iterator then\n * mutation state and publishing\n *\n * @private\n * @param {Iterator<Function>} i\n * @param {*} p\n * @param {Function} [task]\n * @returns {void}\n */", "function", "next", "(", "i", ",", "p", ",", "task", ")", "{", "let", "iResult", "=", "task", "?", "{", "value", ":", "task", ",", "done", ":", "false", "}", ":", "i", ".", "next", "(", ")", ";", "try", "{", "if", "(", "iResult", ".", "done", ")", "{", "publish", "(", "$state", ")", ";", "return", ";", "}", "const", "result", "=", "iResult", ".", "value", "(", "$state", ",", "p", ")", ";", "/* Promise(Like) */", "if", "(", "result", "&&", "typeof", "result", ".", "then", "===", "'function'", ")", "{", "result", ".", "then", "(", "resolved", ",", "rejected", ")", ";", "publish", "(", "$state", ")", ";", "return", ";", "function", "resolved", "(", "t", ")", "{", "const", "_t", "=", "(", "typeof", "t", "===", "'function'", ")", "&&", "t", ";", "next", "(", "i", ",", "p", ",", "_t", ")", ";", "}", ";", "function", "rejected", "(", "err", ")", "{", "publish", "(", "$state", ",", "err", ")", ";", "}", "}", "if", "(", "!", "iResult", ".", "done", ")", "{", "result", "&&", "setState", "(", "result", ")", ";", "next", "(", "i", ",", "p", ")", ";", "return", ";", "}", "}", "catch", "(", "e", ")", "{", "publish", "(", "$state", ",", "e", ")", ";", "}", "}", "}" ]
create quex store @export @template S @param {S} initialState @param {{ updater?: Updater<S>; enhancer?: Enhancer<S> }} [option] @returns {Quex<S>}
[ "create", "quex", "store" ]
5d7652b1642d356db68177fa6bd76d79accfbd4e
https://github.com/typoerr/quex/blob/5d7652b1642d356db68177fa6bd76d79accfbd4e/dist/index.js#L15-L146
44,606
typoerr/quex
dist/index.js
next
function next(i, p, task) { let iResult = task ? { value: task, done: false } : i.next(); try { if (iResult.done) { publish($state); return; } const result = iResult.value($state, p); /* Promise(Like) */ if (result && typeof result.then === 'function') { result.then(resolved, rejected); publish($state); return; function resolved(t) { const _t = (typeof t === 'function') && t; next(i, p, _t); } ; function rejected(err) { publish($state, err); } } if (!iResult.done) { result && setState(result); next(i, p); return; } } catch (e) { publish($state, e); } }
javascript
function next(i, p, task) { let iResult = task ? { value: task, done: false } : i.next(); try { if (iResult.done) { publish($state); return; } const result = iResult.value($state, p); /* Promise(Like) */ if (result && typeof result.then === 'function') { result.then(resolved, rejected); publish($state); return; function resolved(t) { const _t = (typeof t === 'function') && t; next(i, p, _t); } ; function rejected(err) { publish($state, err); } } if (!iResult.done) { result && setState(result); next(i, p); return; } } catch (e) { publish($state, e); } }
[ "function", "next", "(", "i", ",", "p", ",", "task", ")", "{", "let", "iResult", "=", "task", "?", "{", "value", ":", "task", ",", "done", ":", "false", "}", ":", "i", ".", "next", "(", ")", ";", "try", "{", "if", "(", "iResult", ".", "done", ")", "{", "publish", "(", "$state", ")", ";", "return", ";", "}", "const", "result", "=", "iResult", ".", "value", "(", "$state", ",", "p", ")", ";", "/* Promise(Like) */", "if", "(", "result", "&&", "typeof", "result", ".", "then", "===", "'function'", ")", "{", "result", ".", "then", "(", "resolved", ",", "rejected", ")", ";", "publish", "(", "$state", ")", ";", "return", ";", "function", "resolved", "(", "t", ")", "{", "const", "_t", "=", "(", "typeof", "t", "===", "'function'", ")", "&&", "t", ";", "next", "(", "i", ",", "p", ",", "_t", ")", ";", "}", ";", "function", "rejected", "(", "err", ")", "{", "publish", "(", "$state", ",", "err", ")", ";", "}", "}", "if", "(", "!", "iResult", ".", "done", ")", "{", "result", "&&", "setState", "(", "result", ")", ";", "next", "(", "i", ",", "p", ")", ";", "return", ";", "}", "}", "catch", "(", "e", ")", "{", "publish", "(", "$state", ",", "e", ")", ";", "}", "}" ]
Execute one task from iterator then mutation state and publishing @private @param {Iterator<Function>} i @param {*} p @param {Function} [task] @returns {void}
[ "Execute", "one", "task", "from", "iterator", "then", "mutation", "state", "and", "publishing" ]
5d7652b1642d356db68177fa6bd76d79accfbd4e
https://github.com/typoerr/quex/blob/5d7652b1642d356db68177fa6bd76d79accfbd4e/dist/index.js#L114-L145
44,607
socialally/air
lib/air/ui/dialog.js
dialog
function dialog(opts, cb) { var $ = dialog.air , el = opts.el.clone(true) , container = opts.container || $('body') , evt = opts.evt || 'click' , res = {accepted: false, el: el}; opts.accept = opts.accept || '[href="#ok"]'; opts.reject = opts.reject || '[href="#cancel"]'; // pass function to remove element in result // when we don't handle removing if(opts.remove === false) { res.remove = function() { el.remove(); } } container.append(el); function onReject(e) { e.preventDefault(); if(opts.remove !== false) { el.remove(); } cb(res); } function onAccept(e) { e.preventDefault(); if(opts.remove !== false) { el.remove(); } res.accepted = true; cb(res); } var modal = el.find('.modal'); if(opts.modal !== false) { modal.on(evt, onReject); }else{ modal.css({cursor: 'auto'}) } el.find(opts.reject).on(evt, onReject); el.find(opts.accept).on(evt, onAccept); return el; }
javascript
function dialog(opts, cb) { var $ = dialog.air , el = opts.el.clone(true) , container = opts.container || $('body') , evt = opts.evt || 'click' , res = {accepted: false, el: el}; opts.accept = opts.accept || '[href="#ok"]'; opts.reject = opts.reject || '[href="#cancel"]'; // pass function to remove element in result // when we don't handle removing if(opts.remove === false) { res.remove = function() { el.remove(); } } container.append(el); function onReject(e) { e.preventDefault(); if(opts.remove !== false) { el.remove(); } cb(res); } function onAccept(e) { e.preventDefault(); if(opts.remove !== false) { el.remove(); } res.accepted = true; cb(res); } var modal = el.find('.modal'); if(opts.modal !== false) { modal.on(evt, onReject); }else{ modal.css({cursor: 'auto'}) } el.find(opts.reject).on(evt, onReject); el.find(opts.accept).on(evt, onAccept); return el; }
[ "function", "dialog", "(", "opts", ",", "cb", ")", "{", "var", "$", "=", "dialog", ".", "air", ",", "el", "=", "opts", ".", "el", ".", "clone", "(", "true", ")", ",", "container", "=", "opts", ".", "container", "||", "$", "(", "'body'", ")", ",", "evt", "=", "opts", ".", "evt", "||", "'click'", ",", "res", "=", "{", "accepted", ":", "false", ",", "el", ":", "el", "}", ";", "opts", ".", "accept", "=", "opts", ".", "accept", "||", "'[href=\"#ok\"]'", ";", "opts", ".", "reject", "=", "opts", ".", "reject", "||", "'[href=\"#cancel\"]'", ";", "// pass function to remove element in result", "// when we don't handle removing", "if", "(", "opts", ".", "remove", "===", "false", ")", "{", "res", ".", "remove", "=", "function", "(", ")", "{", "el", ".", "remove", "(", ")", ";", "}", "}", "container", ".", "append", "(", "el", ")", ";", "function", "onReject", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "opts", ".", "remove", "!==", "false", ")", "{", "el", ".", "remove", "(", ")", ";", "}", "cb", "(", "res", ")", ";", "}", "function", "onAccept", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "opts", ".", "remove", "!==", "false", ")", "{", "el", ".", "remove", "(", ")", ";", "}", "res", ".", "accepted", "=", "true", ";", "cb", "(", "res", ")", ";", "}", "var", "modal", "=", "el", ".", "find", "(", "'.modal'", ")", ";", "if", "(", "opts", ".", "modal", "!==", "false", ")", "{", "modal", ".", "on", "(", "evt", ",", "onReject", ")", ";", "}", "else", "{", "modal", ".", "css", "(", "{", "cursor", ":", "'auto'", "}", ")", "}", "el", ".", "find", "(", "opts", ".", "reject", ")", ".", "on", "(", "evt", ",", "onReject", ")", ";", "el", ".", "find", "(", "opts", ".", "accept", ")", ".", "on", "(", "evt", ",", "onAccept", ")", ";", "return", "el", ";", "}" ]
Show a modal dialog. The passed element (`el`) is cloned and appended to the `container`. @param opts {Object} Dialog options. @param cb {Function} A callback function for accept or reject. @options: - el: The dialog element (root of the markup below). - container: Parent element to append the dialog to. - modal: Whether the modal element dismisses the dialog. - remove: Whether the dialog is removed on accept or reject. - evt: The event name to listen to. - accept: Selector used to accept the dialog. - reject: Selector used to reject the dialog. @markup - .dialog - .modal - .container - .content @css/stylus .dialog position: absolute; z-index: 2000; top: 0; left: 0; width: 100%; height: 100%; display: table; .modal position: absolute; z-index: 2001; left: 0; top: 0; right: 0; bottom: 0; background: rgba(0,0,0,.8); cursor: pointer; .container display: table-cell; vertical-align: middle; text-align: center; .content position: relative; z-index: 2002; @dependencies - clone - css - event - find
[ "Show", "a", "modal", "dialog", "." ]
a3d94de58aaa4930a425fbcc7266764bf6ca8ca6
https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/ui/dialog.js#L60-L107
44,608
jonschlinkert/delims
index.js
Delimiters
function Delimiters (delims, options) { this.options = options || {}; this.delims = delims || []; this.defaults = merge({}, { beginning: '^', // '^' Matches beginning of input. matter: '([\\s\\S]+?)', // The "content" between the delims body: '([\\s\\S]+|\\s?)', // The "content" after the delims end: '$', // '$' Matches end of input. flags: '' // RegExp flags: g, m, i }, options); }
javascript
function Delimiters (delims, options) { this.options = options || {}; this.delims = delims || []; this.defaults = merge({}, { beginning: '^', // '^' Matches beginning of input. matter: '([\\s\\S]+?)', // The "content" between the delims body: '([\\s\\S]+|\\s?)', // The "content" after the delims end: '$', // '$' Matches end of input. flags: '' // RegExp flags: g, m, i }, options); }
[ "function", "Delimiters", "(", "delims", ",", "options", ")", "{", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "delims", "=", "delims", "||", "[", "]", ";", "this", ".", "defaults", "=", "merge", "(", "{", "}", ",", "{", "beginning", ":", "'^'", ",", "// '^' Matches beginning of input.", "matter", ":", "'([\\\\s\\\\S]+?)'", ",", "// The \"content\" between the delims", "body", ":", "'([\\\\s\\\\S]+|\\\\s?)'", ",", "// The \"content\" after the delims", "end", ":", "'$'", ",", "// '$' Matches end of input.", "flags", ":", "''", "// RegExp flags: g, m, i", "}", ",", "options", ")", ";", "}" ]
Generate regular expressions for template delimiters. @param {Array} `delims` @param {Object} `options`
[ "Generate", "regular", "expressions", "for", "template", "delimiters", "." ]
137f643e83632317045f8d68c3b32abd1ccb45d3
https://github.com/jonschlinkert/delims/blob/137f643e83632317045f8d68c3b32abd1ccb45d3/index.js#L22-L33
44,609
AsceticBoy/chilli-toolkit
lib/ipromise/core.js
safelyToExecutor
function safelyToExecutor(self, executor) { let done = false; try { executor( function(result) { if (done) return; done = true; doResolve.call(self, result); }, // doResolve function(error) { if (done) return; done = true; doReject.call(self, error); } // doReject ); } catch (error) { if (done) return; done = true; doReject.call(self, error); } }
javascript
function safelyToExecutor(self, executor) { let done = false; try { executor( function(result) { if (done) return; done = true; doResolve.call(self, result); }, // doResolve function(error) { if (done) return; done = true; doReject.call(self, error); } // doReject ); } catch (error) { if (done) return; done = true; doReject.call(self, error); } }
[ "function", "safelyToExecutor", "(", "self", ",", "executor", ")", "{", "let", "done", "=", "false", ";", "try", "{", "executor", "(", "function", "(", "result", ")", "{", "if", "(", "done", ")", "return", ";", "done", "=", "true", ";", "doResolve", ".", "call", "(", "self", ",", "result", ")", ";", "}", ",", "// doResolve", "function", "(", "error", ")", "{", "if", "(", "done", ")", "return", ";", "done", "=", "true", ";", "doReject", ".", "call", "(", "self", ",", "error", ")", ";", "}", "// doReject", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "done", ")", "return", ";", "done", "=", "true", ";", "doReject", ".", "call", "(", "self", ",", "error", ")", ";", "}", "}" ]
onResolved or onRejected only one called once @param { object } self current IPromise @param { function } executor this's user operater
[ "onResolved", "or", "onRejected", "only", "one", "called", "once" ]
a4f5f03ce55187a8c91b847e84d767357f347839
https://github.com/AsceticBoy/chilli-toolkit/blob/a4f5f03ce55187a8c91b847e84d767357f347839/lib/ipromise/core.js#L40-L60
44,610
AsceticBoy/chilli-toolkit
lib/ipromise/core.js
doResolve
function doResolve(result) { let self = this; if (result === self) { // Promise Standard 2.3.1 return doReject.call( self, new TypeError("Can not resolve 'Promise' itself") ); } // Promise Standard 2.3.3.2 try { // Promise Standard 2.3.2 and 2.3.3 can be merge // if result is a thenable(.then) let then = safelyToThen(result); if (then) { // Promise Standard 2.3.3.3 safelyToExecutor(self, then.bind(result)); } else { // [[ async ]] setTimeout(function() { // commonly case if (self.currentState === Shared.PENDING) { self.currentState = Shared.FULFILLED; self.valOrErr = result; for (let i = 0; i < self.onFulfilledCallback.length; i++) { self.onFulfilledCallback[i](result); } self.onFulfilledCallback = []; } }, 0); } // case: when then(doResolve, doReject) -> asyncToResolveOrReject -> func(arg) -> return self return self; } catch (error) { return doReject.call(self, error); } }
javascript
function doResolve(result) { let self = this; if (result === self) { // Promise Standard 2.3.1 return doReject.call( self, new TypeError("Can not resolve 'Promise' itself") ); } // Promise Standard 2.3.3.2 try { // Promise Standard 2.3.2 and 2.3.3 can be merge // if result is a thenable(.then) let then = safelyToThen(result); if (then) { // Promise Standard 2.3.3.3 safelyToExecutor(self, then.bind(result)); } else { // [[ async ]] setTimeout(function() { // commonly case if (self.currentState === Shared.PENDING) { self.currentState = Shared.FULFILLED; self.valOrErr = result; for (let i = 0; i < self.onFulfilledCallback.length; i++) { self.onFulfilledCallback[i](result); } self.onFulfilledCallback = []; } }, 0); } // case: when then(doResolve, doReject) -> asyncToResolveOrReject -> func(arg) -> return self return self; } catch (error) { return doReject.call(self, error); } }
[ "function", "doResolve", "(", "result", ")", "{", "let", "self", "=", "this", ";", "if", "(", "result", "===", "self", ")", "{", "// Promise Standard 2.3.1", "return", "doReject", ".", "call", "(", "self", ",", "new", "TypeError", "(", "\"Can not resolve 'Promise' itself\"", ")", ")", ";", "}", "// Promise Standard 2.3.3.2", "try", "{", "// Promise Standard 2.3.2 and 2.3.3 can be merge", "// if result is a thenable(.then)", "let", "then", "=", "safelyToThen", "(", "result", ")", ";", "if", "(", "then", ")", "{", "// Promise Standard 2.3.3.3", "safelyToExecutor", "(", "self", ",", "then", ".", "bind", "(", "result", ")", ")", ";", "}", "else", "{", "// [[ async ]]", "setTimeout", "(", "function", "(", ")", "{", "// commonly case", "if", "(", "self", ".", "currentState", "===", "Shared", ".", "PENDING", ")", "{", "self", ".", "currentState", "=", "Shared", ".", "FULFILLED", ";", "self", ".", "valOrErr", "=", "result", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "self", ".", "onFulfilledCallback", ".", "length", ";", "i", "++", ")", "{", "self", ".", "onFulfilledCallback", "[", "i", "]", "(", "result", ")", ";", "}", "self", ".", "onFulfilledCallback", "=", "[", "]", ";", "}", "}", ",", "0", ")", ";", "}", "// case: when then(doResolve, doReject) -> asyncToResolveOrReject -> func(arg) -> return self", "return", "self", ";", "}", "catch", "(", "error", ")", "{", "return", "doReject", ".", "call", "(", "self", ",", "error", ")", ";", "}", "}" ]
Safely exec executor then doResolve or doReject The most important function call
[ "Safely", "exec", "executor", "then", "doResolve", "or", "doReject", "The", "most", "important", "function", "call" ]
a4f5f03ce55187a8c91b847e84d767357f347839
https://github.com/AsceticBoy/chilli-toolkit/blob/a4f5f03ce55187a8c91b847e84d767357f347839/lib/ipromise/core.js#L88-L124
44,611
synder/xpress
demo/body-parser/lib/types/text.js
text
function text (options) { var opts = options || {} var defaultCharset = opts.defaultCharset || 'utf-8' var inflate = opts.inflate !== false var limit = typeof opts.limit !== 'number' ? bytes.parse(opts.limit || '100kb') : opts.limit var type = opts.type || 'text/plain' var verify = opts.verify || false if (verify !== false && typeof verify !== 'function') { throw new TypeError('option verify must be function') } // create the appropriate type checking function var shouldParse = typeof type !== 'function' ? typeChecker(type) : type function parse (buf) { return buf } return function textParser (req, res, next) { if (req._body) { debug('body already parsed') next() return } req.body = req.body || {} // skip requests without bodies if (!typeis.hasBody(req)) { debug('skip empty body') next() return } debug('content-type %j', req.headers['content-type']) // determine if request should be parsed if (!shouldParse(req)) { debug('skip parsing') next() return } // get charset var charset = getCharset(req) || defaultCharset // read read(req, res, next, parse, debug, { encoding: charset, inflate: inflate, limit: limit, verify: verify }) } }
javascript
function text (options) { var opts = options || {} var defaultCharset = opts.defaultCharset || 'utf-8' var inflate = opts.inflate !== false var limit = typeof opts.limit !== 'number' ? bytes.parse(opts.limit || '100kb') : opts.limit var type = opts.type || 'text/plain' var verify = opts.verify || false if (verify !== false && typeof verify !== 'function') { throw new TypeError('option verify must be function') } // create the appropriate type checking function var shouldParse = typeof type !== 'function' ? typeChecker(type) : type function parse (buf) { return buf } return function textParser (req, res, next) { if (req._body) { debug('body already parsed') next() return } req.body = req.body || {} // skip requests without bodies if (!typeis.hasBody(req)) { debug('skip empty body') next() return } debug('content-type %j', req.headers['content-type']) // determine if request should be parsed if (!shouldParse(req)) { debug('skip parsing') next() return } // get charset var charset = getCharset(req) || defaultCharset // read read(req, res, next, parse, debug, { encoding: charset, inflate: inflate, limit: limit, verify: verify }) } }
[ "function", "text", "(", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", "var", "defaultCharset", "=", "opts", ".", "defaultCharset", "||", "'utf-8'", "var", "inflate", "=", "opts", ".", "inflate", "!==", "false", "var", "limit", "=", "typeof", "opts", ".", "limit", "!==", "'number'", "?", "bytes", ".", "parse", "(", "opts", ".", "limit", "||", "'100kb'", ")", ":", "opts", ".", "limit", "var", "type", "=", "opts", ".", "type", "||", "'text/plain'", "var", "verify", "=", "opts", ".", "verify", "||", "false", "if", "(", "verify", "!==", "false", "&&", "typeof", "verify", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'option verify must be function'", ")", "}", "// create the appropriate type checking function", "var", "shouldParse", "=", "typeof", "type", "!==", "'function'", "?", "typeChecker", "(", "type", ")", ":", "type", "function", "parse", "(", "buf", ")", "{", "return", "buf", "}", "return", "function", "textParser", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "_body", ")", "{", "debug", "(", "'body already parsed'", ")", "next", "(", ")", "return", "}", "req", ".", "body", "=", "req", ".", "body", "||", "{", "}", "// skip requests without bodies", "if", "(", "!", "typeis", ".", "hasBody", "(", "req", ")", ")", "{", "debug", "(", "'skip empty body'", ")", "next", "(", ")", "return", "}", "debug", "(", "'content-type %j'", ",", "req", ".", "headers", "[", "'content-type'", "]", ")", "// determine if request should be parsed", "if", "(", "!", "shouldParse", "(", "req", ")", ")", "{", "debug", "(", "'skip parsing'", ")", "next", "(", ")", "return", "}", "// get charset", "var", "charset", "=", "getCharset", "(", "req", ")", "||", "defaultCharset", "// read", "read", "(", "req", ",", "res", ",", "next", ",", "parse", ",", "debug", ",", "{", "encoding", ":", "charset", ",", "inflate", ":", "inflate", ",", "limit", ":", "limit", ",", "verify", ":", "verify", "}", ")", "}", "}" ]
Create a middleware to parse text bodies. @param {object} [options] @return {function} @api public
[ "Create", "a", "middleware", "to", "parse", "text", "bodies", "." ]
4b1e89208b6f34cd78ce90b8a858592115b6ccb5
https://github.com/synder/xpress/blob/4b1e89208b6f34cd78ce90b8a858592115b6ccb5/demo/body-parser/lib/types/text.js#L33-L93
44,612
synder/xpress
demo/body-parser/lib/types/text.js
getCharset
function getCharset (req) { try { return contentType.parse(req).parameters.charset.toLowerCase() } catch (e) { return undefined } }
javascript
function getCharset (req) { try { return contentType.parse(req).parameters.charset.toLowerCase() } catch (e) { return undefined } }
[ "function", "getCharset", "(", "req", ")", "{", "try", "{", "return", "contentType", ".", "parse", "(", "req", ")", ".", "parameters", ".", "charset", ".", "toLowerCase", "(", ")", "}", "catch", "(", "e", ")", "{", "return", "undefined", "}", "}" ]
Get the charset of a request. @param {object} req @api private
[ "Get", "the", "charset", "of", "a", "request", "." ]
4b1e89208b6f34cd78ce90b8a858592115b6ccb5
https://github.com/synder/xpress/blob/4b1e89208b6f34cd78ce90b8a858592115b6ccb5/demo/body-parser/lib/types/text.js#L102-L108
44,613
hardog/fare
lib/fare.js
Fire
function Fire(opts) { opts = opts || {}; opts.host = opts.host || '0.0.0.0'; opts.port = opts.port || 9998; var self = this; Socket.call(self); self.n = 0; self.buf_size = opts.buf_size || 100; self.stream = opts.stream || 'off'; self.log_queue = []; self.connect(opts.port, opts.host, function(){ debug('connected host %s port %s', opts.host, opts.port); self.announce(); }); }
javascript
function Fire(opts) { opts = opts || {}; opts.host = opts.host || '0.0.0.0'; opts.port = opts.port || 9998; var self = this; Socket.call(self); self.n = 0; self.buf_size = opts.buf_size || 100; self.stream = opts.stream || 'off'; self.log_queue = []; self.connect(opts.port, opts.host, function(){ debug('connected host %s port %s', opts.host, opts.port); self.announce(); }); }
[ "function", "Fire", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "host", "=", "opts", ".", "host", "||", "'0.0.0.0'", ";", "opts", ".", "port", "=", "opts", ".", "port", "||", "9998", ";", "var", "self", "=", "this", ";", "Socket", ".", "call", "(", "self", ")", ";", "self", ".", "n", "=", "0", ";", "self", ".", "buf_size", "=", "opts", ".", "buf_size", "||", "100", ";", "self", ".", "stream", "=", "opts", ".", "stream", "||", "'off'", ";", "self", ".", "log_queue", "=", "[", "]", ";", "self", ".", "connect", "(", "opts", ".", "port", ",", "opts", ".", "host", ",", "function", "(", ")", "{", "debug", "(", "'connected host %s port %s'", ",", "opts", ".", "host", ",", "opts", ".", "port", ")", ";", "self", ".", "announce", "(", ")", ";", "}", ")", ";", "}" ]
Initialize a new `RepSocket`. @api private
[ "Initialize", "a", "new", "RepSocket", "." ]
83e29214b8331601f270fe80e21a969a5ba3f047
https://github.com/hardog/fare/blob/83e29214b8331601f270fe80e21a969a5ba3f047/lib/fare.js#L22-L38
44,614
hagino3000/Struct.js
struct.js
function(name) { if (name in props) { // Check property descriptor var desc = this.getOwnPropertyDescriptor(name); if (props[name].nullable === false) { throw name + ' is not allowd null or undefined'; } return delete obj[name]; } else { throw name + ' is not defined in this struct'; } }
javascript
function(name) { if (name in props) { // Check property descriptor var desc = this.getOwnPropertyDescriptor(name); if (props[name].nullable === false) { throw name + ' is not allowd null or undefined'; } return delete obj[name]; } else { throw name + ' is not defined in this struct'; } }
[ "function", "(", "name", ")", "{", "if", "(", "name", "in", "props", ")", "{", "// Check property descriptor", "var", "desc", "=", "this", ".", "getOwnPropertyDescriptor", "(", "name", ")", ";", "if", "(", "props", "[", "name", "]", ".", "nullable", "===", "false", ")", "{", "throw", "name", "+", "' is not allowd null or undefined'", ";", "}", "return", "delete", "obj", "[", "name", "]", ";", "}", "else", "{", "throw", "name", "+", "' is not defined in this struct'", ";", "}", "}" ]
Delete specified property. Check property name if defined in advance.
[ "Delete", "specified", "property", ".", "Check", "property", "name", "if", "defined", "in", "advance", "." ]
8c5876f58e8b1e721e9e0e3d9ff06ba02e1dd9e5
https://github.com/hagino3000/Struct.js/blob/8c5876f58e8b1e721e9e0e3d9ff06ba02e1dd9e5/struct.js#L173-L186
44,615
hagino3000/Struct.js
struct.js
function(receiver, name, val) { if (name in props) { // Check property descriptor var desc = this.getOwnPropertyDescriptor(name); if (desc && !desc.writable) { throw name + ' is not writable property'; } if (props[name].nullable === false && isNullOrUndefined(val)) { throw name + ' is not allowd null or undefined'; } // Check type match var type = props[name].type; if (isNullOrUndefined(val) || Struct.isStructType(type, val) || Struct.util.isType(type, val)) { // OK } else { throw name + ' must be ' + props[name].type + ' type'; } if (props[name].cond && !props[name].cond(val)) { throw 'Invalid value:' + name + '=' + String(val); } obj[name] = val; return true; } else { throw name + ' is not defined in this struct'; } }
javascript
function(receiver, name, val) { if (name in props) { // Check property descriptor var desc = this.getOwnPropertyDescriptor(name); if (desc && !desc.writable) { throw name + ' is not writable property'; } if (props[name].nullable === false && isNullOrUndefined(val)) { throw name + ' is not allowd null or undefined'; } // Check type match var type = props[name].type; if (isNullOrUndefined(val) || Struct.isStructType(type, val) || Struct.util.isType(type, val)) { // OK } else { throw name + ' must be ' + props[name].type + ' type'; } if (props[name].cond && !props[name].cond(val)) { throw 'Invalid value:' + name + '=' + String(val); } obj[name] = val; return true; } else { throw name + ' is not defined in this struct'; } }
[ "function", "(", "receiver", ",", "name", ",", "val", ")", "{", "if", "(", "name", "in", "props", ")", "{", "// Check property descriptor", "var", "desc", "=", "this", ".", "getOwnPropertyDescriptor", "(", "name", ")", ";", "if", "(", "desc", "&&", "!", "desc", ".", "writable", ")", "{", "throw", "name", "+", "' is not writable property'", ";", "}", "if", "(", "props", "[", "name", "]", ".", "nullable", "===", "false", "&&", "isNullOrUndefined", "(", "val", ")", ")", "{", "throw", "name", "+", "' is not allowd null or undefined'", ";", "}", "// Check type match", "var", "type", "=", "props", "[", "name", "]", ".", "type", ";", "if", "(", "isNullOrUndefined", "(", "val", ")", "||", "Struct", ".", "isStructType", "(", "type", ",", "val", ")", "||", "Struct", ".", "util", ".", "isType", "(", "type", ",", "val", ")", ")", "{", "// OK", "}", "else", "{", "throw", "name", "+", "' must be '", "+", "props", "[", "name", "]", ".", "type", "+", "' type'", ";", "}", "if", "(", "props", "[", "name", "]", ".", "cond", "&&", "!", "props", "[", "name", "]", ".", "cond", "(", "val", ")", ")", "{", "throw", "'Invalid value:'", "+", "name", "+", "'='", "+", "String", "(", "val", ")", ";", "}", "obj", "[", "name", "]", "=", "val", ";", "return", "true", ";", "}", "else", "{", "throw", "name", "+", "' is not defined in this struct'", ";", "}", "}" ]
Set value. Check property name if defined and type is matched in advance.
[ "Set", "value", ".", "Check", "property", "name", "if", "defined", "and", "type", "is", "matched", "in", "advance", "." ]
8c5876f58e8b1e721e9e0e3d9ff06ba02e1dd9e5
https://github.com/hagino3000/Struct.js/blob/8c5876f58e8b1e721e9e0e3d9ff06ba02e1dd9e5/struct.js#L223-L253
44,616
hagino3000/Struct.js
struct.js
createFake
function createFake(name, obj) { obj = obj || {}; // Only add property for type check. Object.defineProperty(obj, STRUCT_NAME_KEY, { value: name, wriatble: false, enumerable: false }); return obj; }
javascript
function createFake(name, obj) { obj = obj || {}; // Only add property for type check. Object.defineProperty(obj, STRUCT_NAME_KEY, { value: name, wriatble: false, enumerable: false }); return obj; }
[ "function", "createFake", "(", "name", ",", "obj", ")", "{", "obj", "=", "obj", "||", "{", "}", ";", "// Only add property for type check.", "Object", ".", "defineProperty", "(", "obj", ",", "STRUCT_NAME_KEY", ",", "{", "value", ":", "name", ",", "wriatble", ":", "false", ",", "enumerable", ":", "false", "}", ")", ";", "return", "obj", ";", "}" ]
For no-check mode. @param {String} name Struct name. @param {Object} obj Base object (option). @return {Object} Fake struct object.
[ "For", "no", "-", "check", "mode", "." ]
8c5876f58e8b1e721e9e0e3d9ff06ba02e1dd9e5
https://github.com/hagino3000/Struct.js/blob/8c5876f58e8b1e721e9e0e3d9ff06ba02e1dd9e5/struct.js#L430-L440
44,617
vadr-vr/VR-Analytics-JSCore
js/userData.js
getUserDictionary
function getUserDictionary(){ const userDict = {}; if (!userId){ userDict['userId'] = deviceData.getDeviceId(); } else { userDict['userId'] = userId; } for (let key in extraInfo){ userDict[key] = extraInfo[key]; } return userDict; }
javascript
function getUserDictionary(){ const userDict = {}; if (!userId){ userDict['userId'] = deviceData.getDeviceId(); } else { userDict['userId'] = userId; } for (let key in extraInfo){ userDict[key] = extraInfo[key]; } return userDict; }
[ "function", "getUserDictionary", "(", ")", "{", "const", "userDict", "=", "{", "}", ";", "if", "(", "!", "userId", ")", "{", "userDict", "[", "'userId'", "]", "=", "deviceData", ".", "getDeviceId", "(", ")", ";", "}", "else", "{", "userDict", "[", "'userId'", "]", "=", "userId", ";", "}", "for", "(", "let", "key", "in", "extraInfo", ")", "{", "userDict", "[", "key", "]", "=", "extraInfo", "[", "key", "]", ";", "}", "return", "userDict", ";", "}" ]
Used to get all the user details in a dictionary format @memberof User @returns {dictionary} dictionary
[ "Used", "to", "get", "all", "the", "user", "details", "in", "a", "dictionary", "format" ]
7e4a493c824c2c1716360dcb6a3bfecfede5df3b
https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/userData.js#L87-L109
44,618
librpc/web
dist/web-rpc.js
peekTransferables
function peekTransferables (data, result) { if ( result === void 0 ) result = []; if (isTransferable(data)) { result.push(data); } else if (isObject(data)) { for (var i in data) { peekTransferables(data[i], result); } } return result }
javascript
function peekTransferables (data, result) { if ( result === void 0 ) result = []; if (isTransferable(data)) { result.push(data); } else if (isObject(data)) { for (var i in data) { peekTransferables(data[i], result); } } return result }
[ "function", "peekTransferables", "(", "data", ",", "result", ")", "{", "if", "(", "result", "===", "void", "0", ")", "result", "=", "[", "]", ";", "if", "(", "isTransferable", "(", "data", ")", ")", "{", "result", ".", "push", "(", "data", ")", ";", "}", "else", "if", "(", "isObject", "(", "data", ")", ")", "{", "for", "(", "var", "i", "in", "data", ")", "{", "peekTransferables", "(", "data", "[", "i", "]", ",", "result", ")", ";", "}", "}", "return", "result", "}" ]
Recursively peek transferables from passed data @param {*} data Data source @param {Array} [result=[]] Dist array @return {ArrayBuffer[]} List of transferables objects
[ "Recursively", "peek", "transferables", "from", "passed", "data" ]
9103512ad0574373ced19d361ae487e8ac8386ca
https://github.com/librpc/web/blob/9103512ad0574373ced19d361ae487e8ac8386ca/dist/web-rpc.js#L103-L114
44,619
chapmanu/hb
lib/services/facebook/stream.js
function(service, credentials, accounts, keywords) { Stream.call(this, service, credentials, accounts, keywords); // Initialize FBGraph fbgraph.setAccessToken(credentials.access_token); // Set api endpoint URL for subscriber this.api_endpoint = 'https://graph.facebook.com/'+ credentials.app_id +'/subscriptions/'; // Initialize subscriber object this.subscriber = new Subscriber(credentials, this.callback_url(), this.api_endpoint); // Initialize responder this.responder = new Responder(); // Start listening for incoming process.nextTick(function() { this.delegateResponder(); }.bind(this)); }
javascript
function(service, credentials, accounts, keywords) { Stream.call(this, service, credentials, accounts, keywords); // Initialize FBGraph fbgraph.setAccessToken(credentials.access_token); // Set api endpoint URL for subscriber this.api_endpoint = 'https://graph.facebook.com/'+ credentials.app_id +'/subscriptions/'; // Initialize subscriber object this.subscriber = new Subscriber(credentials, this.callback_url(), this.api_endpoint); // Initialize responder this.responder = new Responder(); // Start listening for incoming process.nextTick(function() { this.delegateResponder(); }.bind(this)); }
[ "function", "(", "service", ",", "credentials", ",", "accounts", ",", "keywords", ")", "{", "Stream", ".", "call", "(", "this", ",", "service", ",", "credentials", ",", "accounts", ",", "keywords", ")", ";", "// Initialize FBGraph", "fbgraph", ".", "setAccessToken", "(", "credentials", ".", "access_token", ")", ";", "// Set api endpoint URL for subscriber", "this", ".", "api_endpoint", "=", "'https://graph.facebook.com/'", "+", "credentials", ".", "app_id", "+", "'/subscriptions/'", ";", "// Initialize subscriber object", "this", ".", "subscriber", "=", "new", "Subscriber", "(", "credentials", ",", "this", ".", "callback_url", "(", ")", ",", "this", ".", "api_endpoint", ")", ";", "// Initialize responder", "this", ".", "responder", "=", "new", "Responder", "(", ")", ";", "// Start listening for incoming", "process", ".", "nextTick", "(", "function", "(", ")", "{", "this", ".", "delegateResponder", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Manages the streaming connection to Facebook @constructor @extends Stream
[ "Manages", "the", "streaming", "connection", "to", "Facebook" ]
5edd8de89c7c5fdffc3df0c627513889220f7d51
https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/services/facebook/stream.js#L15-L35
44,620
briancsparks/serverassist
lib/sa-modules/load-http-server.js
function(key, value) { const key2 = key.toLowerCase().replace(/[^a-z0-9]/ig, ''); res.serverassist.headers[key] = value; res.serverassist.headers2[key2] = value; }
javascript
function(key, value) { const key2 = key.toLowerCase().replace(/[^a-z0-9]/ig, ''); res.serverassist.headers[key] = value; res.serverassist.headers2[key2] = value; }
[ "function", "(", "key", ",", "value", ")", "{", "const", "key2", "=", "key", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "[^a-z0-9]", "/", "ig", ",", "''", ")", ";", "res", ".", "serverassist", ".", "headers", "[", "key", "]", "=", "value", ";", "res", ".", "serverassist", ".", "headers2", "[", "key2", "]", "=", "value", ";", "}" ]
Remember headers that get set on the response. headers2 is a table that can be looked-up much easier
[ "Remember", "headers", "that", "get", "set", "on", "the", "response", ".", "headers2", "is", "a", "table", "that", "can", "be", "looked", "-", "up", "much", "easier" ]
f966832aae287f502cce53a71f5129b962ada8a3
https://github.com/briancsparks/serverassist/blob/f966832aae287f502cce53a71f5129b962ada8a3/lib/sa-modules/load-http-server.js#L149-L153
44,621
linyngfly/omelo-scheduler
lib/schedule.js
setTimer
function setTimer(job){ clearTimeout(timer); timer = setTimeout(excuteJob, job.excuteTime()-Date.now()); }
javascript
function setTimer(job){ clearTimeout(timer); timer = setTimeout(excuteJob, job.excuteTime()-Date.now()); }
[ "function", "setTimer", "(", "job", ")", "{", "clearTimeout", "(", "timer", ")", ";", "timer", "=", "setTimeout", "(", "excuteJob", ",", "job", ".", "excuteTime", "(", ")", "-", "Date", ".", "now", "(", ")", ")", ";", "}" ]
Clear last timeout and schedule the next job, it will automaticly run the job that need to run now @param job The job need to schedule @return void
[ "Clear", "last", "timeout", "and", "schedule", "the", "next", "job", "it", "will", "automaticly", "run", "the", "job", "that", "need", "to", "run", "now" ]
aa7775eb2b8b31160669c8fedccd84e2108797eb
https://github.com/linyngfly/omelo-scheduler/blob/aa7775eb2b8b31160669c8fedccd84e2108797eb/lib/schedule.js#L68-L72
44,622
linyngfly/omelo-scheduler
lib/schedule.js
excuteJob
function excuteJob(){ let job = peekNextJob(); let nextJob; while(!!job && (job.excuteTime()-Date.now())<accuracy){ job.run(); queue.pop(); let nextTime = job.nextTime(); if(nextTime === null){ delete map[job.id]; }else{ queue.offer({id:job.id, time: nextTime}); } job = peekNextJob(); } //If all the job have been canceled if(!job) return; //Run next schedule setTimer(job); }
javascript
function excuteJob(){ let job = peekNextJob(); let nextJob; while(!!job && (job.excuteTime()-Date.now())<accuracy){ job.run(); queue.pop(); let nextTime = job.nextTime(); if(nextTime === null){ delete map[job.id]; }else{ queue.offer({id:job.id, time: nextTime}); } job = peekNextJob(); } //If all the job have been canceled if(!job) return; //Run next schedule setTimer(job); }
[ "function", "excuteJob", "(", ")", "{", "let", "job", "=", "peekNextJob", "(", ")", ";", "let", "nextJob", ";", "while", "(", "!", "!", "job", "&&", "(", "job", ".", "excuteTime", "(", ")", "-", "Date", ".", "now", "(", ")", ")", "<", "accuracy", ")", "{", "job", ".", "run", "(", ")", ";", "queue", ".", "pop", "(", ")", ";", "let", "nextTime", "=", "job", ".", "nextTime", "(", ")", ";", "if", "(", "nextTime", "===", "null", ")", "{", "delete", "map", "[", "job", ".", "id", "]", ";", "}", "else", "{", "queue", ".", "offer", "(", "{", "id", ":", "job", ".", "id", ",", "time", ":", "nextTime", "}", ")", ";", "}", "job", "=", "peekNextJob", "(", ")", ";", "}", "//If all the job have been canceled", "if", "(", "!", "job", ")", "return", ";", "//Run next schedule", "setTimer", "(", "job", ")", ";", "}" ]
The function used to ran the schedule job, and setTimeout for next running job
[ "The", "function", "used", "to", "ran", "the", "schedule", "job", "and", "setTimeout", "for", "next", "running", "job" ]
aa7775eb2b8b31160669c8fedccd84e2108797eb
https://github.com/linyngfly/omelo-scheduler/blob/aa7775eb2b8b31160669c8fedccd84e2108797eb/lib/schedule.js#L77-L101
44,623
linyngfly/omelo-scheduler
lib/schedule.js
peekNextJob
function peekNextJob(){ if(queue.size() <= 0) return null; let job = null; do{ job = map[queue.peek().id]; if(!job) queue.pop(); }while(!job && queue.size() > 0); return (!!job)?job:null; }
javascript
function peekNextJob(){ if(queue.size() <= 0) return null; let job = null; do{ job = map[queue.peek().id]; if(!job) queue.pop(); }while(!job && queue.size() > 0); return (!!job)?job:null; }
[ "function", "peekNextJob", "(", ")", "{", "if", "(", "queue", ".", "size", "(", ")", "<=", "0", ")", "return", "null", ";", "let", "job", "=", "null", ";", "do", "{", "job", "=", "map", "[", "queue", ".", "peek", "(", ")", ".", "id", "]", ";", "if", "(", "!", "job", ")", "queue", ".", "pop", "(", ")", ";", "}", "while", "(", "!", "job", "&&", "queue", ".", "size", "(", ")", ">", "0", ")", ";", "return", "(", "!", "!", "job", ")", "?", "job", ":", "null", ";", "}" ]
Return, but not remove the next valid job @return Next valid job
[ "Return", "but", "not", "remove", "the", "next", "valid", "job" ]
aa7775eb2b8b31160669c8fedccd84e2108797eb
https://github.com/linyngfly/omelo-scheduler/blob/aa7775eb2b8b31160669c8fedccd84e2108797eb/lib/schedule.js#L107-L119
44,624
linyngfly/omelo-scheduler
lib/schedule.js
getNextJob
function getNextJob(){ let job = null; while(!job && queue.size() > 0){ let id = queue.pop().id; job = map[id]; } return (!!job)?job:null; }
javascript
function getNextJob(){ let job = null; while(!job && queue.size() > 0){ let id = queue.pop().id; job = map[id]; } return (!!job)?job:null; }
[ "function", "getNextJob", "(", ")", "{", "let", "job", "=", "null", ";", "while", "(", "!", "job", "&&", "queue", ".", "size", "(", ")", ">", "0", ")", "{", "let", "id", "=", "queue", ".", "pop", "(", ")", ".", "id", ";", "job", "=", "map", "[", "id", "]", ";", "}", "return", "(", "!", "!", "job", ")", "?", "job", ":", "null", ";", "}" ]
Return and remove the next valid job @return Next valid job
[ "Return", "and", "remove", "the", "next", "valid", "job" ]
aa7775eb2b8b31160669c8fedccd84e2108797eb
https://github.com/linyngfly/omelo-scheduler/blob/aa7775eb2b8b31160669c8fedccd84e2108797eb/lib/schedule.js#L125-L134
44,625
Whitebolt/require-extra
src/workspaces.js
_createProxy
function _createProxy(ids, workspaces) { const _workspaces = makeArray(ids).map(id=>{ if (!workspaces.has(id)) workspaces.set(id, {}); return workspaces.get(id); }); return new Proxy(global, { get: function(target, property, receiver) { if (property === 'global') return global; for (let n=0; n<_workspaces.length; n++) { if (property in _workspaces[n]) return Reflect.get(_workspaces[n], property, receiver); } return Reflect.get(target, property, receiver); }, has: function(target, property) { for (let n=0; n<_workspaces.length; n++) { if (property in _workspaces[n]) return true; } return Reflect.has(target, property); }, set: function(target, property, value, receiver) { return Reflect.set(target, property, value, receiver); } }); }
javascript
function _createProxy(ids, workspaces) { const _workspaces = makeArray(ids).map(id=>{ if (!workspaces.has(id)) workspaces.set(id, {}); return workspaces.get(id); }); return new Proxy(global, { get: function(target, property, receiver) { if (property === 'global') return global; for (let n=0; n<_workspaces.length; n++) { if (property in _workspaces[n]) return Reflect.get(_workspaces[n], property, receiver); } return Reflect.get(target, property, receiver); }, has: function(target, property) { for (let n=0; n<_workspaces.length; n++) { if (property in _workspaces[n]) return true; } return Reflect.has(target, property); }, set: function(target, property, value, receiver) { return Reflect.set(target, property, value, receiver); } }); }
[ "function", "_createProxy", "(", "ids", ",", "workspaces", ")", "{", "const", "_workspaces", "=", "makeArray", "(", "ids", ")", ".", "map", "(", "id", "=>", "{", "if", "(", "!", "workspaces", ".", "has", "(", "id", ")", ")", "workspaces", ".", "set", "(", "id", ",", "{", "}", ")", ";", "return", "workspaces", ".", "get", "(", "id", ")", ";", "}", ")", ";", "return", "new", "Proxy", "(", "global", ",", "{", "get", ":", "function", "(", "target", ",", "property", ",", "receiver", ")", "{", "if", "(", "property", "===", "'global'", ")", "return", "global", ";", "for", "(", "let", "n", "=", "0", ";", "n", "<", "_workspaces", ".", "length", ";", "n", "++", ")", "{", "if", "(", "property", "in", "_workspaces", "[", "n", "]", ")", "return", "Reflect", ".", "get", "(", "_workspaces", "[", "n", "]", ",", "property", ",", "receiver", ")", ";", "}", "return", "Reflect", ".", "get", "(", "target", ",", "property", ",", "receiver", ")", ";", "}", ",", "has", ":", "function", "(", "target", ",", "property", ")", "{", "for", "(", "let", "n", "=", "0", ";", "n", "<", "_workspaces", ".", "length", ";", "n", "++", ")", "{", "if", "(", "property", "in", "_workspaces", "[", "n", "]", ")", "return", "true", ";", "}", "return", "Reflect", ".", "has", "(", "target", ",", "property", ")", ";", "}", ",", "set", ":", "function", "(", "target", ",", "property", ",", "value", ",", "receiver", ")", "{", "return", "Reflect", ".", "set", "(", "target", ",", "property", ",", "value", ",", "receiver", ")", ";", "}", "}", ")", ";", "}" ]
Create a Proxy for use a sandbox global. @private @param {Array.<Symbol>} ids The workspaces to apply to the proxy, in order of use. @param {Workspaces} workspaces The workspaces store. @returns {Proxy} The created proxy.
[ "Create", "a", "Proxy", "for", "use", "a", "sandbox", "global", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/workspaces.js#L17-L41
44,626
Whitebolt/require-extra
src/workspaces.js
createLookup
function createLookup(ids) { for (let value of lookup) { if (ids.length === value.length) { let match = true; value.forEach(subItem=>{ if (ids[n] !== subItem) match = false; }); if (match) return value; } } return ids; }
javascript
function createLookup(ids) { for (let value of lookup) { if (ids.length === value.length) { let match = true; value.forEach(subItem=>{ if (ids[n] !== subItem) match = false; }); if (match) return value; } } return ids; }
[ "function", "createLookup", "(", "ids", ")", "{", "for", "(", "let", "value", "of", "lookup", ")", "{", "if", "(", "ids", ".", "length", "===", "value", ".", "length", ")", "{", "let", "match", "=", "true", ";", "value", ".", "forEach", "(", "subItem", "=>", "{", "if", "(", "ids", "[", "n", "]", "!==", "subItem", ")", "match", "=", "false", ";", "}", ")", ";", "if", "(", "match", ")", "return", "value", ";", "}", "}", "return", "ids", ";", "}" ]
Create a unique lookup for the given workspaces array. @param {Array.<Symbol>] ids Workspaces id. @returns {Array.<Symbol>} The lookup value, always the same array for same Symbol collection.
[ "Create", "a", "unique", "lookup", "for", "the", "given", "workspaces", "array", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/workspaces.js#L49-L60
44,627
acornejo/downshow
src/downshow.js
bfsOrder
function bfsOrder(root) { var inqueue = [root], outqueue = []; root._bfs_parent = null; while (inqueue.length > 0) { var elem = inqueue.shift(); outqueue.push(elem); var children = elem.childNodes; var liParent = null; for (var i=0 ; i<children.length; i++) { if (children[i].nodeType == 1) {// element node if (children[i].tagName === 'LI') { liParent = children[i]; } else if ((children[i].tagName === 'UL' || children[i].tagName === 'OL') && liParent) { liParent.appendChild(children[i]); i--; continue; } children[i]._bfs_parent = elem; inqueue.push(children[i]); } } } outqueue.shift(); return outqueue; }
javascript
function bfsOrder(root) { var inqueue = [root], outqueue = []; root._bfs_parent = null; while (inqueue.length > 0) { var elem = inqueue.shift(); outqueue.push(elem); var children = elem.childNodes; var liParent = null; for (var i=0 ; i<children.length; i++) { if (children[i].nodeType == 1) {// element node if (children[i].tagName === 'LI') { liParent = children[i]; } else if ((children[i].tagName === 'UL' || children[i].tagName === 'OL') && liParent) { liParent.appendChild(children[i]); i--; continue; } children[i]._bfs_parent = elem; inqueue.push(children[i]); } } } outqueue.shift(); return outqueue; }
[ "function", "bfsOrder", "(", "root", ")", "{", "var", "inqueue", "=", "[", "root", "]", ",", "outqueue", "=", "[", "]", ";", "root", ".", "_bfs_parent", "=", "null", ";", "while", "(", "inqueue", ".", "length", ">", "0", ")", "{", "var", "elem", "=", "inqueue", ".", "shift", "(", ")", ";", "outqueue", ".", "push", "(", "elem", ")", ";", "var", "children", "=", "elem", ".", "childNodes", ";", "var", "liParent", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "i", "++", ")", "{", "if", "(", "children", "[", "i", "]", ".", "nodeType", "==", "1", ")", "{", "// element node", "if", "(", "children", "[", "i", "]", ".", "tagName", "===", "'LI'", ")", "{", "liParent", "=", "children", "[", "i", "]", ";", "}", "else", "if", "(", "(", "children", "[", "i", "]", ".", "tagName", "===", "'UL'", "||", "children", "[", "i", "]", ".", "tagName", "===", "'OL'", ")", "&&", "liParent", ")", "{", "liParent", ".", "appendChild", "(", "children", "[", "i", "]", ")", ";", "i", "--", ";", "continue", ";", "}", "children", "[", "i", "]", ".", "_bfs_parent", "=", "elem", ";", "inqueue", ".", "push", "(", "children", "[", "i", "]", ")", ";", "}", "}", "}", "outqueue", ".", "shift", "(", ")", ";", "return", "outqueue", ";", "}" ]
Returns every element in root in their bfs traversal order. In the process it transforms any nested lists to conform to the w3c standard, see: http://www.w3.org/wiki/HTML_lists#Nesting_lists
[ "Returns", "every", "element", "in", "root", "in", "their", "bfs", "traversal", "order", "." ]
67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1
https://github.com/acornejo/downshow/blob/67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1/src/downshow.js#L39-L63
44,628
acornejo/downshow
src/downshow.js
prefixBlock
function prefixBlock(prefix, block, skipEmpty) { var lines = block.split('\n'); for (var i =0; i<lines.length; i++) { // Do not prefix empty lines if (lines[i].length === 0 && skipEmpty === true) continue; else lines[i] = prefix + lines[i]; } return lines.join('\n'); }
javascript
function prefixBlock(prefix, block, skipEmpty) { var lines = block.split('\n'); for (var i =0; i<lines.length; i++) { // Do not prefix empty lines if (lines[i].length === 0 && skipEmpty === true) continue; else lines[i] = prefix + lines[i]; } return lines.join('\n'); }
[ "function", "prefixBlock", "(", "prefix", ",", "block", ",", "skipEmpty", ")", "{", "var", "lines", "=", "block", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "// Do not prefix empty lines", "if", "(", "lines", "[", "i", "]", ".", "length", "===", "0", "&&", "skipEmpty", "===", "true", ")", "continue", ";", "else", "lines", "[", "i", "]", "=", "prefix", "+", "lines", "[", "i", "]", ";", "}", "return", "lines", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Add prefix to the beginning of every line in block.
[ "Add", "prefix", "to", "the", "beginning", "of", "every", "line", "in", "block", "." ]
67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1
https://github.com/acornejo/downshow/blob/67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1/src/downshow.js#L82-L92
44,629
acornejo/downshow
src/downshow.js
setContent
function setContent(node, content, prefix, suffix) { if (content.length > 0) { if (prefix && suffix) node._bfs_text = prefix + content + suffix; else node._bfs_text = content; } else node._bfs_text = ''; }
javascript
function setContent(node, content, prefix, suffix) { if (content.length > 0) { if (prefix && suffix) node._bfs_text = prefix + content + suffix; else node._bfs_text = content; } else node._bfs_text = ''; }
[ "function", "setContent", "(", "node", ",", "content", ",", "prefix", ",", "suffix", ")", "{", "if", "(", "content", ".", "length", ">", "0", ")", "{", "if", "(", "prefix", "&&", "suffix", ")", "node", ".", "_bfs_text", "=", "prefix", "+", "content", "+", "suffix", ";", "else", "node", ".", "_bfs_text", "=", "content", ";", "}", "else", "node", ".", "_bfs_text", "=", "''", ";", "}" ]
Set the node's content.
[ "Set", "the", "node", "s", "content", "." ]
67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1
https://github.com/acornejo/downshow/blob/67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1/src/downshow.js#L97-L105
44,630
acornejo/downshow
src/downshow.js
getContent
function getContent(node) { var text = '', atom; for (var i = 0; i<node.childNodes.length; i++) { if (node.childNodes[i].nodeType === 1) { atom = node.childNodes[i]._bfs_text; } else if (node.childNodes[i].nodeType === 3) { atom = node.childNodes[i].data; } else continue; if (text.match(/[\t ]+$/) && atom.match(/^[\t ]+/)) { text = text.replace(/[\t ]+$/,'') + ' ' + atom.replace(/^[\t ]+/, ''); } else { text = text + atom; } } return text; }
javascript
function getContent(node) { var text = '', atom; for (var i = 0; i<node.childNodes.length; i++) { if (node.childNodes[i].nodeType === 1) { atom = node.childNodes[i]._bfs_text; } else if (node.childNodes[i].nodeType === 3) { atom = node.childNodes[i].data; } else continue; if (text.match(/[\t ]+$/) && atom.match(/^[\t ]+/)) { text = text.replace(/[\t ]+$/,'') + ' ' + atom.replace(/^[\t ]+/, ''); } else { text = text + atom; } } return text; }
[ "function", "getContent", "(", "node", ")", "{", "var", "text", "=", "''", ",", "atom", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "node", ".", "childNodes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "node", ".", "childNodes", "[", "i", "]", ".", "nodeType", "===", "1", ")", "{", "atom", "=", "node", ".", "childNodes", "[", "i", "]", ".", "_bfs_text", ";", "}", "else", "if", "(", "node", ".", "childNodes", "[", "i", "]", ".", "nodeType", "===", "3", ")", "{", "atom", "=", "node", ".", "childNodes", "[", "i", "]", ".", "data", ";", "}", "else", "continue", ";", "if", "(", "text", ".", "match", "(", "/", "[\\t ]+$", "/", ")", "&&", "atom", ".", "match", "(", "/", "^[\\t ]+", "/", ")", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "[\\t ]+$", "/", ",", "''", ")", "+", "' '", "+", "atom", ".", "replace", "(", "/", "^[\\t ]+", "/", ",", "''", ")", ";", "}", "else", "{", "text", "=", "text", "+", "atom", ";", "}", "}", "return", "text", ";", "}" ]
Get a node's content.
[ "Get", "a", "node", "s", "content", "." ]
67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1
https://github.com/acornejo/downshow/blob/67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1/src/downshow.js#L110-L126
44,631
acornejo/downshow
src/downshow.js
processNode
function processNode(node) { if (node.tagName === 'P' || node.tagName === 'DIV' || node.tagName === 'UL' || node.tagName === 'OL' || node.tagName === 'PRE') setContent(node, getContent(node), '\n\n', '\n\n'); else if (node.tagName === 'BR') setContent(node, '\n\n'); else if (node.tagName === 'HR') setContent(node, '\n***\n'); else if (node.tagName === 'H1') setContent(node, nltrim(getContent(node)), '\n# ', '\n'); else if (node.tagName === 'H2') setContent(node, nltrim(getContent(node)), '\n## ', '\n'); else if (node.tagName === 'H3') setContent(node, nltrim(getContent(node)), '\n### ', '\n'); else if (node.tagName === 'H4') setContent(node, nltrim(getContent(node)), '\n#### ', '\n'); else if (node.tagName === 'H5') setContent(node, nltrim(getContent(node)), '\n##### ', '\n'); else if (node.tagName === 'H6') setContent(node, nltrim(getContent(node)), '\n###### ', '\n'); else if (node.tagName === 'B' || node.tagName === 'STRONG') setContent(node, nltrim(getContent(node)), '**', '**'); else if (node.tagName === 'I' || node.tagName === 'EM') setContent(node, nltrim(getContent(node)), '_', '_'); else if (node.tagName === 'A') { var href = node.href ? nltrim(node.href) : '', text = nltrim(getContent(node)) || href, title = node.title ? nltrim(node.title) : ''; if (href.length > 0) setContent(node, '[' + text + '](' + href + (title ? ' "' + title + '"' : '') + ')'); else setContent(node, ''); } else if (node.tagName === 'IMG') { var src = node.getAttribute('src') ? nltrim(node.getAttribute('src')) : '', alt = node.alt ? nltrim(node.alt) : '', caption = node.title ? nltrim(node.title) : ''; if (src.length > 0) setContent(node, '![' + alt + '](' + src + (caption ? ' "' + caption + '"' : '') + ')'); else setContent(node, ''); } else if (node.tagName === 'BLOCKQUOTE') { var block_content = getContent(node); if (block_content.length > 0) setContent(node, prefixBlock('> ', block_content), '\n\n', '\n\n'); else setContent(node, ''); } else if (node.tagName === 'CODE') { if (node._bfs_parent.tagName === 'PRE' && node._bfs_parent._bfs_parent !== null) setContent(node, prefixBlock(' ', getContent(node))); else setContent(node, nltrim(getContent(node)), '`', '`'); } else if (node.tagName === 'LI') { var list_content = getContent(node); if (list_content.length > 0) if (node._bfs_parent.tagName === 'OL') setContent(node, trim(prefixBlock(' ', list_content, true)), '1. ', '\n\n'); else setContent(node, trim(prefixBlock(' ', list_content, true)), '- ', '\n\n'); else setContent(node, ''); } else setContent(node, getContent(node)); }
javascript
function processNode(node) { if (node.tagName === 'P' || node.tagName === 'DIV' || node.tagName === 'UL' || node.tagName === 'OL' || node.tagName === 'PRE') setContent(node, getContent(node), '\n\n', '\n\n'); else if (node.tagName === 'BR') setContent(node, '\n\n'); else if (node.tagName === 'HR') setContent(node, '\n***\n'); else if (node.tagName === 'H1') setContent(node, nltrim(getContent(node)), '\n# ', '\n'); else if (node.tagName === 'H2') setContent(node, nltrim(getContent(node)), '\n## ', '\n'); else if (node.tagName === 'H3') setContent(node, nltrim(getContent(node)), '\n### ', '\n'); else if (node.tagName === 'H4') setContent(node, nltrim(getContent(node)), '\n#### ', '\n'); else if (node.tagName === 'H5') setContent(node, nltrim(getContent(node)), '\n##### ', '\n'); else if (node.tagName === 'H6') setContent(node, nltrim(getContent(node)), '\n###### ', '\n'); else if (node.tagName === 'B' || node.tagName === 'STRONG') setContent(node, nltrim(getContent(node)), '**', '**'); else if (node.tagName === 'I' || node.tagName === 'EM') setContent(node, nltrim(getContent(node)), '_', '_'); else if (node.tagName === 'A') { var href = node.href ? nltrim(node.href) : '', text = nltrim(getContent(node)) || href, title = node.title ? nltrim(node.title) : ''; if (href.length > 0) setContent(node, '[' + text + '](' + href + (title ? ' "' + title + '"' : '') + ')'); else setContent(node, ''); } else if (node.tagName === 'IMG') { var src = node.getAttribute('src') ? nltrim(node.getAttribute('src')) : '', alt = node.alt ? nltrim(node.alt) : '', caption = node.title ? nltrim(node.title) : ''; if (src.length > 0) setContent(node, '![' + alt + '](' + src + (caption ? ' "' + caption + '"' : '') + ')'); else setContent(node, ''); } else if (node.tagName === 'BLOCKQUOTE') { var block_content = getContent(node); if (block_content.length > 0) setContent(node, prefixBlock('> ', block_content), '\n\n', '\n\n'); else setContent(node, ''); } else if (node.tagName === 'CODE') { if (node._bfs_parent.tagName === 'PRE' && node._bfs_parent._bfs_parent !== null) setContent(node, prefixBlock(' ', getContent(node))); else setContent(node, nltrim(getContent(node)), '`', '`'); } else if (node.tagName === 'LI') { var list_content = getContent(node); if (list_content.length > 0) if (node._bfs_parent.tagName === 'OL') setContent(node, trim(prefixBlock(' ', list_content, true)), '1. ', '\n\n'); else setContent(node, trim(prefixBlock(' ', list_content, true)), '- ', '\n\n'); else setContent(node, ''); } else setContent(node, getContent(node)); }
[ "function", "processNode", "(", "node", ")", "{", "if", "(", "node", ".", "tagName", "===", "'P'", "||", "node", ".", "tagName", "===", "'DIV'", "||", "node", ".", "tagName", "===", "'UL'", "||", "node", ".", "tagName", "===", "'OL'", "||", "node", ".", "tagName", "===", "'PRE'", ")", "setContent", "(", "node", ",", "getContent", "(", "node", ")", ",", "'\\n\\n'", ",", "'\\n\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'BR'", ")", "setContent", "(", "node", ",", "'\\n\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'HR'", ")", "setContent", "(", "node", ",", "'\\n***\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'H1'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'\\n# '", ",", "'\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'H2'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'\\n## '", ",", "'\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'H3'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'\\n### '", ",", "'\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'H4'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'\\n#### '", ",", "'\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'H5'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'\\n##### '", ",", "'\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'H6'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'\\n###### '", ",", "'\\n'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'B'", "||", "node", ".", "tagName", "===", "'STRONG'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'**'", ",", "'**'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'I'", "||", "node", ".", "tagName", "===", "'EM'", ")", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'_'", ",", "'_'", ")", ";", "else", "if", "(", "node", ".", "tagName", "===", "'A'", ")", "{", "var", "href", "=", "node", ".", "href", "?", "nltrim", "(", "node", ".", "href", ")", ":", "''", ",", "text", "=", "nltrim", "(", "getContent", "(", "node", ")", ")", "||", "href", ",", "title", "=", "node", ".", "title", "?", "nltrim", "(", "node", ".", "title", ")", ":", "''", ";", "if", "(", "href", ".", "length", ">", "0", ")", "setContent", "(", "node", ",", "'['", "+", "text", "+", "']('", "+", "href", "+", "(", "title", "?", "' \"'", "+", "title", "+", "'\"'", ":", "''", ")", "+", "')'", ")", ";", "else", "setContent", "(", "node", ",", "''", ")", ";", "}", "else", "if", "(", "node", ".", "tagName", "===", "'IMG'", ")", "{", "var", "src", "=", "node", ".", "getAttribute", "(", "'src'", ")", "?", "nltrim", "(", "node", ".", "getAttribute", "(", "'src'", ")", ")", ":", "''", ",", "alt", "=", "node", ".", "alt", "?", "nltrim", "(", "node", ".", "alt", ")", ":", "''", ",", "caption", "=", "node", ".", "title", "?", "nltrim", "(", "node", ".", "title", ")", ":", "''", ";", "if", "(", "src", ".", "length", ">", "0", ")", "setContent", "(", "node", ",", "'!['", "+", "alt", "+", "']('", "+", "src", "+", "(", "caption", "?", "' \"'", "+", "caption", "+", "'\"'", ":", "''", ")", "+", "')'", ")", ";", "else", "setContent", "(", "node", ",", "''", ")", ";", "}", "else", "if", "(", "node", ".", "tagName", "===", "'BLOCKQUOTE'", ")", "{", "var", "block_content", "=", "getContent", "(", "node", ")", ";", "if", "(", "block_content", ".", "length", ">", "0", ")", "setContent", "(", "node", ",", "prefixBlock", "(", "'> '", ",", "block_content", ")", ",", "'\\n\\n'", ",", "'\\n\\n'", ")", ";", "else", "setContent", "(", "node", ",", "''", ")", ";", "}", "else", "if", "(", "node", ".", "tagName", "===", "'CODE'", ")", "{", "if", "(", "node", ".", "_bfs_parent", ".", "tagName", "===", "'PRE'", "&&", "node", ".", "_bfs_parent", ".", "_bfs_parent", "!==", "null", ")", "setContent", "(", "node", ",", "prefixBlock", "(", "' '", ",", "getContent", "(", "node", ")", ")", ")", ";", "else", "setContent", "(", "node", ",", "nltrim", "(", "getContent", "(", "node", ")", ")", ",", "'`'", ",", "'`'", ")", ";", "}", "else", "if", "(", "node", ".", "tagName", "===", "'LI'", ")", "{", "var", "list_content", "=", "getContent", "(", "node", ")", ";", "if", "(", "list_content", ".", "length", ">", "0", ")", "if", "(", "node", ".", "_bfs_parent", ".", "tagName", "===", "'OL'", ")", "setContent", "(", "node", ",", "trim", "(", "prefixBlock", "(", "' '", ",", "list_content", ",", "true", ")", ")", ",", "'1. '", ",", "'\\n\\n'", ")", ";", "else", "setContent", "(", "node", ",", "trim", "(", "prefixBlock", "(", "' '", ",", "list_content", ",", "true", ")", ")", ",", "'- '", ",", "'\\n\\n'", ")", ";", "else", "setContent", "(", "node", ",", "''", ")", ";", "}", "else", "setContent", "(", "node", ",", "getContent", "(", "node", ")", ")", ";", "}" ]
Process a node in the DOM tree.
[ "Process", "a", "node", "in", "the", "DOM", "tree", "." ]
67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1
https://github.com/acornejo/downshow/blob/67cd83e7e9068666e4edb1c0b9ba171e0e1c1ad1/src/downshow.js#L131-L188
44,632
nodejitsu/contour
pagelets/nodejitsu/login/base.js
initialize
function initialize() { var hash = window.location.hash.match(/^\#?\/([^\/]+)?\/?$/) , self = this; // // The login form is in the DOM by default so it can leverage // browser password saving features. // this.content = $('section.modal').get('innerHTML'); if (hash && hash[1] === 'login') setTimeout(function check() { if (Cortex.app('modal')) return self.render('login'); setTimeout(check, 100); }, 100); }
javascript
function initialize() { var hash = window.location.hash.match(/^\#?\/([^\/]+)?\/?$/) , self = this; // // The login form is in the DOM by default so it can leverage // browser password saving features. // this.content = $('section.modal').get('innerHTML'); if (hash && hash[1] === 'login') setTimeout(function check() { if (Cortex.app('modal')) return self.render('login'); setTimeout(check, 100); }, 100); }
[ "function", "initialize", "(", ")", "{", "var", "hash", "=", "window", ".", "location", ".", "hash", ".", "match", "(", "/", "^\\#?\\/([^\\/]+)?\\/?$", "/", ")", ",", "self", "=", "this", ";", "//", "// The login form is in the DOM by default so it can leverage", "// browser password saving features.", "//", "this", ".", "content", "=", "$", "(", "'section.modal'", ")", ".", "get", "(", "'innerHTML'", ")", ";", "if", "(", "hash", "&&", "hash", "[", "1", "]", "===", "'login'", ")", "setTimeout", "(", "function", "check", "(", ")", "{", "if", "(", "Cortex", ".", "app", "(", "'modal'", ")", ")", "return", "self", ".", "render", "(", "'login'", ")", ";", "setTimeout", "(", "check", ",", "100", ")", ";", "}", ",", "100", ")", ";", "}" ]
Initialize called by the constructor on load. @api private
[ "Initialize", "called", "by", "the", "constructor", "on", "load", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/login/base.js#L33-L48
44,633
nodejitsu/contour
pagelets/nodejitsu/login/base.js
modal
function modal(e) { e.preventDefault(); // Remove the old listeners so we don't trigger the regular validation Cortex.app('modal').off('done'); var self = this; self.redirect = $(e.element).get('data-redirect'); if (!this.restore) this.restore = Cortex.app('modal').on('close', function () { // The modal is closed, make sure that we still have a login state // present or restore it with our cached content. var modal = $('section.modal'); if (~modal.get('innerHTML').indexOf('type="password"')) return; modal.set('innerHTML', self.content); }); return this.render('login'); }
javascript
function modal(e) { e.preventDefault(); // Remove the old listeners so we don't trigger the regular validation Cortex.app('modal').off('done'); var self = this; self.redirect = $(e.element).get('data-redirect'); if (!this.restore) this.restore = Cortex.app('modal').on('close', function () { // The modal is closed, make sure that we still have a login state // present or restore it with our cached content. var modal = $('section.modal'); if (~modal.get('innerHTML').indexOf('type="password"')) return; modal.set('innerHTML', self.content); }); return this.render('login'); }
[ "function", "modal", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "// Remove the old listeners so we don't trigger the regular validation", "Cortex", ".", "app", "(", "'modal'", ")", ".", "off", "(", "'done'", ")", ";", "var", "self", "=", "this", ";", "self", ".", "redirect", "=", "$", "(", "e", ".", "element", ")", ".", "get", "(", "'data-redirect'", ")", ";", "if", "(", "!", "this", ".", "restore", ")", "this", ".", "restore", "=", "Cortex", ".", "app", "(", "'modal'", ")", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "// The modal is closed, make sure that we still have a login state", "// present or restore it with our cached content.", "var", "modal", "=", "$", "(", "'section.modal'", ")", ";", "if", "(", "~", "modal", ".", "get", "(", "'innerHTML'", ")", ".", "indexOf", "(", "'type=\"password\"'", ")", ")", "return", ";", "modal", ".", "set", "(", "'innerHTML'", ",", "self", ".", "content", ")", ";", "}", ")", ";", "return", "this", ".", "render", "(", "'login'", ")", ";", "}" ]
Open the Login modal @param {Event} e @api private
[ "Open", "the", "Login", "modal" ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/login/base.js#L56-L75
44,634
nodejitsu/contour
pagelets/nodejitsu/login/base.js
forgotten
function forgotten() { var self = this , username = $('.modal input[name="username"]') , button = $('.modal button[type="submit"]'); // Add an disabled state to the button as we are processing it button.addClass('disabled loading') .set('disabled', 'disabled') .set('innerHTML', 'Submitting'); username = username.set('readOnly', true).get('value'); Cortex.request({ url: '/forgot' , method: 'post' , type: 'json' , data: { username: username } , success: function success(res) { if (res.error) { return self.render('forgot', { error: 'Invalid user account' , username: username }); } return self.render('forgot', { success: 'We have sent an password reset request to your e-mail address' , username: username }); } }); }
javascript
function forgotten() { var self = this , username = $('.modal input[name="username"]') , button = $('.modal button[type="submit"]'); // Add an disabled state to the button as we are processing it button.addClass('disabled loading') .set('disabled', 'disabled') .set('innerHTML', 'Submitting'); username = username.set('readOnly', true).get('value'); Cortex.request({ url: '/forgot' , method: 'post' , type: 'json' , data: { username: username } , success: function success(res) { if (res.error) { return self.render('forgot', { error: 'Invalid user account' , username: username }); } return self.render('forgot', { success: 'We have sent an password reset request to your e-mail address' , username: username }); } }); }
[ "function", "forgotten", "(", ")", "{", "var", "self", "=", "this", ",", "username", "=", "$", "(", "'.modal input[name=\"username\"]'", ")", ",", "button", "=", "$", "(", "'.modal button[type=\"submit\"]'", ")", ";", "// Add an disabled state to the button as we are processing it", "button", ".", "addClass", "(", "'disabled loading'", ")", ".", "set", "(", "'disabled'", ",", "'disabled'", ")", ".", "set", "(", "'innerHTML'", ",", "'Submitting'", ")", ";", "username", "=", "username", ".", "set", "(", "'readOnly'", ",", "true", ")", ".", "get", "(", "'value'", ")", ";", "Cortex", ".", "request", "(", "{", "url", ":", "'/forgot'", ",", "method", ":", "'post'", ",", "type", ":", "'json'", ",", "data", ":", "{", "username", ":", "username", "}", ",", "success", ":", "function", "success", "(", "res", ")", "{", "if", "(", "res", ".", "error", ")", "{", "return", "self", ".", "render", "(", "'forgot'", ",", "{", "error", ":", "'Invalid user account'", ",", "username", ":", "username", "}", ")", ";", "}", "return", "self", ".", "render", "(", "'forgot'", ",", "{", "success", ":", "'We have sent an password reset request to your e-mail address'", ",", "username", ":", "username", "}", ")", ";", "}", "}", ")", ";", "}" ]
The user requested a password forget. @api public
[ "The", "user", "requested", "a", "password", "forget", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/login/base.js#L96-L129
44,635
nodejitsu/contour
pagelets/nodejitsu/login/base.js
validate
function validate(closed) { if (closed) return; var username = $('.modal input[name="username"]') , password = $('.modal input[name="password"]') , button = $('.modal button[type="submit"]') , self = this; // Add an disabled state to the button as we are processing it button.addClass('disabled loading') .set('disabled', 'disabled') .set('innerHTML', 'Logging in'); username = username.set('readOnly', true).get('value'); password = password.set('readOnly', true).get('value'); // Show the spinner. $('.modal .close').addClass('gone'); $('.modal .spinner').removeClass('gone'); Cortex.request({ url: '/signin/verify' , method: 'post' , type: 'json' , data: { username: username , password: password } , success: function success(res) { if (res.status === 'error') return self.render('login', { error: res.message , username: username , password: password }); $('.modal form').plain(0).submit(); } }); return this; }
javascript
function validate(closed) { if (closed) return; var username = $('.modal input[name="username"]') , password = $('.modal input[name="password"]') , button = $('.modal button[type="submit"]') , self = this; // Add an disabled state to the button as we are processing it button.addClass('disabled loading') .set('disabled', 'disabled') .set('innerHTML', 'Logging in'); username = username.set('readOnly', true).get('value'); password = password.set('readOnly', true).get('value'); // Show the spinner. $('.modal .close').addClass('gone'); $('.modal .spinner').removeClass('gone'); Cortex.request({ url: '/signin/verify' , method: 'post' , type: 'json' , data: { username: username , password: password } , success: function success(res) { if (res.status === 'error') return self.render('login', { error: res.message , username: username , password: password }); $('.modal form').plain(0).submit(); } }); return this; }
[ "function", "validate", "(", "closed", ")", "{", "if", "(", "closed", ")", "return", ";", "var", "username", "=", "$", "(", "'.modal input[name=\"username\"]'", ")", ",", "password", "=", "$", "(", "'.modal input[name=\"password\"]'", ")", ",", "button", "=", "$", "(", "'.modal button[type=\"submit\"]'", ")", ",", "self", "=", "this", ";", "// Add an disabled state to the button as we are processing it", "button", ".", "addClass", "(", "'disabled loading'", ")", ".", "set", "(", "'disabled'", ",", "'disabled'", ")", ".", "set", "(", "'innerHTML'", ",", "'Logging in'", ")", ";", "username", "=", "username", ".", "set", "(", "'readOnly'", ",", "true", ")", ".", "get", "(", "'value'", ")", ";", "password", "=", "password", ".", "set", "(", "'readOnly'", ",", "true", ")", ".", "get", "(", "'value'", ")", ";", "// Show the spinner.", "$", "(", "'.modal .close'", ")", ".", "addClass", "(", "'gone'", ")", ";", "$", "(", "'.modal .spinner'", ")", ".", "removeClass", "(", "'gone'", ")", ";", "Cortex", ".", "request", "(", "{", "url", ":", "'/signin/verify'", ",", "method", ":", "'post'", ",", "type", ":", "'json'", ",", "data", ":", "{", "username", ":", "username", ",", "password", ":", "password", "}", ",", "success", ":", "function", "success", "(", "res", ")", "{", "if", "(", "res", ".", "status", "===", "'error'", ")", "return", "self", ".", "render", "(", "'login'", ",", "{", "error", ":", "res", ".", "message", ",", "username", ":", "username", ",", "password", ":", "password", "}", ")", ";", "$", "(", "'.modal form'", ")", ".", "plain", "(", "0", ")", ".", "submit", "(", ")", ";", "}", "}", ")", ";", "return", "this", ";", "}" ]
Validate the login credentials. @param {Boolean} closed the user closed modal @api private
[ "Validate", "the", "login", "credentials", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/login/base.js#L137-L177
44,636
nodejitsu/contour
pagelets/nodejitsu/login/base.js
render
function render(name, data) { var template; if (name !== 'login') { template = this.template(name, data || {}); template.where('name').is('username').use('username').as('value'); template.where('name').is('password').use('password').as('value'); if (data && data.error) { template.className('error').use('error'); } else { template.className('error').remove(); } if (data && data.success) { template.className('success').use('success'); } else { template.className('success').remove(); } } else if (data && data.error) { // Hide the spinner and show the close button. $('.modal .close').removeClass('gone'); $('.modal .spinner').addClass('gone'); // Login request, but with data.. so the login failed $('.modal input[name="username"], .modal input[name="password"]').set( 'readOnly', false ); $('.modal button[type="submit"]') .removeClass('disabled loading') .set('innerHTML', 'Log in') .set('disabled', ''); $('.modal .error').removeClass('gone').set('innerHTML', data.error); } Cortex.app('modal') .render(template) .once('done', this.close.bind(this, name)); // // Check if we need to create a hidden input field with a redirect directive. // if (this.redirect) { $('.modal form input[name="redirect"]').set('value', this.redirect); } return this; }
javascript
function render(name, data) { var template; if (name !== 'login') { template = this.template(name, data || {}); template.where('name').is('username').use('username').as('value'); template.where('name').is('password').use('password').as('value'); if (data && data.error) { template.className('error').use('error'); } else { template.className('error').remove(); } if (data && data.success) { template.className('success').use('success'); } else { template.className('success').remove(); } } else if (data && data.error) { // Hide the spinner and show the close button. $('.modal .close').removeClass('gone'); $('.modal .spinner').addClass('gone'); // Login request, but with data.. so the login failed $('.modal input[name="username"], .modal input[name="password"]').set( 'readOnly', false ); $('.modal button[type="submit"]') .removeClass('disabled loading') .set('innerHTML', 'Log in') .set('disabled', ''); $('.modal .error').removeClass('gone').set('innerHTML', data.error); } Cortex.app('modal') .render(template) .once('done', this.close.bind(this, name)); // // Check if we need to create a hidden input field with a redirect directive. // if (this.redirect) { $('.modal form input[name="redirect"]').set('value', this.redirect); } return this; }
[ "function", "render", "(", "name", ",", "data", ")", "{", "var", "template", ";", "if", "(", "name", "!==", "'login'", ")", "{", "template", "=", "this", ".", "template", "(", "name", ",", "data", "||", "{", "}", ")", ";", "template", ".", "where", "(", "'name'", ")", ".", "is", "(", "'username'", ")", ".", "use", "(", "'username'", ")", ".", "as", "(", "'value'", ")", ";", "template", ".", "where", "(", "'name'", ")", ".", "is", "(", "'password'", ")", ".", "use", "(", "'password'", ")", ".", "as", "(", "'value'", ")", ";", "if", "(", "data", "&&", "data", ".", "error", ")", "{", "template", ".", "className", "(", "'error'", ")", ".", "use", "(", "'error'", ")", ";", "}", "else", "{", "template", ".", "className", "(", "'error'", ")", ".", "remove", "(", ")", ";", "}", "if", "(", "data", "&&", "data", ".", "success", ")", "{", "template", ".", "className", "(", "'success'", ")", ".", "use", "(", "'success'", ")", ";", "}", "else", "{", "template", ".", "className", "(", "'success'", ")", ".", "remove", "(", ")", ";", "}", "}", "else", "if", "(", "data", "&&", "data", ".", "error", ")", "{", "// Hide the spinner and show the close button.", "$", "(", "'.modal .close'", ")", ".", "removeClass", "(", "'gone'", ")", ";", "$", "(", "'.modal .spinner'", ")", ".", "addClass", "(", "'gone'", ")", ";", "// Login request, but with data.. so the login failed", "$", "(", "'.modal input[name=\"username\"], .modal input[name=\"password\"]'", ")", ".", "set", "(", "'readOnly'", ",", "false", ")", ";", "$", "(", "'.modal button[type=\"submit\"]'", ")", ".", "removeClass", "(", "'disabled loading'", ")", ".", "set", "(", "'innerHTML'", ",", "'Log in'", ")", ".", "set", "(", "'disabled'", ",", "''", ")", ";", "$", "(", "'.modal .error'", ")", ".", "removeClass", "(", "'gone'", ")", ".", "set", "(", "'innerHTML'", ",", "data", ".", "error", ")", ";", "}", "Cortex", ".", "app", "(", "'modal'", ")", ".", "render", "(", "template", ")", ".", "once", "(", "'done'", ",", "this", ".", "close", ".", "bind", "(", "this", ",", "name", ")", ")", ";", "//", "// Check if we need to create a hidden input field with a redirect directive.", "//", "if", "(", "this", ".", "redirect", ")", "{", "$", "(", "'.modal form input[name=\"redirect\"]'", ")", ".", "set", "(", "'value'", ",", "this", ".", "redirect", ")", ";", "}", "return", "this", ";", "}" ]
Render a new Modal window where the user can log his stuff @param {Object} data @api public
[ "Render", "a", "new", "Modal", "window", "where", "the", "user", "can", "log", "his", "stuff" ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/login/base.js#L201-L252
44,637
odogono/elsinore-js
src/query/pluck.js
commandPluck
function commandPluck(context, componentIDs, attributes, options) { // resolve the components to ids let result; let entitySet; // if( true ){ log.debug('pluck> ' + stringify(_.rest(arguments))); } attributes = context.valueOf(attributes, true); attributes = Array.isArray(attributes) ? attributes : [attributes]; options = context.valueOf(options, true); entitySet = context.resolveEntitySet(); // resolve the component ids // componentIDs = context.valueOf(componentIDs,true); // if( componentIDs ){ // componentIDs = context.registry.getIID( componentIDs, true ); // } result = pluckEntitySet( context.registry, entitySet, componentIDs, attributes ); if (options && options.unique) { result = arrayUnique(result); } return context.last = [VALUE, result]; }
javascript
function commandPluck(context, componentIDs, attributes, options) { // resolve the components to ids let result; let entitySet; // if( true ){ log.debug('pluck> ' + stringify(_.rest(arguments))); } attributes = context.valueOf(attributes, true); attributes = Array.isArray(attributes) ? attributes : [attributes]; options = context.valueOf(options, true); entitySet = context.resolveEntitySet(); // resolve the component ids // componentIDs = context.valueOf(componentIDs,true); // if( componentIDs ){ // componentIDs = context.registry.getIID( componentIDs, true ); // } result = pluckEntitySet( context.registry, entitySet, componentIDs, attributes ); if (options && options.unique) { result = arrayUnique(result); } return context.last = [VALUE, result]; }
[ "function", "commandPluck", "(", "context", ",", "componentIDs", ",", "attributes", ",", "options", ")", "{", "// resolve the components to ids", "let", "result", ";", "let", "entitySet", ";", "// if( true ){ log.debug('pluck> ' + stringify(_.rest(arguments))); }", "attributes", "=", "context", ".", "valueOf", "(", "attributes", ",", "true", ")", ";", "attributes", "=", "Array", ".", "isArray", "(", "attributes", ")", "?", "attributes", ":", "[", "attributes", "]", ";", "options", "=", "context", ".", "valueOf", "(", "options", ",", "true", ")", ";", "entitySet", "=", "context", ".", "resolveEntitySet", "(", ")", ";", "// resolve the component ids", "// componentIDs = context.valueOf(componentIDs,true);", "// if( componentIDs ){", "// componentIDs = context.registry.getIID( componentIDs, true );", "// }", "result", "=", "pluckEntitySet", "(", "context", ".", "registry", ",", "entitySet", ",", "componentIDs", ",", "attributes", ")", ";", "if", "(", "options", "&&", "options", ".", "unique", ")", "{", "result", "=", "arrayUnique", "(", "result", ")", ";", "}", "return", "context", ".", "last", "=", "[", "VALUE", ",", "result", "]", ";", "}" ]
Returns the attribute values of specified components in the specified entitySet
[ "Returns", "the", "attribute", "values", "of", "specified", "components", "in", "the", "specified", "entitySet" ]
1ecce67ad0022646419a740def029b1ba92dd558
https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/query/pluck.js#L48-L79
44,638
vanetix/waterline-errors
lib/index.js
expose
function expose(anchor, name, message) { Object.defineProperty(errors[anchor], name, { enumerable: true, get: function() { var err = new Error(); err.name = capitalize(anchor) + 'Error'; err.message = message; Error.captureStackTrace(err, arguments.callee); return err; } }); }
javascript
function expose(anchor, name, message) { Object.defineProperty(errors[anchor], name, { enumerable: true, get: function() { var err = new Error(); err.name = capitalize(anchor) + 'Error'; err.message = message; Error.captureStackTrace(err, arguments.callee); return err; } }); }
[ "function", "expose", "(", "anchor", ",", "name", ",", "message", ")", "{", "Object", ".", "defineProperty", "(", "errors", "[", "anchor", "]", ",", "name", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "var", "err", "=", "new", "Error", "(", ")", ";", "err", ".", "name", "=", "capitalize", "(", "anchor", ")", "+", "'Error'", ";", "err", ".", "message", "=", "message", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "arguments", ".", "callee", ")", ";", "return", "err", ";", "}", "}", ")", ";", "}" ]
Helper function for exposing errors, also edits the stack trace to remove itself. @param {Object} anchor @param {String} name @param {String} message
[ "Helper", "function", "for", "exposing", "errors", "also", "edits", "the", "stack", "trace", "to", "remove", "itself", "." ]
274319a0418dc42e0f0b182e3d1085bb20469c04
https://github.com/vanetix/waterline-errors/blob/274319a0418dc42e0f0b182e3d1085bb20469c04/lib/index.js#L36-L48
44,639
jaredhanson/antenna
lib/router.js
Router
function Router() { var self = this; this.arr = []; this.caseSensitive = true; this.strict = false; this.middleware = function router(msg, next) { self._dispatch(msg, next); }; }
javascript
function Router() { var self = this; this.arr = []; this.caseSensitive = true; this.strict = false; this.middleware = function router(msg, next) { self._dispatch(msg, next); }; }
[ "function", "Router", "(", ")", "{", "var", "self", "=", "this", ";", "this", ".", "arr", "=", "[", "]", ";", "this", ".", "caseSensitive", "=", "true", ";", "this", ".", "strict", "=", "false", ";", "this", ".", "middleware", "=", "function", "router", "(", "msg", ",", "next", ")", "{", "self", ".", "_dispatch", "(", "msg", ",", "next", ")", ";", "}", ";", "}" ]
`Router` constructor. @api protected
[ "Router", "constructor", "." ]
fecfa8320a29d0f1cf22df0230f3b65a12316087
https://github.com/jaredhanson/antenna/blob/fecfa8320a29d0f1cf22df0230f3b65a12316087/lib/router.js#L14-L23
44,640
hufeng/babel-plugin-transform-rn-react-dom
lib/index.js
function(path, state) { if (t.isStringLiteral(path.node.source, { value: 'react-dom' })) { path.node.source = t.StringLiteral('react-native'); } }
javascript
function(path, state) { if (t.isStringLiteral(path.node.source, { value: 'react-dom' })) { path.node.source = t.StringLiteral('react-native'); } }
[ "function", "(", "path", ",", "state", ")", "{", "if", "(", "t", ".", "isStringLiteral", "(", "path", ".", "node", ".", "source", ",", "{", "value", ":", "'react-dom'", "}", ")", ")", "{", "path", ".", "node", ".", "source", "=", "t", ".", "StringLiteral", "(", "'react-native'", ")", ";", "}", "}" ]
import ReactDOM from 'react-dom' => import ReactDOm from 'react-native'
[ "import", "ReactDOM", "from", "react", "-", "dom", "=", ">", "import", "ReactDOm", "from", "react", "-", "native" ]
1024b5cb7b7fd7b458202223787de0300b7eb64f
https://github.com/hufeng/babel-plugin-transform-rn-react-dom/blob/1024b5cb7b7fd7b458202223787de0300b7eb64f/lib/index.js#L21-L25
44,641
vid/SenseBase
lib/apis/bing.js
checkApiKey
function checkApiKey(key) { if (!GLOBAL.config.apis || !GLOBAL.config.apis[key]) { GLOBAL.error('no GLOBAL.config.apis.bing'); return false; } return true; }
javascript
function checkApiKey(key) { if (!GLOBAL.config.apis || !GLOBAL.config.apis[key]) { GLOBAL.error('no GLOBAL.config.apis.bing'); return false; } return true; }
[ "function", "checkApiKey", "(", "key", ")", "{", "if", "(", "!", "GLOBAL", ".", "config", ".", "apis", "||", "!", "GLOBAL", ".", "config", ".", "apis", "[", "key", "]", ")", "{", "GLOBAL", ".", "error", "(", "'no GLOBAL.config.apis.bing'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if an API key exists, return false if not
[ "Check", "if", "an", "API", "key", "exists", "return", "false", "if", "not" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/apis/bing.js#L101-L107
44,642
bosonic-labs/b-datepicker
dist/b-datepicker.js
function(date, preventOnSelect) { if (!date) { this._d = null; return this.draw(); } if (typeof date === 'string') { date = new Date(Date.parse(date)); } if (!isDate(date)) { return; } var min = this._o.minDate, max = this._o.maxDate; if (isDate(min) && date < min) { date = min; } else if (isDate(max) && date > max) { date = max; } this._d = new Date(date.getTime()); setToStartOfDay(this._d); this.gotoDate(this._d); if (this._o.field) { this._o.field.value = this.toString(); fireEvent(this._o.field, 'change', { firedBy: this }); } if (!preventOnSelect && typeof this._o.onSelect === 'function') { this._o.onSelect.call(this, this.getDate()); } }
javascript
function(date, preventOnSelect) { if (!date) { this._d = null; return this.draw(); } if (typeof date === 'string') { date = new Date(Date.parse(date)); } if (!isDate(date)) { return; } var min = this._o.minDate, max = this._o.maxDate; if (isDate(min) && date < min) { date = min; } else if (isDate(max) && date > max) { date = max; } this._d = new Date(date.getTime()); setToStartOfDay(this._d); this.gotoDate(this._d); if (this._o.field) { this._o.field.value = this.toString(); fireEvent(this._o.field, 'change', { firedBy: this }); } if (!preventOnSelect && typeof this._o.onSelect === 'function') { this._o.onSelect.call(this, this.getDate()); } }
[ "function", "(", "date", ",", "preventOnSelect", ")", "{", "if", "(", "!", "date", ")", "{", "this", ".", "_d", "=", "null", ";", "return", "this", ".", "draw", "(", ")", ";", "}", "if", "(", "typeof", "date", "===", "'string'", ")", "{", "date", "=", "new", "Date", "(", "Date", ".", "parse", "(", "date", ")", ")", ";", "}", "if", "(", "!", "isDate", "(", "date", ")", ")", "{", "return", ";", "}", "var", "min", "=", "this", ".", "_o", ".", "minDate", ",", "max", "=", "this", ".", "_o", ".", "maxDate", ";", "if", "(", "isDate", "(", "min", ")", "&&", "date", "<", "min", ")", "{", "date", "=", "min", ";", "}", "else", "if", "(", "isDate", "(", "max", ")", "&&", "date", ">", "max", ")", "{", "date", "=", "max", ";", "}", "this", ".", "_d", "=", "new", "Date", "(", "date", ".", "getTime", "(", ")", ")", ";", "setToStartOfDay", "(", "this", ".", "_d", ")", ";", "this", ".", "gotoDate", "(", "this", ".", "_d", ")", ";", "if", "(", "this", ".", "_o", ".", "field", ")", "{", "this", ".", "_o", ".", "field", ".", "value", "=", "this", ".", "toString", "(", ")", ";", "fireEvent", "(", "this", ".", "_o", ".", "field", ",", "'change'", ",", "{", "firedBy", ":", "this", "}", ")", ";", "}", "if", "(", "!", "preventOnSelect", "&&", "typeof", "this", ".", "_o", ".", "onSelect", "===", "'function'", ")", "{", "this", ".", "_o", ".", "onSelect", ".", "call", "(", "this", ",", "this", ".", "getDate", "(", ")", ")", ";", "}", "}" ]
set the current selection
[ "set", "the", "current", "selection" ]
a15b4cafc04c36a69fca72c5924ed77d0114fc5d
https://github.com/bosonic-labs/b-datepicker/blob/a15b4cafc04c36a69fca72c5924ed77d0114fc5d/dist/b-datepicker.js#L615-L648
44,643
bosonic-labs/b-datepicker
dist/b-datepicker.js
function(date) { if (!isDate(date)) { return; } this._y = date.getFullYear(); this._m = date.getMonth(); this.draw(); }
javascript
function(date) { if (!isDate(date)) { return; } this._y = date.getFullYear(); this._m = date.getMonth(); this.draw(); }
[ "function", "(", "date", ")", "{", "if", "(", "!", "isDate", "(", "date", ")", ")", "{", "return", ";", "}", "this", ".", "_y", "=", "date", ".", "getFullYear", "(", ")", ";", "this", ".", "_m", "=", "date", ".", "getMonth", "(", ")", ";", "this", ".", "draw", "(", ")", ";", "}" ]
change view to a specific date
[ "change", "view", "to", "a", "specific", "date" ]
a15b4cafc04c36a69fca72c5924ed77d0114fc5d
https://github.com/bosonic-labs/b-datepicker/blob/a15b4cafc04c36a69fca72c5924ed77d0114fc5d/dist/b-datepicker.js#L653-L661
44,644
bosonic-labs/b-datepicker
dist/b-datepicker.js
function(force) { if (!this._v && !force) { return; } var opts = this._o, minYear = opts.minYear, maxYear = opts.maxYear, minMonth = opts.minMonth, maxMonth = opts.maxMonth; if (this._y <= minYear) { this._y = minYear; if (!isNaN(minMonth) && this._m < minMonth) { this._m = minMonth; } } if (this._y >= maxYear) { this._y = maxYear; if (!isNaN(maxMonth) && this._m > maxMonth) { this._m = maxMonth; } } this.el.innerHTML = renderTitle(this) + this.render(this._y, this._m); if (opts.bound) { this.adjustPosition(); if(opts.field.type !== 'hidden') { sto(function() { opts.trigger.focus(); }, 1); } } if (typeof this._o.onDraw === 'function') { var self = this; sto(function() { self._o.onDraw.call(self); }, 0); } }
javascript
function(force) { if (!this._v && !force) { return; } var opts = this._o, minYear = opts.minYear, maxYear = opts.maxYear, minMonth = opts.minMonth, maxMonth = opts.maxMonth; if (this._y <= minYear) { this._y = minYear; if (!isNaN(minMonth) && this._m < minMonth) { this._m = minMonth; } } if (this._y >= maxYear) { this._y = maxYear; if (!isNaN(maxMonth) && this._m > maxMonth) { this._m = maxMonth; } } this.el.innerHTML = renderTitle(this) + this.render(this._y, this._m); if (opts.bound) { this.adjustPosition(); if(opts.field.type !== 'hidden') { sto(function() { opts.trigger.focus(); }, 1); } } if (typeof this._o.onDraw === 'function') { var self = this; sto(function() { self._o.onDraw.call(self); }, 0); } }
[ "function", "(", "force", ")", "{", "if", "(", "!", "this", ".", "_v", "&&", "!", "force", ")", "{", "return", ";", "}", "var", "opts", "=", "this", ".", "_o", ",", "minYear", "=", "opts", ".", "minYear", ",", "maxYear", "=", "opts", ".", "maxYear", ",", "minMonth", "=", "opts", ".", "minMonth", ",", "maxMonth", "=", "opts", ".", "maxMonth", ";", "if", "(", "this", ".", "_y", "<=", "minYear", ")", "{", "this", ".", "_y", "=", "minYear", ";", "if", "(", "!", "isNaN", "(", "minMonth", ")", "&&", "this", ".", "_m", "<", "minMonth", ")", "{", "this", ".", "_m", "=", "minMonth", ";", "}", "}", "if", "(", "this", ".", "_y", ">=", "maxYear", ")", "{", "this", ".", "_y", "=", "maxYear", ";", "if", "(", "!", "isNaN", "(", "maxMonth", ")", "&&", "this", ".", "_m", ">", "maxMonth", ")", "{", "this", ".", "_m", "=", "maxMonth", ";", "}", "}", "this", ".", "el", ".", "innerHTML", "=", "renderTitle", "(", "this", ")", "+", "this", ".", "render", "(", "this", ".", "_y", ",", "this", ".", "_m", ")", ";", "if", "(", "opts", ".", "bound", ")", "{", "this", ".", "adjustPosition", "(", ")", ";", "if", "(", "opts", ".", "field", ".", "type", "!==", "'hidden'", ")", "{", "sto", "(", "function", "(", ")", "{", "opts", ".", "trigger", ".", "focus", "(", ")", ";", "}", ",", "1", ")", ";", "}", "}", "if", "(", "typeof", "this", ".", "_o", ".", "onDraw", "===", "'function'", ")", "{", "var", "self", "=", "this", ";", "sto", "(", "function", "(", ")", "{", "self", ".", "_o", ".", "onDraw", ".", "call", "(", "self", ")", ";", "}", ",", "0", ")", ";", "}", "}" ]
refresh the HTML
[ "refresh", "the", "HTML" ]
a15b4cafc04c36a69fca72c5924ed77d0114fc5d
https://github.com/bosonic-labs/b-datepicker/blob/a15b4cafc04c36a69fca72c5924ed77d0114fc5d/dist/b-datepicker.js#L727-L768
44,645
bosonic-labs/b-datepicker
dist/b-datepicker.js
function(year, month) { var opts = this._o, now = new Date(), days = getDaysInMonth(year, month), before = new Date(year, month, 1).getDay(), data = [], row = []; setToStartOfDay(now); if (opts.firstDay > 0) { before -= opts.firstDay; if (before < 0) { before += 7; } } var cells = days + before, after = cells; while(after > 7) { after -= 7; } cells += 7 - after; for (var i = 0, r = 0; i < cells; i++) { var day = new Date(year, month, 1 + (i - before)), isDisabled = (opts.minDate && day < opts.minDate) || (opts.maxDate && day > opts.maxDate), isSelected = isDate(this._d) ? compareDates(day, this._d) : false, isToday = compareDates(day, now), isEmpty = i < before || i >= (days + before); row.push(renderDay(1 + (i - before), isSelected, isToday, isDisabled, isEmpty)); if (++r === 7) { data.push(renderRow(row, opts.isRTL)); row = []; r = 0; } } return renderTable(opts, data); }
javascript
function(year, month) { var opts = this._o, now = new Date(), days = getDaysInMonth(year, month), before = new Date(year, month, 1).getDay(), data = [], row = []; setToStartOfDay(now); if (opts.firstDay > 0) { before -= opts.firstDay; if (before < 0) { before += 7; } } var cells = days + before, after = cells; while(after > 7) { after -= 7; } cells += 7 - after; for (var i = 0, r = 0; i < cells; i++) { var day = new Date(year, month, 1 + (i - before)), isDisabled = (opts.minDate && day < opts.minDate) || (opts.maxDate && day > opts.maxDate), isSelected = isDate(this._d) ? compareDates(day, this._d) : false, isToday = compareDates(day, now), isEmpty = i < before || i >= (days + before); row.push(renderDay(1 + (i - before), isSelected, isToday, isDisabled, isEmpty)); if (++r === 7) { data.push(renderRow(row, opts.isRTL)); row = []; r = 0; } } return renderTable(opts, data); }
[ "function", "(", "year", ",", "month", ")", "{", "var", "opts", "=", "this", ".", "_o", ",", "now", "=", "new", "Date", "(", ")", ",", "days", "=", "getDaysInMonth", "(", "year", ",", "month", ")", ",", "before", "=", "new", "Date", "(", "year", ",", "month", ",", "1", ")", ".", "getDay", "(", ")", ",", "data", "=", "[", "]", ",", "row", "=", "[", "]", ";", "setToStartOfDay", "(", "now", ")", ";", "if", "(", "opts", ".", "firstDay", ">", "0", ")", "{", "before", "-=", "opts", ".", "firstDay", ";", "if", "(", "before", "<", "0", ")", "{", "before", "+=", "7", ";", "}", "}", "var", "cells", "=", "days", "+", "before", ",", "after", "=", "cells", ";", "while", "(", "after", ">", "7", ")", "{", "after", "-=", "7", ";", "}", "cells", "+=", "7", "-", "after", ";", "for", "(", "var", "i", "=", "0", ",", "r", "=", "0", ";", "i", "<", "cells", ";", "i", "++", ")", "{", "var", "day", "=", "new", "Date", "(", "year", ",", "month", ",", "1", "+", "(", "i", "-", "before", ")", ")", ",", "isDisabled", "=", "(", "opts", ".", "minDate", "&&", "day", "<", "opts", ".", "minDate", ")", "||", "(", "opts", ".", "maxDate", "&&", "day", ">", "opts", ".", "maxDate", ")", ",", "isSelected", "=", "isDate", "(", "this", ".", "_d", ")", "?", "compareDates", "(", "day", ",", "this", ".", "_d", ")", ":", "false", ",", "isToday", "=", "compareDates", "(", "day", ",", "now", ")", ",", "isEmpty", "=", "i", "<", "before", "||", "i", ">=", "(", "days", "+", "before", ")", ";", "row", ".", "push", "(", "renderDay", "(", "1", "+", "(", "i", "-", "before", ")", ",", "isSelected", ",", "isToday", ",", "isDisabled", ",", "isEmpty", ")", ")", ";", "if", "(", "++", "r", "===", "7", ")", "{", "data", ".", "push", "(", "renderRow", "(", "row", ",", "opts", ".", "isRTL", ")", ")", ";", "row", "=", "[", "]", ";", "r", "=", "0", ";", "}", "}", "return", "renderTable", "(", "opts", ",", "data", ")", ";", "}" ]
render HTML for a particular month
[ "render", "HTML", "for", "a", "particular", "month" ]
a15b4cafc04c36a69fca72c5924ed77d0114fc5d
https://github.com/bosonic-labs/b-datepicker/blob/a15b4cafc04c36a69fca72c5924ed77d0114fc5d/dist/b-datepicker.js#L819-L857
44,646
odogono/elsinore-js
src/query/alias.js
commandAlias
function commandAlias(context, name) { let value; context.alias = context.alias || {}; value = context.last; name = context.valueOf(name, true); value = context.valueOf(value, true); if (context.debug) { log.debug('cmd alias ' + stringify(name) + ' ' + stringify(value)); } context.alias[name] = value; return (context.last = [VALUE, value]); }
javascript
function commandAlias(context, name) { let value; context.alias = context.alias || {}; value = context.last; name = context.valueOf(name, true); value = context.valueOf(value, true); if (context.debug) { log.debug('cmd alias ' + stringify(name) + ' ' + stringify(value)); } context.alias[name] = value; return (context.last = [VALUE, value]); }
[ "function", "commandAlias", "(", "context", ",", "name", ")", "{", "let", "value", ";", "context", ".", "alias", "=", "context", ".", "alias", "||", "{", "}", ";", "value", "=", "context", ".", "last", ";", "name", "=", "context", ".", "valueOf", "(", "name", ",", "true", ")", ";", "value", "=", "context", ".", "valueOf", "(", "value", ",", "true", ")", ";", "if", "(", "context", ".", "debug", ")", "{", "log", ".", "debug", "(", "'cmd alias '", "+", "stringify", "(", "name", ")", "+", "' '", "+", "stringify", "(", "value", ")", ")", ";", "}", "context", ".", "alias", "[", "name", "]", "=", "value", ";", "return", "(", "context", ".", "last", "=", "[", "VALUE", ",", "value", "]", ")", ";", "}" ]
Stores or retrieves a value with the given name in the context
[ "Stores", "or", "retrieves", "a", "value", "with", "the", "given", "name", "in", "the", "context" ]
1ecce67ad0022646419a740def029b1ba92dd558
https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/query/alias.js#L29-L44
44,647
Knape/triggerhappy
lib/spray.js
caller
function caller(instances, index, options) { // at the moment we are only calling the first event, // but lets start prepare the api for managin an array of events return instances(options).then(function (_ref) { var event = _ref.event, eventName = _ref.eventName; var shouldExit = typeof options.tick === 'function' ? options.tick(event, index) : false; var newIndex = index + 1; // if we havent reached the end of our cycle return a new caller // otherwise just exit the recursive function var eventObj = _eventProps2.default[eventName]; return newIndex >= options.steps || shouldExit ? event : caller(instances, newIndex, Object.assign({}, options, handlePathObj(options.path, event, eventObj, newIndex))); }); }
javascript
function caller(instances, index, options) { // at the moment we are only calling the first event, // but lets start prepare the api for managin an array of events return instances(options).then(function (_ref) { var event = _ref.event, eventName = _ref.eventName; var shouldExit = typeof options.tick === 'function' ? options.tick(event, index) : false; var newIndex = index + 1; // if we havent reached the end of our cycle return a new caller // otherwise just exit the recursive function var eventObj = _eventProps2.default[eventName]; return newIndex >= options.steps || shouldExit ? event : caller(instances, newIndex, Object.assign({}, options, handlePathObj(options.path, event, eventObj, newIndex))); }); }
[ "function", "caller", "(", "instances", ",", "index", ",", "options", ")", "{", "// at the moment we are only calling the first event,", "// but lets start prepare the api for managin an array of events", "return", "instances", "(", "options", ")", ".", "then", "(", "function", "(", "_ref", ")", "{", "var", "event", "=", "_ref", ".", "event", ",", "eventName", "=", "_ref", ".", "eventName", ";", "var", "shouldExit", "=", "typeof", "options", ".", "tick", "===", "'function'", "?", "options", ".", "tick", "(", "event", ",", "index", ")", ":", "false", ";", "var", "newIndex", "=", "index", "+", "1", ";", "// if we havent reached the end of our cycle return a new caller", "// otherwise just exit the recursive function", "var", "eventObj", "=", "_eventProps2", ".", "default", "[", "eventName", "]", ";", "return", "newIndex", ">=", "options", ".", "steps", "||", "shouldExit", "?", "event", ":", "caller", "(", "instances", ",", "newIndex", ",", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "handlePathObj", "(", "options", ".", "path", ",", "event", ",", "eventObj", ",", "newIndex", ")", ")", ")", ";", "}", ")", ";", "}" ]
Recursive function to be called as many times as we defined the steps count @param {Array} instances @param {Integer} index @param {Object} options
[ "Recursive", "function", "to", "be", "called", "as", "many", "times", "as", "we", "defined", "the", "steps", "count" ]
7d470faab8f74004d3b4ba2d27d8006e9203b7f3
https://github.com/Knape/triggerhappy/blob/7d470faab8f74004d3b4ba2d27d8006e9203b7f3/lib/spray.js#L42-L57
44,648
edappy/seneca-context
plugins/setContext.js
setContextPlugin
function setContextPlugin(options) { var seneca = this; var plugin = 'set-context'; options = seneca.util.deepextend({ createContext: createContext, contextHeader: 'x-request-id' }, options); seneca.act({ role: 'web', plugin: plugin, use: processRequest.bind(null, options) }); return {name: plugin}; }
javascript
function setContextPlugin(options) { var seneca = this; var plugin = 'set-context'; options = seneca.util.deepextend({ createContext: createContext, contextHeader: 'x-request-id' }, options); seneca.act({ role: 'web', plugin: plugin, use: processRequest.bind(null, options) }); return {name: plugin}; }
[ "function", "setContextPlugin", "(", "options", ")", "{", "var", "seneca", "=", "this", ";", "var", "plugin", "=", "'set-context'", ";", "options", "=", "seneca", ".", "util", ".", "deepextend", "(", "{", "createContext", ":", "createContext", ",", "contextHeader", ":", "'x-request-id'", "}", ",", "options", ")", ";", "seneca", ".", "act", "(", "{", "role", ":", "'web'", ",", "plugin", ":", "plugin", ",", "use", ":", "processRequest", ".", "bind", "(", "null", ",", "options", ")", "}", ")", ";", "return", "{", "name", ":", "plugin", "}", ";", "}" ]
A seneca plugin, which automatically sets the context for all HTTP requests. @param {{ // A function which creates a context based on the HTTP request and response. // It is used by the `setContextPlugin`. // The `defaultContext` is `{requestId: req.headers[options.contextHeader]}`. // Default is noop. createContext: function (request, response, defaultContext, function(error, context)) // The name of the HTTP request header containing the request context. // Default is 'x-request-id'. contextHeader: string }} options
[ "A", "seneca", "plugin", "which", "automatically", "sets", "the", "context", "for", "all", "HTTP", "requests", "." ]
1e0c8d36c5be4b661b062754c01f064de47873c4
https://github.com/edappy/seneca-context/blob/1e0c8d36c5be4b661b062754c01f064de47873c4/plugins/setContext.js#L23-L39
44,649
edappy/seneca-context
plugins/setContext.js
processRequest
function processRequest(options, req, res, next) { debug('processing HTTP request'); var seneca = req.seneca; options.createContext(req, res, createDefaultContext(options, req), function (error, context) { if (error) { next(error); } else { setContext(seneca, context); next(); } }); }
javascript
function processRequest(options, req, res, next) { debug('processing HTTP request'); var seneca = req.seneca; options.createContext(req, res, createDefaultContext(options, req), function (error, context) { if (error) { next(error); } else { setContext(seneca, context); next(); } }); }
[ "function", "processRequest", "(", "options", ",", "req", ",", "res", ",", "next", ")", "{", "debug", "(", "'processing HTTP request'", ")", ";", "var", "seneca", "=", "req", ".", "seneca", ";", "options", ".", "createContext", "(", "req", ",", "res", ",", "createDefaultContext", "(", "options", ",", "req", ")", ",", "function", "(", "error", ",", "context", ")", "{", "if", "(", "error", ")", "{", "next", "(", "error", ")", ";", "}", "else", "{", "setContext", "(", "seneca", ",", "context", ")", ";", "next", "(", ")", ";", "}", "}", ")", ";", "}" ]
Derives a context from an HTTP request and ensures that it is available to all seneca actions in this transaction.
[ "Derives", "a", "context", "from", "an", "HTTP", "request", "and", "ensures", "that", "it", "is", "available", "to", "all", "seneca", "actions", "in", "this", "transaction", "." ]
1e0c8d36c5be4b661b062754c01f064de47873c4
https://github.com/edappy/seneca-context/blob/1e0c8d36c5be4b661b062754c01f064de47873c4/plugins/setContext.js#L45-L58
44,650
edappy/seneca-context
plugins/setContext.js
createContext
function createContext(req, res, context, done) { debug('default createContext - does nothing', context); process.nextTick(done.bind(null, null, context)); }
javascript
function createContext(req, res, context, done) { debug('default createContext - does nothing', context); process.nextTick(done.bind(null, null, context)); }
[ "function", "createContext", "(", "req", ",", "res", ",", "context", ",", "done", ")", "{", "debug", "(", "'default createContext - does nothing'", ",", "context", ")", ";", "process", ".", "nextTick", "(", "done", ".", "bind", "(", "null", ",", "null", ",", "context", ")", ")", ";", "}" ]
Default implementation of createContext, which responds with the default context.
[ "Default", "implementation", "of", "createContext", "which", "responds", "with", "the", "default", "context", "." ]
1e0c8d36c5be4b661b062754c01f064de47873c4
https://github.com/edappy/seneca-context/blob/1e0c8d36c5be4b661b062754c01f064de47873c4/plugins/setContext.js#L75-L78
44,651
octet-stream/object-deep-from-entries
objectDeepFromEntries.js
objectDeepFromEntries
function objectDeepFromEntries(entries) { if (!isArray(entries)) { throw new TypeError( `Expected an array of entries. Received ${getTag(entries)}` ) } let res = {} let isCollection = false if (hasNumKey(entries)) { res = [] isCollection = true } for (const entry of entries) { let path = entry[0] const value = entry[1] if (!isArray(path)) { path = [path] } const root = path.shift() if (path.length === 0 && (isCollection && isNaN(root))) { res.push({[root]: value}) } else if (path.length === 0) { res[root] = value } else if (isCollection && isNaN(root)) { res.push({[root]: deepFromEntries(res[root], root, path, value)}) } else { res[root] = deepFromEntries(res[root], root, path, value) } } return res }
javascript
function objectDeepFromEntries(entries) { if (!isArray(entries)) { throw new TypeError( `Expected an array of entries. Received ${getTag(entries)}` ) } let res = {} let isCollection = false if (hasNumKey(entries)) { res = [] isCollection = true } for (const entry of entries) { let path = entry[0] const value = entry[1] if (!isArray(path)) { path = [path] } const root = path.shift() if (path.length === 0 && (isCollection && isNaN(root))) { res.push({[root]: value}) } else if (path.length === 0) { res[root] = value } else if (isCollection && isNaN(root)) { res.push({[root]: deepFromEntries(res[root], root, path, value)}) } else { res[root] = deepFromEntries(res[root], root, path, value) } } return res }
[ "function", "objectDeepFromEntries", "(", "entries", ")", "{", "if", "(", "!", "isArray", "(", "entries", ")", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "getTag", "(", "entries", ")", "}", "`", ")", "}", "let", "res", "=", "{", "}", "let", "isCollection", "=", "false", "if", "(", "hasNumKey", "(", "entries", ")", ")", "{", "res", "=", "[", "]", "isCollection", "=", "true", "}", "for", "(", "const", "entry", "of", "entries", ")", "{", "let", "path", "=", "entry", "[", "0", "]", "const", "value", "=", "entry", "[", "1", "]", "if", "(", "!", "isArray", "(", "path", ")", ")", "{", "path", "=", "[", "path", "]", "}", "const", "root", "=", "path", ".", "shift", "(", ")", "if", "(", "path", ".", "length", "===", "0", "&&", "(", "isCollection", "&&", "isNaN", "(", "root", ")", ")", ")", "{", "res", ".", "push", "(", "{", "[", "root", "]", ":", "value", "}", ")", "}", "else", "if", "(", "path", ".", "length", "===", "0", ")", "{", "res", "[", "root", "]", "=", "value", "}", "else", "if", "(", "isCollection", "&&", "isNaN", "(", "root", ")", ")", "{", "res", ".", "push", "(", "{", "[", "root", "]", ":", "deepFromEntries", "(", "res", "[", "root", "]", ",", "root", ",", "path", ",", "value", ")", "}", ")", "}", "else", "{", "res", "[", "root", "]", "=", "deepFromEntries", "(", "res", "[", "root", "]", ",", "root", ",", "path", ",", "value", ")", "}", "}", "return", "res", "}" ]
Create an object from given entries @param {array} entries @return {object} @api public @example const entries = [ [ ["name"], "John Doe" ], [ ["age"], 25 ], [ ["gender"], "Male" ] ] objectDeepFromEntries(entries) // -> {name: "John Doe", age: 25, gender: "Male"}
[ "Create", "an", "object", "from", "given", "entries" ]
ea0c889c659150aeee6855f03ce7fbfba04ad99a
https://github.com/octet-stream/object-deep-from-entries/blob/ea0c889c659150aeee6855f03ce7fbfba04ad99a/objectDeepFromEntries.js#L87-L124
44,652
socialally/air
lib/air/dimension.js
outerWidth
function outerWidth(margin) { var s, style; if(!this.length) { return null; } s = this.dom[0].getClientRects()[0].width; if(!margin) { style = window.getComputedStyle(this.dom[0], null); s -= parseInt(style.getPropertyValue('margin-top')); s -= parseInt(style.getPropertyValue('margin-bottom')); } return s; }
javascript
function outerWidth(margin) { var s, style; if(!this.length) { return null; } s = this.dom[0].getClientRects()[0].width; if(!margin) { style = window.getComputedStyle(this.dom[0], null); s -= parseInt(style.getPropertyValue('margin-top')); s -= parseInt(style.getPropertyValue('margin-bottom')); } return s; }
[ "function", "outerWidth", "(", "margin", ")", "{", "var", "s", ",", "style", ";", "if", "(", "!", "this", ".", "length", ")", "{", "return", "null", ";", "}", "s", "=", "this", ".", "dom", "[", "0", "]", ".", "getClientRects", "(", ")", "[", "0", "]", ".", "width", ";", "if", "(", "!", "margin", ")", "{", "style", "=", "window", ".", "getComputedStyle", "(", "this", ".", "dom", "[", "0", "]", ",", "null", ")", ";", "s", "-=", "parseInt", "(", "style", ".", "getPropertyValue", "(", "'margin-top'", ")", ")", ";", "s", "-=", "parseInt", "(", "style", ".", "getPropertyValue", "(", "'margin-bottom'", ")", ")", ";", "}", "return", "s", ";", "}" ]
Get the current computed width for the first element in the set of matched elements, including padding, border, and optionally margin. Returns a number (without "px") representation of the value or null if called on an empty set of elements.
[ "Get", "the", "current", "computed", "width", "for", "the", "first", "element", "in", "the", "set", "of", "matched", "elements", "including", "padding", "border", "and", "optionally", "margin", "." ]
a3d94de58aaa4930a425fbcc7266764bf6ca8ca6
https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/dimension.js#L34-L46
44,653
socialally/air
lib/air/dimension.js
outerHeight
function outerHeight(margin) { var s, style; if(!this.length) { return null; } s = this.dom[0].getClientRects()[0].height; if(!margin) { style = window.getComputedStyle(this.dom[0], null); s -= parseInt(style.getPropertyValue('margin-top')); s -= parseInt(style.getPropertyValue('margin-bottom')); } return s; }
javascript
function outerHeight(margin) { var s, style; if(!this.length) { return null; } s = this.dom[0].getClientRects()[0].height; if(!margin) { style = window.getComputedStyle(this.dom[0], null); s -= parseInt(style.getPropertyValue('margin-top')); s -= parseInt(style.getPropertyValue('margin-bottom')); } return s; }
[ "function", "outerHeight", "(", "margin", ")", "{", "var", "s", ",", "style", ";", "if", "(", "!", "this", ".", "length", ")", "{", "return", "null", ";", "}", "s", "=", "this", ".", "dom", "[", "0", "]", ".", "getClientRects", "(", ")", "[", "0", "]", ".", "height", ";", "if", "(", "!", "margin", ")", "{", "style", "=", "window", ".", "getComputedStyle", "(", "this", ".", "dom", "[", "0", "]", ",", "null", ")", ";", "s", "-=", "parseInt", "(", "style", ".", "getPropertyValue", "(", "'margin-top'", ")", ")", ";", "s", "-=", "parseInt", "(", "style", ".", "getPropertyValue", "(", "'margin-bottom'", ")", ")", ";", "}", "return", "s", ";", "}" ]
Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns a number (without "px") representation of the value or null if called on an empty set of elements.
[ "Get", "the", "current", "computed", "height", "for", "the", "first", "element", "in", "the", "set", "of", "matched", "elements", "including", "padding", "border", "and", "optionally", "margin", "." ]
a3d94de58aaa4930a425fbcc7266764bf6ca8ca6
https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/dimension.js#L55-L67
44,654
Sobesednik/wrote
src/read-dir-structure.js
readDirStructure
async function readDirStructure(dirPath) { if (!dirPath) { throw new Error('Please specify a path to the directory') } const lstat = await makePromise(fs.lstat, dirPath) if (!lstat.isDirectory()) { const err = new Error('Path is not a directory') err.code = 'ENOTDIR' throw err } const dir = await makePromise(fs.readdir, dirPath) const lstatRes = await lib.lstatFiles(dirPath, dir) const directories = lstatRes.filter(isDirectory) const notDirectories = lstatRes.filter(isNotDirectory) const files = notDirectories.reduce((acc, lstatRes) => Object.assign(acc, { [lstatRes.relativePath]: { type: getType(lstatRes), }, }), {}) const dirPromises = directories.map(async ({ path, relativePath }) => { const structure = await readDirStructure(path) return [relativePath, structure] }) const dirsArray = await Promise.all(dirPromises) const dirs = dirsArray.reduce( (acc, [relativePath, structure]) => { const d = { [relativePath]: structure } return Object.assign(acc, d) }, {} ) const merged = Object.assign({}, files, dirs) return { type: 'Directory', content: merged, } }
javascript
async function readDirStructure(dirPath) { if (!dirPath) { throw new Error('Please specify a path to the directory') } const lstat = await makePromise(fs.lstat, dirPath) if (!lstat.isDirectory()) { const err = new Error('Path is not a directory') err.code = 'ENOTDIR' throw err } const dir = await makePromise(fs.readdir, dirPath) const lstatRes = await lib.lstatFiles(dirPath, dir) const directories = lstatRes.filter(isDirectory) const notDirectories = lstatRes.filter(isNotDirectory) const files = notDirectories.reduce((acc, lstatRes) => Object.assign(acc, { [lstatRes.relativePath]: { type: getType(lstatRes), }, }), {}) const dirPromises = directories.map(async ({ path, relativePath }) => { const structure = await readDirStructure(path) return [relativePath, structure] }) const dirsArray = await Promise.all(dirPromises) const dirs = dirsArray.reduce( (acc, [relativePath, structure]) => { const d = { [relativePath]: structure } return Object.assign(acc, d) }, {} ) const merged = Object.assign({}, files, dirs) return { type: 'Directory', content: merged, } }
[ "async", "function", "readDirStructure", "(", "dirPath", ")", "{", "if", "(", "!", "dirPath", ")", "{", "throw", "new", "Error", "(", "'Please specify a path to the directory'", ")", "}", "const", "lstat", "=", "await", "makePromise", "(", "fs", ".", "lstat", ",", "dirPath", ")", "if", "(", "!", "lstat", ".", "isDirectory", "(", ")", ")", "{", "const", "err", "=", "new", "Error", "(", "'Path is not a directory'", ")", "err", ".", "code", "=", "'ENOTDIR'", "throw", "err", "}", "const", "dir", "=", "await", "makePromise", "(", "fs", ".", "readdir", ",", "dirPath", ")", "const", "lstatRes", "=", "await", "lib", ".", "lstatFiles", "(", "dirPath", ",", "dir", ")", "const", "directories", "=", "lstatRes", ".", "filter", "(", "isDirectory", ")", "const", "notDirectories", "=", "lstatRes", ".", "filter", "(", "isNotDirectory", ")", "const", "files", "=", "notDirectories", ".", "reduce", "(", "(", "acc", ",", "lstatRes", ")", "=>", "Object", ".", "assign", "(", "acc", ",", "{", "[", "lstatRes", ".", "relativePath", "]", ":", "{", "type", ":", "getType", "(", "lstatRes", ")", ",", "}", ",", "}", ")", ",", "{", "}", ")", "const", "dirPromises", "=", "directories", ".", "map", "(", "async", "(", "{", "path", ",", "relativePath", "}", ")", "=>", "{", "const", "structure", "=", "await", "readDirStructure", "(", "path", ")", "return", "[", "relativePath", ",", "structure", "]", "}", ")", "const", "dirsArray", "=", "await", "Promise", ".", "all", "(", "dirPromises", ")", "const", "dirs", "=", "dirsArray", ".", "reduce", "(", "(", "acc", ",", "[", "relativePath", ",", "structure", "]", ")", "=>", "{", "const", "d", "=", "{", "[", "relativePath", "]", ":", "structure", "}", "return", "Object", ".", "assign", "(", "acc", ",", "d", ")", "}", ",", "{", "}", ")", "const", "merged", "=", "Object", ".", "assign", "(", "{", "}", ",", "files", ",", "dirs", ")", "return", "{", "type", ":", "'Directory'", ",", "content", ":", "merged", ",", "}", "}" ]
Read a directory, and return its structure as an object @param {string} dirPath Path to the directory @returns {Promise.<DirectoryStructure>} An object reflecting directory structure
[ "Read", "a", "directory", "and", "return", "its", "structure", "as", "an", "object" ]
24992ad3bba4e5959dfb617b6c1f22d9a1306ab9
https://github.com/Sobesednik/wrote/blob/24992ad3bba4e5959dfb617b6c1f22d9a1306ab9/src/read-dir-structure.js#L50-L88
44,655
eps1lon/poe-i18n
scripts/generateDatLocaleData.js
fromEntries
function fromEntries(keys, values) { return keys.reduce((obj, key, i) => { obj[key] = values[i]; return obj; }, {}) }
javascript
function fromEntries(keys, values) { return keys.reduce((obj, key, i) => { obj[key] = values[i]; return obj; }, {}) }
[ "function", "fromEntries", "(", "keys", ",", "values", ")", "{", "return", "keys", ".", "reduce", "(", "(", "obj", ",", "key", ",", "i", ")", "=>", "{", "obj", "[", "key", "]", "=", "values", "[", "i", "]", ";", "return", "obj", ";", "}", ",", "{", "}", ")", "}" ]
reverse of Object.entries
[ "reverse", "of", "Object", ".", "entries" ]
fa92cc4a2be7f321f07a5dba28135db03dc0bc38
https://github.com/eps1lon/poe-i18n/blob/fa92cc4a2be7f321f07a5dba28135db03dc0bc38/scripts/generateDatLocaleData.js#L160-L165
44,656
gkarthiks/isEmptyObj
index.js
isEmptyObj
function isEmptyObj(object) { if(object === undefined) return true; var objToSend = JSON.parse(JSON.stringify(object)); var result = nestedEmptyCheck(objToSend); if(JSON.stringify(result).indexOf('false') > -1) return false; return true; }
javascript
function isEmptyObj(object) { if(object === undefined) return true; var objToSend = JSON.parse(JSON.stringify(object)); var result = nestedEmptyCheck(objToSend); if(JSON.stringify(result).indexOf('false') > -1) return false; return true; }
[ "function", "isEmptyObj", "(", "object", ")", "{", "if", "(", "object", "===", "undefined", ")", "return", "true", ";", "var", "objToSend", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "object", ")", ")", ";", "var", "result", "=", "nestedEmptyCheck", "(", "objToSend", ")", ";", "if", "(", "JSON", ".", "stringify", "(", "result", ")", ".", "indexOf", "(", "'false'", ")", ">", "-", "1", ")", "return", "false", ";", "return", "true", ";", "}" ]
before calling the nested validation method, makes a copy of the original object and calls with the copy of the object. @param object @returns {boolean}
[ "before", "calling", "the", "nested", "validation", "method", "makes", "a", "copy", "of", "the", "original", "object", "and", "calls", "with", "the", "copy", "of", "the", "object", "." ]
b83ea082db800731b9d7e0ad57e975f864994b07
https://github.com/gkarthiks/isEmptyObj/blob/b83ea082db800731b9d7e0ad57e975f864994b07/index.js#L60-L69
44,657
onecommons/base
lib/jsonrpc.js
function(result) { if (done) { if (session.httpRequest && session.httpRequest.log) { session.httpRequest.log.error("jsonrpc promise resolved after response sent:", req.method, "params:", req.params); } return; } return makeResult(req, result) }
javascript
function(result) { if (done) { if (session.httpRequest && session.httpRequest.log) { session.httpRequest.log.error("jsonrpc promise resolved after response sent:", req.method, "params:", req.params); } return; } return makeResult(req, result) }
[ "function", "(", "result", ")", "{", "if", "(", "done", ")", "{", "if", "(", "session", ".", "httpRequest", "&&", "session", ".", "httpRequest", ".", "log", ")", "{", "session", ".", "httpRequest", ".", "log", ".", "error", "(", "\"jsonrpc promise resolved after response sent:\"", ",", "req", ".", "method", ",", "\"params:\"", ",", "req", ".", "params", ")", ";", "}", "return", ";", "}", "return", "makeResult", "(", "req", ",", "result", ")", "}" ]
it's a promise
[ "it", "s", "a", "promise" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/lib/jsonrpc.js#L117-L125
44,658
jaredhanson/antenna
lib/index.js
create
function create() { function app(msg) { app.handle(msg); } utils.merge(app, proto); app.init(); for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } return app; }
javascript
function create() { function app(msg) { app.handle(msg); } utils.merge(app, proto); app.init(); for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } return app; }
[ "function", "create", "(", ")", "{", "function", "app", "(", "msg", ")", "{", "app", ".", "handle", "(", "msg", ")", ";", "}", "utils", ".", "merge", "(", "app", ",", "proto", ")", ";", "app", ".", "init", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "++", "i", ")", "{", "app", ".", "use", "(", "arguments", "[", "i", "]", ")", ";", "}", "return", "app", ";", "}" ]
Create application. @return {Function} @api public
[ "Create", "application", "." ]
fecfa8320a29d0f1cf22df0230f3b65a12316087
https://github.com/jaredhanson/antenna/blob/fecfa8320a29d0f1cf22df0230f3b65a12316087/lib/index.js#L14-L22
44,659
onecommons/base
lib/namedroutes.js
update
function update(app, target, source) { for (var prop in source) { if (!source.hasOwnProperty(prop)) continue; var def = expandDefinition(app, prop, source[prop]); if (prop in target) { if (!def) { delete target[prop]; } else if (def.route) { debugger; //XXX } else if (def.pathonly) { target[prop].path = def.path; } else { //use defaults() instead of extends() so undefined are skipped target[prop] = _.defaults({}, def, target[prop]); } } else if (!def.pathonly) { if (typeof def.path === 'undefined') def.path = prop; //use name as path target[prop] = def; } } return target; }
javascript
function update(app, target, source) { for (var prop in source) { if (!source.hasOwnProperty(prop)) continue; var def = expandDefinition(app, prop, source[prop]); if (prop in target) { if (!def) { delete target[prop]; } else if (def.route) { debugger; //XXX } else if (def.pathonly) { target[prop].path = def.path; } else { //use defaults() instead of extends() so undefined are skipped target[prop] = _.defaults({}, def, target[prop]); } } else if (!def.pathonly) { if (typeof def.path === 'undefined') def.path = prop; //use name as path target[prop] = def; } } return target; }
[ "function", "update", "(", "app", ",", "target", ",", "source", ")", "{", "for", "(", "var", "prop", "in", "source", ")", "{", "if", "(", "!", "source", ".", "hasOwnProperty", "(", "prop", ")", ")", "continue", ";", "var", "def", "=", "expandDefinition", "(", "app", ",", "prop", ",", "source", "[", "prop", "]", ")", ";", "if", "(", "prop", "in", "target", ")", "{", "if", "(", "!", "def", ")", "{", "delete", "target", "[", "prop", "]", ";", "}", "else", "if", "(", "def", ".", "route", ")", "{", "debugger", ";", "//XXX", "}", "else", "if", "(", "def", ".", "pathonly", ")", "{", "target", "[", "prop", "]", ".", "path", "=", "def", ".", "path", ";", "}", "else", "{", "//use defaults() instead of extends() so undefined are skipped", "target", "[", "prop", "]", "=", "_", ".", "defaults", "(", "{", "}", ",", "def", ",", "target", "[", "prop", "]", ")", ";", "}", "}", "else", "if", "(", "!", "def", ".", "pathonly", ")", "{", "if", "(", "typeof", "def", ".", "path", "===", "'undefined'", ")", "def", ".", "path", "=", "prop", ";", "//use name as path", "target", "[", "prop", "]", "=", "def", ";", "}", "}", "return", "target", ";", "}" ]
expand source and target then merge, if source and target are both have route recurse XXX if one or the the have route replace target with source otherwise merge source keys into target, if source key has falsy value, remove the key if handle is being added assume its the current app unless app is specified?
[ "expand", "source", "and", "target", "then", "merge", "if", "source", "and", "target", "are", "both", "have", "route", "recurse", "XXX", "if", "one", "or", "the", "the", "have", "route", "replace", "target", "with", "source", "otherwise", "merge", "source", "keys", "into", "target", "if", "source", "key", "has", "falsy", "value", "remove", "the", "key", "if", "handle", "is", "being", "added", "assume", "its", "the", "current", "app", "unless", "app", "is", "specified?" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/lib/namedroutes.js#L10-L32
44,660
briancsparks/serverassist
lib/client.js
function() { const query = {clientId}; var body = sg.extend({partnerId, version, sessionId}, {rsvr}); self.POST('hq', '/clientStart', query, body, function(err, config) { //console.log('clientStart-object', query, body, err, config); if (sg.ok(err, config)) { self.config = sg.deepCopy(config); _.each(self.config.upstreams, (upstream, prj_app) => { self.upstreams[prj_app] = upstream; }); if (sg.verbosity() > 2) { _.each(self.upstreams, (upstream, prj_app) => { console.log(`Using upstream: ${sg.lpad(prj_app, 20)} ->> ${upstream}`); }); } ctor_callback(err, self.config); } }); }
javascript
function() { const query = {clientId}; var body = sg.extend({partnerId, version, sessionId}, {rsvr}); self.POST('hq', '/clientStart', query, body, function(err, config) { //console.log('clientStart-object', query, body, err, config); if (sg.ok(err, config)) { self.config = sg.deepCopy(config); _.each(self.config.upstreams, (upstream, prj_app) => { self.upstreams[prj_app] = upstream; }); if (sg.verbosity() > 2) { _.each(self.upstreams, (upstream, prj_app) => { console.log(`Using upstream: ${sg.lpad(prj_app, 20)} ->> ${upstream}`); }); } ctor_callback(err, self.config); } }); }
[ "function", "(", ")", "{", "const", "query", "=", "{", "clientId", "}", ";", "var", "body", "=", "sg", ".", "extend", "(", "{", "partnerId", ",", "version", ",", "sessionId", "}", ",", "{", "rsvr", "}", ")", ";", "self", ".", "POST", "(", "'hq'", ",", "'/clientStart'", ",", "query", ",", "body", ",", "function", "(", "err", ",", "config", ")", "{", "//console.log('clientStart-object', query, body, err, config);", "if", "(", "sg", ".", "ok", "(", "err", ",", "config", ")", ")", "{", "self", ".", "config", "=", "sg", ".", "deepCopy", "(", "config", ")", ";", "_", ".", "each", "(", "self", ".", "config", ".", "upstreams", ",", "(", "upstream", ",", "prj_app", ")", "=>", "{", "self", ".", "upstreams", "[", "prj_app", "]", "=", "upstream", ";", "}", ")", ";", "if", "(", "sg", ".", "verbosity", "(", ")", ">", "2", ")", "{", "_", ".", "each", "(", "self", ".", "upstreams", ",", "(", "upstream", ",", "prj_app", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "sg", ".", "lpad", "(", "prj_app", ",", "20", ")", "}", "${", "upstream", "}", "`", ")", ";", "}", ")", ";", "}", "ctor_callback", "(", "err", ",", "self", ".", "config", ")", ";", "}", "}", ")", ";", "}" ]
main for ClientStart ctor
[ "main", "for", "ClientStart", "ctor" ]
f966832aae287f502cce53a71f5129b962ada8a3
https://github.com/briancsparks/serverassist/blob/f966832aae287f502cce53a71f5129b962ada8a3/lib/client.js#L50-L74
44,661
tmorin/ceb
dist/systemjs/helper/arrays.js
flatten
function flatten(array) { return array.reduce(function (a, b) { return isArray(b) ? a.concat(flatten(b)) : a.concat(b); }, []); }
javascript
function flatten(array) { return array.reduce(function (a, b) { return isArray(b) ? a.concat(flatten(b)) : a.concat(b); }, []); }
[ "function", "flatten", "(", "array", ")", "{", "return", "array", ".", "reduce", "(", "function", "(", "a", ",", "b", ")", "{", "return", "isArray", "(", "b", ")", "?", "a", ".", "concat", "(", "flatten", "(", "b", ")", ")", ":", "a", ".", "concat", "(", "b", ")", ";", "}", ",", "[", "]", ")", ";", "}" ]
Flattens a nested array. @param {!Array} array the array to flatten @returns {Array} the new flattened array
[ "Flattens", "a", "nested", "array", "." ]
7cc0904b482aa99e5123302c5de4401f7a80af02
https://github.com/tmorin/ceb/blob/7cc0904b482aa99e5123302c5de4401f7a80af02/dist/systemjs/helper/arrays.js#L14-L18
44,662
haraldrudell/nodegod
lib/master/masterserver.js
handleConnection
function handleConnection(socket) { // server 'connect' socket.setEncoding('utf-8') socket.on('data', requestResponder) function requestResponder(data) { socket.end(String(process.pid)) self.emit('data', data) } }
javascript
function handleConnection(socket) { // server 'connect' socket.setEncoding('utf-8') socket.on('data', requestResponder) function requestResponder(data) { socket.end(String(process.pid)) self.emit('data', data) } }
[ "function", "handleConnection", "(", "socket", ")", "{", "// server 'connect'", "socket", ".", "setEncoding", "(", "'utf-8'", ")", "socket", ".", "on", "(", "'data'", ",", "requestResponder", ")", "function", "requestResponder", "(", "data", ")", "{", "socket", ".", "end", "(", "String", "(", "process", ".", "pid", ")", ")", "self", ".", "emit", "(", "'data'", ",", "data", ")", "}", "}" ]
manage a connection, reponding to requests
[ "manage", "a", "connection", "reponding", "to", "requests" ]
3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21
https://github.com/haraldrudell/nodegod/blob/3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21/lib/master/masterserver.js#L88-L96
44,663
marknotton/env
index.js
getVariable
function getVariable(variable) { if ( cached.data == null ) { getData(); } if (variable.toUpperCase() in cached.data ) { return cached.data[variable.toUpperCase()]; } else if (variable in cached.data) { return cached.data[variable]; } }
javascript
function getVariable(variable) { if ( cached.data == null ) { getData(); } if (variable.toUpperCase() in cached.data ) { return cached.data[variable.toUpperCase()]; } else if (variable in cached.data) { return cached.data[variable]; } }
[ "function", "getVariable", "(", "variable", ")", "{", "if", "(", "cached", ".", "data", "==", "null", ")", "{", "getData", "(", ")", ";", "}", "if", "(", "variable", ".", "toUpperCase", "(", ")", "in", "cached", ".", "data", ")", "{", "return", "cached", ".", "data", "[", "variable", ".", "toUpperCase", "(", ")", "]", ";", "}", "else", "if", "(", "variable", "in", "cached", ".", "data", ")", "{", "return", "cached", ".", "data", "[", "variable", "]", ";", "}", "}" ]
Get a specific variable @param {string} variable Enter the variable you want to get @return {string}
[ "Get", "a", "specific", "variable" ]
13d9aaf4b060de4d3e09b221b191e65c463526ae
https://github.com/marknotton/env/blob/13d9aaf4b060de4d3e09b221b191e65c463526ae/index.js#L161-L172
44,664
MiguelCastillo/bit-loader
example/asyncfile/src/resolvePath.js
resolve
function resolve(moduleMeta, options) { function setPath(path) { return { path: path }; } return resolvePath(moduleMeta, options).then(setPath, log2console); }
javascript
function resolve(moduleMeta, options) { function setPath(path) { return { path: path }; } return resolvePath(moduleMeta, options).then(setPath, log2console); }
[ "function", "resolve", "(", "moduleMeta", ",", "options", ")", "{", "function", "setPath", "(", "path", ")", "{", "return", "{", "path", ":", "path", "}", ";", "}", "return", "resolvePath", "(", "moduleMeta", ",", "options", ")", ".", "then", "(", "setPath", ",", "log2console", ")", ";", "}" ]
Convert module name to full module path
[ "Convert", "module", "name", "to", "full", "module", "path" ]
da9d18952d87014fdb09e7a8320a24cbf1c2b436
https://github.com/MiguelCastillo/bit-loader/blob/da9d18952d87014fdb09e7a8320a24cbf1c2b436/example/asyncfile/src/resolvePath.js#L36-L44
44,665
MiguelCastillo/bit-loader
example/asyncfile/src/resolvePath.js
resolvePath
function resolvePath(moduleMeta, options) { var parentPath = getParentPath(moduleMeta, options); var filePath = path.resolve(path.dirname(options.baseUrl), moduleMeta.name); if (fs.existsSync(filePath)) { return Promise.resolve(filePath); } return new Promise(function(resolve, reject) { browserResolve(moduleMeta.name, {filename: parentPath}, function(err, path) { if (err) { reject(err); } else { resolve(path); } }); }); }
javascript
function resolvePath(moduleMeta, options) { var parentPath = getParentPath(moduleMeta, options); var filePath = path.resolve(path.dirname(options.baseUrl), moduleMeta.name); if (fs.existsSync(filePath)) { return Promise.resolve(filePath); } return new Promise(function(resolve, reject) { browserResolve(moduleMeta.name, {filename: parentPath}, function(err, path) { if (err) { reject(err); } else { resolve(path); } }); }); }
[ "function", "resolvePath", "(", "moduleMeta", ",", "options", ")", "{", "var", "parentPath", "=", "getParentPath", "(", "moduleMeta", ",", "options", ")", ";", "var", "filePath", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "options", ".", "baseUrl", ")", ",", "moduleMeta", ".", "name", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "filePath", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "browserResolve", "(", "moduleMeta", ".", "name", ",", "{", "filename", ":", "parentPath", "}", ",", "function", "(", "err", ",", "path", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "path", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Figures out the path for the moduleMeta so that the module file can be loaded from storage. We use browser-resolve to do the heavy lifting for us, so all this module is really doing is wrapping browser-resolve so that it can be used by bit loader in a convenient way.
[ "Figures", "out", "the", "path", "for", "the", "moduleMeta", "so", "that", "the", "module", "file", "can", "be", "loaded", "from", "storage", "." ]
da9d18952d87014fdb09e7a8320a24cbf1c2b436
https://github.com/MiguelCastillo/bit-loader/blob/da9d18952d87014fdb09e7a8320a24cbf1c2b436/example/asyncfile/src/resolvePath.js#L53-L71
44,666
MiguelCastillo/bit-loader
example/asyncfile/src/resolvePath.js
getParentPath
function getParentPath(moduleMeta, options) { var referrer = moduleMeta.referrer; return (referrer && moduleMeta !== referrer) ? referrer.path : options.baseUrl; }
javascript
function getParentPath(moduleMeta, options) { var referrer = moduleMeta.referrer; return (referrer && moduleMeta !== referrer) ? referrer.path : options.baseUrl; }
[ "function", "getParentPath", "(", "moduleMeta", ",", "options", ")", "{", "var", "referrer", "=", "moduleMeta", ".", "referrer", ";", "return", "(", "referrer", "&&", "moduleMeta", "!==", "referrer", ")", "?", "referrer", ".", "path", ":", "options", ".", "baseUrl", ";", "}" ]
Gets the path for the module requesting the moduleMeta being resolved. This is what happens when a dependency is loaded.
[ "Gets", "the", "path", "for", "the", "module", "requesting", "the", "moduleMeta", "being", "resolved", ".", "This", "is", "what", "happens", "when", "a", "dependency", "is", "loaded", "." ]
da9d18952d87014fdb09e7a8320a24cbf1c2b436
https://github.com/MiguelCastillo/bit-loader/blob/da9d18952d87014fdb09e7a8320a24cbf1c2b436/example/asyncfile/src/resolvePath.js#L78-L81
44,667
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(point) { var latitude = point.hasOwnProperty('lat') ? 'lat' : 'latitude'; var longitude = (point.hasOwnProperty('lng') ? 'lng' : false) || (point.hasOwnProperty('long') ? 'long' : false) || 'longitude'; var elevation = (point.hasOwnProperty('alt') ? 'alt' : false) || (point.hasOwnProperty('altitude') ? 'altitude' : false) || (point.hasOwnProperty('elev') ? 'elev' : false) || 'elevation'; return { latitude: latitude, longitude: longitude, elevation: elevation }; }
javascript
function(point) { var latitude = point.hasOwnProperty('lat') ? 'lat' : 'latitude'; var longitude = (point.hasOwnProperty('lng') ? 'lng' : false) || (point.hasOwnProperty('long') ? 'long' : false) || 'longitude'; var elevation = (point.hasOwnProperty('alt') ? 'alt' : false) || (point.hasOwnProperty('altitude') ? 'altitude' : false) || (point.hasOwnProperty('elev') ? 'elev' : false) || 'elevation'; return { latitude: latitude, longitude: longitude, elevation: elevation }; }
[ "function", "(", "point", ")", "{", "var", "latitude", "=", "point", ".", "hasOwnProperty", "(", "'lat'", ")", "?", "'lat'", ":", "'latitude'", ";", "var", "longitude", "=", "(", "point", ".", "hasOwnProperty", "(", "'lng'", ")", "?", "'lng'", ":", "false", ")", "||", "(", "point", ".", "hasOwnProperty", "(", "'long'", ")", "?", "'long'", ":", "false", ")", "||", "'longitude'", ";", "var", "elevation", "=", "(", "point", ".", "hasOwnProperty", "(", "'alt'", ")", "?", "'alt'", ":", "false", ")", "||", "(", "point", ".", "hasOwnProperty", "(", "'altitude'", ")", "?", "'altitude'", ":", "false", ")", "||", "(", "point", ".", "hasOwnProperty", "(", "'elev'", ")", "?", "'elev'", ":", "false", ")", "||", "'elevation'", ";", "return", "{", "latitude", ":", "latitude", ",", "longitude", ":", "longitude", ",", "elevation", ":", "elevation", "}", ";", "}" ]
Get the key names for a geo point. @param object Point position {latitude: 123, longitude: 123, elevation: 123} @return object { longitude: 'lng|long|longitude', latitude: 'lat|latitude', elevation: 'alt|altitude|elev|elevation' }
[ "Get", "the", "key", "names", "for", "a", "geo", "point", "." ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L36-L50
44,668
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(start, end, accuracy) { var keys = geolib.getKeys(start); var latitude = keys.latitude; var longitude = keys.longitude; accuracy = Math.floor(accuracy) || 1; var coord1 = {}, coord2 = {}; coord1[latitude] = parseFloat(geolib.useDecimal(start[latitude])).toRad(); coord1[longitude] = parseFloat(geolib.useDecimal(start[longitude])).toRad(); coord2[latitude] = parseFloat(geolib.useDecimal(end[latitude])).toRad(); coord2[longitude] = parseFloat(geolib.useDecimal(end[longitude])).toRad(); var distance = Math.round( Math.acos( Math.sin( coord2[latitude] ) * Math.sin( coord1[latitude] ) + Math.cos( coord2[latitude] ) * Math.cos( coord1[latitude] ) * Math.cos( coord1[longitude] - coord2[longitude] ) ) * radius ); return geolib.distance = Math.floor(Math.round(distance/accuracy)*accuracy); }
javascript
function(start, end, accuracy) { var keys = geolib.getKeys(start); var latitude = keys.latitude; var longitude = keys.longitude; accuracy = Math.floor(accuracy) || 1; var coord1 = {}, coord2 = {}; coord1[latitude] = parseFloat(geolib.useDecimal(start[latitude])).toRad(); coord1[longitude] = parseFloat(geolib.useDecimal(start[longitude])).toRad(); coord2[latitude] = parseFloat(geolib.useDecimal(end[latitude])).toRad(); coord2[longitude] = parseFloat(geolib.useDecimal(end[longitude])).toRad(); var distance = Math.round( Math.acos( Math.sin( coord2[latitude] ) * Math.sin( coord1[latitude] ) + Math.cos( coord2[latitude] ) * Math.cos( coord1[latitude] ) * Math.cos( coord1[longitude] - coord2[longitude] ) ) * radius ); return geolib.distance = Math.floor(Math.round(distance/accuracy)*accuracy); }
[ "function", "(", "start", ",", "end", ",", "accuracy", ")", "{", "var", "keys", "=", "geolib", ".", "getKeys", "(", "start", ")", ";", "var", "latitude", "=", "keys", ".", "latitude", ";", "var", "longitude", "=", "keys", ".", "longitude", ";", "accuracy", "=", "Math", ".", "floor", "(", "accuracy", ")", "||", "1", ";", "var", "coord1", "=", "{", "}", ",", "coord2", "=", "{", "}", ";", "coord1", "[", "latitude", "]", "=", "parseFloat", "(", "geolib", ".", "useDecimal", "(", "start", "[", "latitude", "]", ")", ")", ".", "toRad", "(", ")", ";", "coord1", "[", "longitude", "]", "=", "parseFloat", "(", "geolib", ".", "useDecimal", "(", "start", "[", "longitude", "]", ")", ")", ".", "toRad", "(", ")", ";", "coord2", "[", "latitude", "]", "=", "parseFloat", "(", "geolib", ".", "useDecimal", "(", "end", "[", "latitude", "]", ")", ")", ".", "toRad", "(", ")", ";", "coord2", "[", "longitude", "]", "=", "parseFloat", "(", "geolib", ".", "useDecimal", "(", "end", "[", "longitude", "]", ")", ")", ".", "toRad", "(", ")", ";", "var", "distance", "=", "Math", ".", "round", "(", "Math", ".", "acos", "(", "Math", ".", "sin", "(", "coord2", "[", "latitude", "]", ")", "*", "Math", ".", "sin", "(", "coord1", "[", "latitude", "]", ")", "+", "Math", ".", "cos", "(", "coord2", "[", "latitude", "]", ")", "*", "Math", ".", "cos", "(", "coord1", "[", "latitude", "]", ")", "*", "Math", ".", "cos", "(", "coord1", "[", "longitude", "]", "-", "coord2", "[", "longitude", "]", ")", ")", "*", "radius", ")", ";", "return", "geolib", ".", "distance", "=", "Math", ".", "floor", "(", "Math", ".", "round", "(", "distance", "/", "accuracy", ")", "*", "accuracy", ")", ";", "}" ]
Calculates the distance between two spots. This method is more simple but also more inaccurate @param object Start position {latitude: 123, longitude: 123} @param object End position {latitude: 123, longitude: 123} @param integer Accuracy (in meters) @return integer Distance (in meters)
[ "Calculates", "the", "distance", "between", "two", "spots", ".", "This", "method", "is", "more", "simple", "but", "also", "more", "inaccurate" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L212-L250
44,669
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(coords) { if (!coords.length) { return false; } var keys = geolib.getKeys(coords[0]); var latitude = keys.latitude; var longitude = keys.longitude; var max = function( array ){ return Math.max.apply( Math, array ); }; var min = function( array ){ return Math.min.apply( Math, array ); }; var lat, lng, splitCoords = {lat: [], lng: []}; for(var coord in coords) { splitCoords.lat.push(geolib.useDecimal(coords[coord][latitude])); splitCoords.lng.push(geolib.useDecimal(coords[coord][longitude])); } var minLat = min(splitCoords.lat); var minLng = min(splitCoords.lng); var maxLat = max(splitCoords.lat); var maxLng = max(splitCoords.lng); lat = ((minLat + maxLat)/2).toFixed(6); lng = ((minLng + maxLng)/2).toFixed(6); // distance from the deepest left to the highest right point (diagonal distance) var distance = geolib.convertUnit('km', geolib.getDistance({lat:minLat, lng:minLng}, {lat:maxLat, lng:maxLng})); return {"latitude": lat, "longitude": lng, "distance": distance}; }
javascript
function(coords) { if (!coords.length) { return false; } var keys = geolib.getKeys(coords[0]); var latitude = keys.latitude; var longitude = keys.longitude; var max = function( array ){ return Math.max.apply( Math, array ); }; var min = function( array ){ return Math.min.apply( Math, array ); }; var lat, lng, splitCoords = {lat: [], lng: []}; for(var coord in coords) { splitCoords.lat.push(geolib.useDecimal(coords[coord][latitude])); splitCoords.lng.push(geolib.useDecimal(coords[coord][longitude])); } var minLat = min(splitCoords.lat); var minLng = min(splitCoords.lng); var maxLat = max(splitCoords.lat); var maxLng = max(splitCoords.lng); lat = ((minLat + maxLat)/2).toFixed(6); lng = ((minLng + maxLng)/2).toFixed(6); // distance from the deepest left to the highest right point (diagonal distance) var distance = geolib.convertUnit('km', geolib.getDistance({lat:minLat, lng:minLng}, {lat:maxLat, lng:maxLng})); return {"latitude": lat, "longitude": lng, "distance": distance}; }
[ "function", "(", "coords", ")", "{", "if", "(", "!", "coords", ".", "length", ")", "{", "return", "false", ";", "}", "var", "keys", "=", "geolib", ".", "getKeys", "(", "coords", "[", "0", "]", ")", ";", "var", "latitude", "=", "keys", ".", "latitude", ";", "var", "longitude", "=", "keys", ".", "longitude", ";", "var", "max", "=", "function", "(", "array", ")", "{", "return", "Math", ".", "max", ".", "apply", "(", "Math", ",", "array", ")", ";", "}", ";", "var", "min", "=", "function", "(", "array", ")", "{", "return", "Math", ".", "min", ".", "apply", "(", "Math", ",", "array", ")", ";", "}", ";", "var", "lat", ",", "lng", ",", "splitCoords", "=", "{", "lat", ":", "[", "]", ",", "lng", ":", "[", "]", "}", ";", "for", "(", "var", "coord", "in", "coords", ")", "{", "splitCoords", ".", "lat", ".", "push", "(", "geolib", ".", "useDecimal", "(", "coords", "[", "coord", "]", "[", "latitude", "]", ")", ")", ";", "splitCoords", ".", "lng", ".", "push", "(", "geolib", ".", "useDecimal", "(", "coords", "[", "coord", "]", "[", "longitude", "]", ")", ")", ";", "}", "var", "minLat", "=", "min", "(", "splitCoords", ".", "lat", ")", ";", "var", "minLng", "=", "min", "(", "splitCoords", ".", "lng", ")", ";", "var", "maxLat", "=", "max", "(", "splitCoords", ".", "lat", ")", ";", "var", "maxLng", "=", "max", "(", "splitCoords", ".", "lng", ")", ";", "lat", "=", "(", "(", "minLat", "+", "maxLat", ")", "/", "2", ")", ".", "toFixed", "(", "6", ")", ";", "lng", "=", "(", "(", "minLng", "+", "maxLng", ")", "/", "2", ")", ".", "toFixed", "(", "6", ")", ";", "// distance from the deepest left to the highest right point (diagonal distance)", "var", "distance", "=", "geolib", ".", "convertUnit", "(", "'km'", ",", "geolib", ".", "getDistance", "(", "{", "lat", ":", "minLat", ",", "lng", ":", "minLng", "}", ",", "{", "lat", ":", "maxLat", ",", "lng", ":", "maxLng", "}", ")", ")", ";", "return", "{", "\"latitude\"", ":", "lat", ",", "\"longitude\"", ":", "lng", ",", "\"distance\"", ":", "distance", "}", ";", "}" ]
Calculates the center of a collection of geo coordinates @param array Collection of coords [{latitude: 51.510, longitude: 7.1321}, {latitude: 49.1238, longitude: "8° 30' W"}, ...] @return object {latitude: centerLat, longitude: centerLng, distance: diagonalDistance}
[ "Calculates", "the", "center", "of", "a", "collection", "of", "geo", "coordinates" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L259-L297
44,670
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(latlng, coords) { var keys = geolib.getKeys(latlng); var latitude = keys.latitude; var longitude = keys.longitude; for(var c = false, i = -1, l = coords.length, j = l - 1; ++i < l; j = i) { ( (coords[i][longitude] <= latlng[longitude] && latlng[longitude] < coords[j][longitude]) || (coords[j][longitude] <= latlng[longitude] && latlng[longitude] < coords[i][longitude]) ) && (latlng[latitude] < (coords[j][latitude] - coords[i][latitude]) * (latlng[longitude] - coords[i][longitude]) / (coords[j][longitude] - coords[i][longitude]) + coords[i][latitude]) && (c = !c); } return c; }
javascript
function(latlng, coords) { var keys = geolib.getKeys(latlng); var latitude = keys.latitude; var longitude = keys.longitude; for(var c = false, i = -1, l = coords.length, j = l - 1; ++i < l; j = i) { ( (coords[i][longitude] <= latlng[longitude] && latlng[longitude] < coords[j][longitude]) || (coords[j][longitude] <= latlng[longitude] && latlng[longitude] < coords[i][longitude]) ) && (latlng[latitude] < (coords[j][latitude] - coords[i][latitude]) * (latlng[longitude] - coords[i][longitude]) / (coords[j][longitude] - coords[i][longitude]) + coords[i][latitude]) && (c = !c); } return c; }
[ "function", "(", "latlng", ",", "coords", ")", "{", "var", "keys", "=", "geolib", ".", "getKeys", "(", "latlng", ")", ";", "var", "latitude", "=", "keys", ".", "latitude", ";", "var", "longitude", "=", "keys", ".", "longitude", ";", "for", "(", "var", "c", "=", "false", ",", "i", "=", "-", "1", ",", "l", "=", "coords", ".", "length", ",", "j", "=", "l", "-", "1", ";", "++", "i", "<", "l", ";", "j", "=", "i", ")", "{", "(", "(", "coords", "[", "i", "]", "[", "longitude", "]", "<=", "latlng", "[", "longitude", "]", "&&", "latlng", "[", "longitude", "]", "<", "coords", "[", "j", "]", "[", "longitude", "]", ")", "||", "(", "coords", "[", "j", "]", "[", "longitude", "]", "<=", "latlng", "[", "longitude", "]", "&&", "latlng", "[", "longitude", "]", "<", "coords", "[", "i", "]", "[", "longitude", "]", ")", ")", "&&", "(", "latlng", "[", "latitude", "]", "<", "(", "coords", "[", "j", "]", "[", "latitude", "]", "-", "coords", "[", "i", "]", "[", "latitude", "]", ")", "*", "(", "latlng", "[", "longitude", "]", "-", "coords", "[", "i", "]", "[", "longitude", "]", ")", "/", "(", "coords", "[", "j", "]", "[", "longitude", "]", "-", "coords", "[", "i", "]", "[", "longitude", "]", ")", "+", "coords", "[", "i", "]", "[", "latitude", "]", ")", "&&", "(", "c", "=", "!", "c", ")", ";", "}", "return", "c", ";", "}" ]
Checks whether a point is inside of a polygon or not. Note that the polygon coords must be in correct order! @param object coordinate to check e.g. {latitude: 51.5023, longitude: 7.3815} @param array array with coords e.g. [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...] @return bool true if the coordinate is inside the given polygon
[ "Checks", "whether", "a", "point", "is", "inside", "of", "a", "polygon", "or", "not", ".", "Note", "that", "the", "polygon", "coords", "must", "be", "in", "correct", "order!" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L353-L374
44,671
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(originLL, destLL) { var keys = geolib.getKeys(originLL); var latitude = keys.latitude; var longitude = keys.longitude; destLL[latitude] = geolib.useDecimal(destLL[latitude]); destLL[longitude] = geolib.useDecimal(destLL[longitude]); originLL[latitude] = geolib.useDecimal(originLL[latitude]); originLL[longitude] = geolib.useDecimal(originLL[longitude]); var bearing = ( ( Math.atan2( Math.sin( destLL[longitude].toRad() - originLL[longitude].toRad() ) * Math.cos( destLL[latitude].toRad() ), Math.cos( originLL[latitude].toRad() ) * Math.sin( destLL[latitude].toRad() ) - Math.sin( originLL[latitude].toRad() ) * Math.cos( destLL[latitude].toRad() ) * Math.cos( destLL[longitude].toRad() - originLL[longitude].toRad() ) ) ).toDeg() + 360 ) % 360; return bearing; }
javascript
function(originLL, destLL) { var keys = geolib.getKeys(originLL); var latitude = keys.latitude; var longitude = keys.longitude; destLL[latitude] = geolib.useDecimal(destLL[latitude]); destLL[longitude] = geolib.useDecimal(destLL[longitude]); originLL[latitude] = geolib.useDecimal(originLL[latitude]); originLL[longitude] = geolib.useDecimal(originLL[longitude]); var bearing = ( ( Math.atan2( Math.sin( destLL[longitude].toRad() - originLL[longitude].toRad() ) * Math.cos( destLL[latitude].toRad() ), Math.cos( originLL[latitude].toRad() ) * Math.sin( destLL[latitude].toRad() ) - Math.sin( originLL[latitude].toRad() ) * Math.cos( destLL[latitude].toRad() ) * Math.cos( destLL[longitude].toRad() - originLL[longitude].toRad() ) ) ).toDeg() + 360 ) % 360; return bearing; }
[ "function", "(", "originLL", ",", "destLL", ")", "{", "var", "keys", "=", "geolib", ".", "getKeys", "(", "originLL", ")", ";", "var", "latitude", "=", "keys", ".", "latitude", ";", "var", "longitude", "=", "keys", ".", "longitude", ";", "destLL", "[", "latitude", "]", "=", "geolib", ".", "useDecimal", "(", "destLL", "[", "latitude", "]", ")", ";", "destLL", "[", "longitude", "]", "=", "geolib", ".", "useDecimal", "(", "destLL", "[", "longitude", "]", ")", ";", "originLL", "[", "latitude", "]", "=", "geolib", ".", "useDecimal", "(", "originLL", "[", "latitude", "]", ")", ";", "originLL", "[", "longitude", "]", "=", "geolib", ".", "useDecimal", "(", "originLL", "[", "longitude", "]", ")", ";", "var", "bearing", "=", "(", "(", "Math", ".", "atan2", "(", "Math", ".", "sin", "(", "destLL", "[", "longitude", "]", ".", "toRad", "(", ")", "-", "originLL", "[", "longitude", "]", ".", "toRad", "(", ")", ")", "*", "Math", ".", "cos", "(", "destLL", "[", "latitude", "]", ".", "toRad", "(", ")", ")", ",", "Math", ".", "cos", "(", "originLL", "[", "latitude", "]", ".", "toRad", "(", ")", ")", "*", "Math", ".", "sin", "(", "destLL", "[", "latitude", "]", ".", "toRad", "(", ")", ")", "-", "Math", ".", "sin", "(", "originLL", "[", "latitude", "]", ".", "toRad", "(", ")", ")", "*", "Math", ".", "cos", "(", "destLL", "[", "latitude", "]", ".", "toRad", "(", ")", ")", "*", "Math", ".", "cos", "(", "destLL", "[", "longitude", "]", ".", "toRad", "(", ")", "-", "originLL", "[", "longitude", "]", ".", "toRad", "(", ")", ")", ")", ")", ".", "toDeg", "(", ")", "+", "360", ")", "%", "360", ";", "return", "bearing", ";", "}" ]
Gets great circle bearing of two points. See description of getRhumbLineBearing for more information @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815}) @param object destination coordinate @return integer calculated bearing
[ "Gets", "great", "circle", "bearing", "of", "two", "points", ".", "See", "description", "of", "getRhumbLineBearing", "for", "more", "information" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L440-L482
44,672
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(originLL, destLL, bearingMode) { var direction; if(bearingMode == 'circle') { // use great circle bearing var bearing = geolib.getBearing(originLL, destLL); } else { // default is rhumb line bearing var bearing = geolib.getRhumbLineBearing(originLL, destLL); } switch(Math.round(bearing/22.5)) { case 1: direction = {exact: "NNE", rough: "N"}; break; case 2: direction = {exact: "NE", rough: "N"} break; case 3: direction = {exact: "ENE", rough: "E"} break; case 4: direction = {exact: "E", rough: "E"} break; case 5: direction = {exact: "ESE", rough: "E"} break; case 6: direction = {exact: "SE", rough: "E"} break; case 7: direction = {exact: "SSE", rough: "S"} break; case 8: direction = {exact: "S", rough: "S"} break; case 9: direction = {exact: "SSW", rough: "S"} break; case 10: direction = {exact: "SW", rough: "S"} break; case 11: direction = {exact: "WSW", rough: "W"} break; case 12: direction = {exact: "W", rough: "W"} break; case 13: direction = {exact: "WNW", rough: "W"} break; case 14: direction = {exact: "NW", rough: "W"} break; case 15: direction = {exact: "NNW", rough: "N"} break; default: direction = {exact: "N", rough: "N"} } return direction; }
javascript
function(originLL, destLL, bearingMode) { var direction; if(bearingMode == 'circle') { // use great circle bearing var bearing = geolib.getBearing(originLL, destLL); } else { // default is rhumb line bearing var bearing = geolib.getRhumbLineBearing(originLL, destLL); } switch(Math.round(bearing/22.5)) { case 1: direction = {exact: "NNE", rough: "N"}; break; case 2: direction = {exact: "NE", rough: "N"} break; case 3: direction = {exact: "ENE", rough: "E"} break; case 4: direction = {exact: "E", rough: "E"} break; case 5: direction = {exact: "ESE", rough: "E"} break; case 6: direction = {exact: "SE", rough: "E"} break; case 7: direction = {exact: "SSE", rough: "S"} break; case 8: direction = {exact: "S", rough: "S"} break; case 9: direction = {exact: "SSW", rough: "S"} break; case 10: direction = {exact: "SW", rough: "S"} break; case 11: direction = {exact: "WSW", rough: "W"} break; case 12: direction = {exact: "W", rough: "W"} break; case 13: direction = {exact: "WNW", rough: "W"} break; case 14: direction = {exact: "NW", rough: "W"} break; case 15: direction = {exact: "NNW", rough: "N"} break; default: direction = {exact: "N", rough: "N"} } return direction; }
[ "function", "(", "originLL", ",", "destLL", ",", "bearingMode", ")", "{", "var", "direction", ";", "if", "(", "bearingMode", "==", "'circle'", ")", "{", "// use great circle bearing", "var", "bearing", "=", "geolib", ".", "getBearing", "(", "originLL", ",", "destLL", ")", ";", "}", "else", "{", "// default is rhumb line bearing", "var", "bearing", "=", "geolib", ".", "getRhumbLineBearing", "(", "originLL", ",", "destLL", ")", ";", "}", "switch", "(", "Math", ".", "round", "(", "bearing", "/", "22.5", ")", ")", "{", "case", "1", ":", "direction", "=", "{", "exact", ":", "\"NNE\"", ",", "rough", ":", "\"N\"", "}", ";", "break", ";", "case", "2", ":", "direction", "=", "{", "exact", ":", "\"NE\"", ",", "rough", ":", "\"N\"", "}", "break", ";", "case", "3", ":", "direction", "=", "{", "exact", ":", "\"ENE\"", ",", "rough", ":", "\"E\"", "}", "break", ";", "case", "4", ":", "direction", "=", "{", "exact", ":", "\"E\"", ",", "rough", ":", "\"E\"", "}", "break", ";", "case", "5", ":", "direction", "=", "{", "exact", ":", "\"ESE\"", ",", "rough", ":", "\"E\"", "}", "break", ";", "case", "6", ":", "direction", "=", "{", "exact", ":", "\"SE\"", ",", "rough", ":", "\"E\"", "}", "break", ";", "case", "7", ":", "direction", "=", "{", "exact", ":", "\"SSE\"", ",", "rough", ":", "\"S\"", "}", "break", ";", "case", "8", ":", "direction", "=", "{", "exact", ":", "\"S\"", ",", "rough", ":", "\"S\"", "}", "break", ";", "case", "9", ":", "direction", "=", "{", "exact", ":", "\"SSW\"", ",", "rough", ":", "\"S\"", "}", "break", ";", "case", "10", ":", "direction", "=", "{", "exact", ":", "\"SW\"", ",", "rough", ":", "\"S\"", "}", "break", ";", "case", "11", ":", "direction", "=", "{", "exact", ":", "\"WSW\"", ",", "rough", ":", "\"W\"", "}", "break", ";", "case", "12", ":", "direction", "=", "{", "exact", ":", "\"W\"", ",", "rough", ":", "\"W\"", "}", "break", ";", "case", "13", ":", "direction", "=", "{", "exact", ":", "\"WNW\"", ",", "rough", ":", "\"W\"", "}", "break", ";", "case", "14", ":", "direction", "=", "{", "exact", ":", "\"NW\"", ",", "rough", ":", "\"W\"", "}", "break", ";", "case", "15", ":", "direction", "=", "{", "exact", ":", "\"NNW\"", ",", "rough", ":", "\"N\"", "}", "break", ";", "default", ":", "direction", "=", "{", "exact", ":", "\"N\"", ",", "rough", ":", "\"N\"", "}", "}", "return", "direction", ";", "}" ]
Gets the compass direction from an origin coordinate to a destination coordinate. @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815}) @param object destination coordinate @param string Bearing mode. Can be either circle or rhumbline @return object Returns an object with a rough (NESW) and an exact direction (NNE, NE, ENE, E, ESE, etc).
[ "Gets", "the", "compass", "direction", "from", "an", "origin", "coordinate", "to", "a", "destination", "coordinate", "." ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L493-L554
44,673
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(latlng, coords) { var keys = geolib.getKeys(latlng); var latitude = keys.latitude; var longitude = keys.longitude; var coordsArray = []; for(var coord in coords) { var d = geolib.getDistance(latlng, coords[coord]); coordsArray.push({key: coord, latitude: coords[coord][latitude], longitude: coords[coord][longitude], distance: d}); } return coordsArray.sort(function(a, b) { return a.distance - b.distance; }); }
javascript
function(latlng, coords) { var keys = geolib.getKeys(latlng); var latitude = keys.latitude; var longitude = keys.longitude; var coordsArray = []; for(var coord in coords) { var d = geolib.getDistance(latlng, coords[coord]); coordsArray.push({key: coord, latitude: coords[coord][latitude], longitude: coords[coord][longitude], distance: d}); } return coordsArray.sort(function(a, b) { return a.distance - b.distance; }); }
[ "function", "(", "latlng", ",", "coords", ")", "{", "var", "keys", "=", "geolib", ".", "getKeys", "(", "latlng", ")", ";", "var", "latitude", "=", "keys", ".", "latitude", ";", "var", "longitude", "=", "keys", ".", "longitude", ";", "var", "coordsArray", "=", "[", "]", ";", "for", "(", "var", "coord", "in", "coords", ")", "{", "var", "d", "=", "geolib", ".", "getDistance", "(", "latlng", ",", "coords", "[", "coord", "]", ")", ";", "coordsArray", ".", "push", "(", "{", "key", ":", "coord", ",", "latitude", ":", "coords", "[", "coord", "]", "[", "latitude", "]", ",", "longitude", ":", "coords", "[", "coord", "]", "[", "longitude", "]", ",", "distance", ":", "d", "}", ")", ";", "}", "return", "coordsArray", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "distance", "-", "b", ".", "distance", ";", "}", ")", ";", "}" ]
Sorts an array of coords by distance from a reference coordinate @param object reference coordinate e.g. {latitude: 51.5023, longitude: 7.3815} @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...] @return array ordered array
[ "Sorts", "an", "array", "of", "coords", "by", "distance", "from", "a", "reference", "coordinate" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L564-L578
44,674
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(latlng, coords, offset) { offset = offset || 0; var ordered = geolib.orderByDistance(latlng, coords); return ordered[offset]; }
javascript
function(latlng, coords, offset) { offset = offset || 0; var ordered = geolib.orderByDistance(latlng, coords); return ordered[offset]; }
[ "function", "(", "latlng", ",", "coords", ",", "offset", ")", "{", "offset", "=", "offset", "||", "0", ";", "var", "ordered", "=", "geolib", ".", "orderByDistance", "(", "latlng", ",", "coords", ")", ";", "return", "ordered", "[", "offset", "]", ";", "}" ]
Finds the nearest coordinate to a reference coordinate @param object reference coordinate e.g. {latitude: 51.5023, longitude: 7.3815} @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...] @return array ordered array
[ "Finds", "the", "nearest", "coordinate", "to", "a", "reference", "coordinate" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L588-L594
44,675
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(coords) { var dist = 0, last; for (var i = 0, l = coords.length; i < l; ++i) { if(last) { dist += geolib.getDistance(coords[i], last); } last = coords[i]; } return dist; }
javascript
function(coords) { var dist = 0, last; for (var i = 0, l = coords.length; i < l; ++i) { if(last) { dist += geolib.getDistance(coords[i], last); } last = coords[i]; } return dist; }
[ "function", "(", "coords", ")", "{", "var", "dist", "=", "0", ",", "last", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "coords", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "if", "(", "last", ")", "{", "dist", "+=", "geolib", ".", "getDistance", "(", "coords", "[", "i", "]", ",", "last", ")", ";", "}", "last", "=", "coords", "[", "i", "]", ";", "}", "return", "dist", ";", "}" ]
Calculates the length of a given path @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...] @return integer length of the path (in meters)
[ "Calculates", "the", "length", "of", "a", "given", "path" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L603-L615
44,676
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(unit, distance, round) { if(distance == 0 || typeof distance == 'undefined') { if(geolib.distance == 0) { // throw 'No distance given.'; return 0; } else { distance = geolib.distance; } } unit = unit || 'm'; round = (null == round ? 4 : round); switch(unit) { case 'm': // Meter return geolib.round(distance, round); break; case 'km': // Kilometer return geolib.round(distance / 1000, round); break; case 'cm': // Centimeter return geolib.round(distance * 100, round); break; case 'mm': // Millimeter return geolib.round(distance * 1000, round); break; case 'mi': // Miles return geolib.round(distance * (1 / 1609.344), round); break; case 'sm': // Seamiles return geolib.round(distance * (1 / 1852.216), round); break; case 'ft': // Feet return geolib.round(distance * (100 / 30.48), round); break; case 'in': // Inch return geolib.round(distance * 100 / 2.54, round); break; case 'yd': // Yards return geolib.round(distance * (1 / 0.9144), round); break; } return distance; }
javascript
function(unit, distance, round) { if(distance == 0 || typeof distance == 'undefined') { if(geolib.distance == 0) { // throw 'No distance given.'; return 0; } else { distance = geolib.distance; } } unit = unit || 'm'; round = (null == round ? 4 : round); switch(unit) { case 'm': // Meter return geolib.round(distance, round); break; case 'km': // Kilometer return geolib.round(distance / 1000, round); break; case 'cm': // Centimeter return geolib.round(distance * 100, round); break; case 'mm': // Millimeter return geolib.round(distance * 1000, round); break; case 'mi': // Miles return geolib.round(distance * (1 / 1609.344), round); break; case 'sm': // Seamiles return geolib.round(distance * (1 / 1852.216), round); break; case 'ft': // Feet return geolib.round(distance * (100 / 30.48), round); break; case 'in': // Inch return geolib.round(distance * 100 / 2.54, round); break; case 'yd': // Yards return geolib.round(distance * (1 / 0.9144), round); break; } return distance; }
[ "function", "(", "unit", ",", "distance", ",", "round", ")", "{", "if", "(", "distance", "==", "0", "||", "typeof", "distance", "==", "'undefined'", ")", "{", "if", "(", "geolib", ".", "distance", "==", "0", ")", "{", "// throw 'No distance given.';", "return", "0", ";", "}", "else", "{", "distance", "=", "geolib", ".", "distance", ";", "}", "}", "unit", "=", "unit", "||", "'m'", ";", "round", "=", "(", "null", "==", "round", "?", "4", ":", "round", ")", ";", "switch", "(", "unit", ")", "{", "case", "'m'", ":", "// Meter", "return", "geolib", ".", "round", "(", "distance", ",", "round", ")", ";", "break", ";", "case", "'km'", ":", "// Kilometer", "return", "geolib", ".", "round", "(", "distance", "/", "1000", ",", "round", ")", ";", "break", ";", "case", "'cm'", ":", "// Centimeter", "return", "geolib", ".", "round", "(", "distance", "*", "100", ",", "round", ")", ";", "break", ";", "case", "'mm'", ":", "// Millimeter", "return", "geolib", ".", "round", "(", "distance", "*", "1000", ",", "round", ")", ";", "break", ";", "case", "'mi'", ":", "// Miles", "return", "geolib", ".", "round", "(", "distance", "*", "(", "1", "/", "1609.344", ")", ",", "round", ")", ";", "break", ";", "case", "'sm'", ":", "// Seamiles", "return", "geolib", ".", "round", "(", "distance", "*", "(", "1", "/", "1852.216", ")", ",", "round", ")", ";", "break", ";", "case", "'ft'", ":", "// Feet", "return", "geolib", ".", "round", "(", "distance", "*", "(", "100", "/", "30.48", ")", ",", "round", ")", ";", "break", ";", "case", "'in'", ":", "// Inch", "return", "geolib", ".", "round", "(", "distance", "*", "100", "/", "2.54", ",", "round", ")", ";", "break", ";", "case", "'yd'", ":", "// Yards", "return", "geolib", ".", "round", "(", "distance", "*", "(", "1", "/", "0.9144", ")", ",", "round", ")", ";", "break", ";", "}", "return", "distance", ";", "}" ]
Converts a distance from meters to km, mm, cm, mi, ft, in or yd @param string Format to be converted in @param float Distance in meters @param float Decimal places for rounding (default: 4) @return float Converted distance
[ "Converts", "a", "distance", "from", "meters", "to", "km", "mm", "cm", "mi", "ft", "in", "or", "yd" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L746-L795
44,677
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(value) { value = value.toString().replace(/\s*/, ''); // looks silly but works as expected // checks if value is in decimal format if (!isNaN(parseFloat(value)) && parseFloat(value).toString() == value) { return parseFloat(value); // checks if it's sexagesimal format (HHH° MM' SS" (NESW)) } else if(geolib.isSexagesimal(value) == true) { return parseFloat(geolib.sexagesimal2decimal(value)); } else { throw 'Unknown format.'; } }
javascript
function(value) { value = value.toString().replace(/\s*/, ''); // looks silly but works as expected // checks if value is in decimal format if (!isNaN(parseFloat(value)) && parseFloat(value).toString() == value) { return parseFloat(value); // checks if it's sexagesimal format (HHH° MM' SS" (NESW)) } else if(geolib.isSexagesimal(value) == true) { return parseFloat(geolib.sexagesimal2decimal(value)); } else { throw 'Unknown format.'; } }
[ "function", "(", "value", ")", "{", "value", "=", "value", ".", "toString", "(", ")", ".", "replace", "(", "/", "\\s*", "/", ",", "''", ")", ";", "// looks silly but works as expected", "// checks if value is in decimal format", "if", "(", "!", "isNaN", "(", "parseFloat", "(", "value", ")", ")", "&&", "parseFloat", "(", "value", ")", ".", "toString", "(", ")", "==", "value", ")", "{", "return", "parseFloat", "(", "value", ")", ";", "// checks if it's sexagesimal format (HHH° MM' SS\" (NESW))", "}", "else", "if", "(", "geolib", ".", "isSexagesimal", "(", "value", ")", "==", "true", ")", "{", "return", "parseFloat", "(", "geolib", ".", "sexagesimal2decimal", "(", "value", ")", ")", ";", "}", "else", "{", "throw", "'Unknown format.'", ";", "}", "}" ]
Checks if a value is in decimal format or, if neccessary, converts to decimal @param mixed Value to be checked/converted @return float Coordinate in decimal format
[ "Checks", "if", "a", "value", "is", "in", "decimal", "format", "or", "if", "neccessary", "converts", "to", "decimal" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L804-L819
44,678
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(dec) { if (dec in geolib.sexagesimal) { return geolib.sexagesimal[dec]; } var tmp = dec.toString().split('.'); var deg = Math.abs(tmp[0]); var min = ('0.' + tmp[1])*60; var sec = min.toString().split('.'); min = Math.floor(min); sec = (('0.' + sec[1]) * 60).toFixed(2); geolib.sexagesimal[dec] = (deg + '° ' + min + "' " + sec + '"'); return geolib.sexagesimal[dec]; }
javascript
function(dec) { if (dec in geolib.sexagesimal) { return geolib.sexagesimal[dec]; } var tmp = dec.toString().split('.'); var deg = Math.abs(tmp[0]); var min = ('0.' + tmp[1])*60; var sec = min.toString().split('.'); min = Math.floor(min); sec = (('0.' + sec[1]) * 60).toFixed(2); geolib.sexagesimal[dec] = (deg + '° ' + min + "' " + sec + '"'); return geolib.sexagesimal[dec]; }
[ "function", "(", "dec", ")", "{", "if", "(", "dec", "in", "geolib", ".", "sexagesimal", ")", "{", "return", "geolib", ".", "sexagesimal", "[", "dec", "]", ";", "}", "var", "tmp", "=", "dec", ".", "toString", "(", ")", ".", "split", "(", "'.'", ")", ";", "var", "deg", "=", "Math", ".", "abs", "(", "tmp", "[", "0", "]", ")", ";", "var", "min", "=", "(", "'0.'", "+", "tmp", "[", "1", "]", ")", "*", "60", ";", "var", "sec", "=", "min", ".", "toString", "(", ")", ".", "split", "(", "'.'", ")", ";", "min", "=", "Math", ".", "floor", "(", "min", ")", ";", "sec", "=", "(", "(", "'0.'", "+", "sec", "[", "1", "]", ")", "*", "60", ")", ".", "toFixed", "(", "2", ")", ";", "geolib", ".", "sexagesimal", "[", "dec", "]", "=", "(", "deg", "+", "'° ' ", " ", "in ", " ", "' \" ", " ", "ec ", " ", "\"')", ";", "", "return", "geolib", ".", "sexagesimal", "[", "dec", "]", ";", "}" ]
Converts a decimal coordinate value to sexagesimal format @param float decimal @return string Sexagesimal value (XX° YY' ZZ")
[ "Converts", "a", "decimal", "coordinate", "value", "to", "sexagesimal", "format" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L828-L847
44,679
feilaoda/power
public/javascripts/vendor/javascripts/geolib.js
function(sexagesimal) { if (sexagesimal in geolib.decimal) { return geolib.decimal[sexagesimal]; } var regEx = new RegExp(sexagesimalPattern); var data = regEx.exec(sexagesimal); if(data) { var min = parseFloat(data[2]/60); var sec = parseFloat(data[4]/3600) || 0; } var dec = ((parseFloat(data[1]) + min + sec)).toFixed(8); // South and West are negative decimals dec = (data[7] == 'S' || data[7] == 'W') ? dec * -1 : dec; geolib.decimal[sexagesimal] = dec; return dec; }
javascript
function(sexagesimal) { if (sexagesimal in geolib.decimal) { return geolib.decimal[sexagesimal]; } var regEx = new RegExp(sexagesimalPattern); var data = regEx.exec(sexagesimal); if(data) { var min = parseFloat(data[2]/60); var sec = parseFloat(data[4]/3600) || 0; } var dec = ((parseFloat(data[1]) + min + sec)).toFixed(8); // South and West are negative decimals dec = (data[7] == 'S' || data[7] == 'W') ? dec * -1 : dec; geolib.decimal[sexagesimal] = dec; return dec; }
[ "function", "(", "sexagesimal", ")", "{", "if", "(", "sexagesimal", "in", "geolib", ".", "decimal", ")", "{", "return", "geolib", ".", "decimal", "[", "sexagesimal", "]", ";", "}", "var", "regEx", "=", "new", "RegExp", "(", "sexagesimalPattern", ")", ";", "var", "data", "=", "regEx", ".", "exec", "(", "sexagesimal", ")", ";", "if", "(", "data", ")", "{", "var", "min", "=", "parseFloat", "(", "data", "[", "2", "]", "/", "60", ")", ";", "var", "sec", "=", "parseFloat", "(", "data", "[", "4", "]", "/", "3600", ")", "||", "0", ";", "}", "var", "dec", "=", "(", "(", "parseFloat", "(", "data", "[", "1", "]", ")", "+", "min", "+", "sec", ")", ")", ".", "toFixed", "(", "8", ")", ";", "// South and West are negative decimals", "dec", "=", "(", "data", "[", "7", "]", "==", "'S'", "||", "data", "[", "7", "]", "==", "'W'", ")", "?", "dec", "*", "-", "1", ":", "dec", ";", "geolib", ".", "decimal", "[", "sexagesimal", "]", "=", "dec", ";", "return", "dec", ";", "}" ]
Converts a sexagesimal coordinate to decimal format @param float Sexagesimal coordinate @return string Decimal value (XX.XXXXXXXX)
[ "Converts", "a", "sexagesimal", "coordinate", "to", "decimal", "format" ]
89432e5b8e455eceef5f5098d479ad94c88acc59
https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/geolib.js#L856-L878
44,680
douglascvas/jsonutils
src/main/jsonUtils.js
function (jsonObject, path, force, value) { if (!path) { return; } var newValue, obj; obj = jsonObject || {}; path.trim().split('.').some(function (key, index, array) { if (!key && key !== 0) { return false; } newValue = obj[key]; if (index == array.length - 1) { if (value === undefined) { value = {}; } obj[key] = value; return true; } if (!newValue && newValue != 0 && index <= (array.length - 1)) { if (force) { obj[key] = {}; } else { return true; } } obj = obj[key]; }); return jsonObject; }
javascript
function (jsonObject, path, force, value) { if (!path) { return; } var newValue, obj; obj = jsonObject || {}; path.trim().split('.').some(function (key, index, array) { if (!key && key !== 0) { return false; } newValue = obj[key]; if (index == array.length - 1) { if (value === undefined) { value = {}; } obj[key] = value; return true; } if (!newValue && newValue != 0 && index <= (array.length - 1)) { if (force) { obj[key] = {}; } else { return true; } } obj = obj[key]; }); return jsonObject; }
[ "function", "(", "jsonObject", ",", "path", ",", "force", ",", "value", ")", "{", "if", "(", "!", "path", ")", "{", "return", ";", "}", "var", "newValue", ",", "obj", ";", "obj", "=", "jsonObject", "||", "{", "}", ";", "path", ".", "trim", "(", ")", ".", "split", "(", "'.'", ")", ".", "some", "(", "function", "(", "key", ",", "index", ",", "array", ")", "{", "if", "(", "!", "key", "&&", "key", "!==", "0", ")", "{", "return", "false", ";", "}", "newValue", "=", "obj", "[", "key", "]", ";", "if", "(", "index", "==", "array", ".", "length", "-", "1", ")", "{", "if", "(", "value", "===", "undefined", ")", "{", "value", "=", "{", "}", ";", "}", "obj", "[", "key", "]", "=", "value", ";", "return", "true", ";", "}", "if", "(", "!", "newValue", "&&", "newValue", "!=", "0", "&&", "index", "<=", "(", "array", ".", "length", "-", "1", ")", ")", "{", "if", "(", "force", ")", "{", "obj", "[", "key", "]", "=", "{", "}", ";", "}", "else", "{", "return", "true", ";", "}", "}", "obj", "=", "obj", "[", "key", "]", ";", "}", ")", ";", "return", "jsonObject", ";", "}" ]
Sets the value in the JSON object or create the path. @method setValue @private
[ "Sets", "the", "value", "in", "the", "JSON", "object", "or", "create", "the", "path", "." ]
44c2f77252467d2d4ab8daa616115b81dda31dd3
https://github.com/douglascvas/jsonutils/blob/44c2f77252467d2d4ab8daa616115b81dda31dd3/src/main/jsonUtils.js#L18-L47
44,681
odogono/elsinore-js
src/query/index.js
gatherEntityFilters
function gatherEntityFilters(context, expression) { let ii, len, bf, result, obj; let filter = expression[0]; result = EntityFilter.create(); switch (filter) { case ANY: case ANY_FILTER: case ALL: case ALL_FILTER: case NONE: case NONE_FILTER: case INCLUDE: case INCLUDE_FILTER: if (expression[1] === ROOT) { result.add(ROOT); } else { obj = context.valueOf(expression[1], true); if (!obj) { if (filter == ALL_FILTER) { result.add(ROOT); return; } return null; } bf = context.componentsToBitfield(context, obj); // filter = expression[0]; switch (filter) { case ALL_FILTER: filter = ALL; break; case ANY_FILTER: filter = ANY; break; case NONE_FILTER: filter = NONE; break; case INCLUDE_FILTER: filter = INCLUDE; break; default: break; } // console.log('CONVERTED TO BF', filter, bf.toString(), bf.toJSON() ); result.add(filter, bf); } break; case AND: expression = expression.slice(1); // _.rest(expression); for (ii = 0, len = expression.length; ii < len; ii++) { obj = gatherEntityFilters(context, expression[ii]); if (!obj) { return null; } result.filters = result.filters.concat(obj.filters); } break; default: return null; } return result; }
javascript
function gatherEntityFilters(context, expression) { let ii, len, bf, result, obj; let filter = expression[0]; result = EntityFilter.create(); switch (filter) { case ANY: case ANY_FILTER: case ALL: case ALL_FILTER: case NONE: case NONE_FILTER: case INCLUDE: case INCLUDE_FILTER: if (expression[1] === ROOT) { result.add(ROOT); } else { obj = context.valueOf(expression[1], true); if (!obj) { if (filter == ALL_FILTER) { result.add(ROOT); return; } return null; } bf = context.componentsToBitfield(context, obj); // filter = expression[0]; switch (filter) { case ALL_FILTER: filter = ALL; break; case ANY_FILTER: filter = ANY; break; case NONE_FILTER: filter = NONE; break; case INCLUDE_FILTER: filter = INCLUDE; break; default: break; } // console.log('CONVERTED TO BF', filter, bf.toString(), bf.toJSON() ); result.add(filter, bf); } break; case AND: expression = expression.slice(1); // _.rest(expression); for (ii = 0, len = expression.length; ii < len; ii++) { obj = gatherEntityFilters(context, expression[ii]); if (!obj) { return null; } result.filters = result.filters.concat(obj.filters); } break; default: return null; } return result; }
[ "function", "gatherEntityFilters", "(", "context", ",", "expression", ")", "{", "let", "ii", ",", "len", ",", "bf", ",", "result", ",", "obj", ";", "let", "filter", "=", "expression", "[", "0", "]", ";", "result", "=", "EntityFilter", ".", "create", "(", ")", ";", "switch", "(", "filter", ")", "{", "case", "ANY", ":", "case", "ANY_FILTER", ":", "case", "ALL", ":", "case", "ALL_FILTER", ":", "case", "NONE", ":", "case", "NONE_FILTER", ":", "case", "INCLUDE", ":", "case", "INCLUDE_FILTER", ":", "if", "(", "expression", "[", "1", "]", "===", "ROOT", ")", "{", "result", ".", "add", "(", "ROOT", ")", ";", "}", "else", "{", "obj", "=", "context", ".", "valueOf", "(", "expression", "[", "1", "]", ",", "true", ")", ";", "if", "(", "!", "obj", ")", "{", "if", "(", "filter", "==", "ALL_FILTER", ")", "{", "result", ".", "add", "(", "ROOT", ")", ";", "return", ";", "}", "return", "null", ";", "}", "bf", "=", "context", ".", "componentsToBitfield", "(", "context", ",", "obj", ")", ";", "// filter = expression[0];", "switch", "(", "filter", ")", "{", "case", "ALL_FILTER", ":", "filter", "=", "ALL", ";", "break", ";", "case", "ANY_FILTER", ":", "filter", "=", "ANY", ";", "break", ";", "case", "NONE_FILTER", ":", "filter", "=", "NONE", ";", "break", ";", "case", "INCLUDE_FILTER", ":", "filter", "=", "INCLUDE", ";", "break", ";", "default", ":", "break", ";", "}", "// console.log('CONVERTED TO BF', filter, bf.toString(), bf.toJSON() );", "result", ".", "add", "(", "filter", ",", "bf", ")", ";", "}", "break", ";", "case", "AND", ":", "expression", "=", "expression", ".", "slice", "(", "1", ")", ";", "// _.rest(expression);", "for", "(", "ii", "=", "0", ",", "len", "=", "expression", ".", "length", ";", "ii", "<", "len", ";", "ii", "++", ")", "{", "obj", "=", "gatherEntityFilters", "(", "context", ",", "expression", "[", "ii", "]", ")", ";", "if", "(", "!", "obj", ")", "{", "return", "null", ";", "}", "result", ".", "filters", "=", "result", ".", "filters", ".", "concat", "(", "obj", ".", "filters", ")", ";", "}", "break", ";", "default", ":", "return", "null", ";", "}", "return", "result", ";", "}" ]
Query functions for the memory based entity set. Some inspiration taken from https://github.com/aaronpowell/db.js
[ "Query", "functions", "for", "the", "memory", "based", "entity", "set", "." ]
1ecce67ad0022646419a740def029b1ba92dd558
https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/query/index.js#L389-L455
44,682
nodejitsu/contour
pagelets/nodejitsu/creditcard/base.js
initialize
function initialize() { var creditcard; // [square] @import "creditcard/index.js" this.lib = creditcard; // // Create references to elements. // this.number = this.$('input[name="full_number"]'); this.cvv = this.$('input[name="cvv"]'); this.year = this.$('select[name="expiration_year"]'); this.month = this.$('select[name="expiration_month"]'); this.card = this.$('.card'); // // Is validation required? // this.validate = !!this.$el.get('validate'); }
javascript
function initialize() { var creditcard; // [square] @import "creditcard/index.js" this.lib = creditcard; // // Create references to elements. // this.number = this.$('input[name="full_number"]'); this.cvv = this.$('input[name="cvv"]'); this.year = this.$('select[name="expiration_year"]'); this.month = this.$('select[name="expiration_month"]'); this.card = this.$('.card'); // // Is validation required? // this.validate = !!this.$el.get('validate'); }
[ "function", "initialize", "(", ")", "{", "var", "creditcard", ";", "// [square] @import \"creditcard/index.js\"", "this", ".", "lib", "=", "creditcard", ";", "//", "// Create references to elements.", "//", "this", ".", "number", "=", "this", ".", "$", "(", "'input[name=\"full_number\"]'", ")", ";", "this", ".", "cvv", "=", "this", ".", "$", "(", "'input[name=\"cvv\"]'", ")", ";", "this", ".", "year", "=", "this", ".", "$", "(", "'select[name=\"expiration_year\"]'", ")", ";", "this", ".", "month", "=", "this", ".", "$", "(", "'select[name=\"expiration_month\"]'", ")", ";", "this", ".", "card", "=", "this", ".", "$", "(", "'.card'", ")", ";", "//", "// Is validation required?", "//", "this", ".", "validate", "=", "!", "!", "this", ".", "$el", ".", "get", "(", "'validate'", ")", ";", "}" ]
Import the credit card library and store a reference in lib. @api private
[ "Import", "the", "credit", "card", "library", "and", "store", "a", "reference", "in", "lib", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/creditcard/base.js#L36-L54
44,683
nodejitsu/contour
pagelets/nodejitsu/creditcard/base.js
digit
function digit(event) { var element = event.element , code = event.keyCode || event.which , result; result = (code >= 48 && code <= 57) || code === 8 || code === 46; if (!result) event.preventDefault(); return { allowed: result, code: code, removal: code === 8 || code === 48 }; }
javascript
function digit(event) { var element = event.element , code = event.keyCode || event.which , result; result = (code >= 48 && code <= 57) || code === 8 || code === 46; if (!result) event.preventDefault(); return { allowed: result, code: code, removal: code === 8 || code === 48 }; }
[ "function", "digit", "(", "event", ")", "{", "var", "element", "=", "event", ".", "element", ",", "code", "=", "event", ".", "keyCode", "||", "event", ".", "which", ",", "result", ";", "result", "=", "(", "code", ">=", "48", "&&", "code", "<=", "57", ")", "||", "code", "===", "8", "||", "code", "===", "46", ";", "if", "(", "!", "result", ")", "event", ".", "preventDefault", "(", ")", ";", "return", "{", "allowed", ":", "result", ",", "code", ":", "code", ",", "removal", ":", "code", "===", "8", "||", "code", "===", "48", "}", ";", "}" ]
Only allow numbers in the number field. @api private
[ "Only", "allow", "numbers", "in", "the", "number", "field", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/creditcard/base.js#L61-L74
44,684
nodejitsu/contour
pagelets/nodejitsu/creditcard/base.js
date
function date(event) { var result = this.lib.expiry(this.month.get('value'), this.year.get('value')) , className = result ? 'valid' : 'invalid'; // // Update both select boxes. // this.month.removeClass('invalid').addClass(className); this.year.removeClass('invalid').addClass(className); }
javascript
function date(event) { var result = this.lib.expiry(this.month.get('value'), this.year.get('value')) , className = result ? 'valid' : 'invalid'; // // Update both select boxes. // this.month.removeClass('invalid').addClass(className); this.year.removeClass('invalid').addClass(className); }
[ "function", "date", "(", "event", ")", "{", "var", "result", "=", "this", ".", "lib", ".", "expiry", "(", "this", ".", "month", ".", "get", "(", "'value'", ")", ",", "this", ".", "year", ".", "get", "(", "'value'", ")", ")", ",", "className", "=", "result", "?", "'valid'", ":", "'invalid'", ";", "//", "// Update both select boxes.", "//", "this", ".", "month", ".", "removeClass", "(", "'invalid'", ")", ".", "addClass", "(", "className", ")", ";", "this", ".", "year", ".", "removeClass", "(", "'invalid'", ")", ".", "addClass", "(", "className", ")", ";", "}" ]
On date changes, year or month, check expiration date. @param {Event} event @api private
[ "On", "date", "changes", "year", "or", "month", "check", "expiration", "date", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/creditcard/base.js#L82-L91
44,685
nodejitsu/contour
pagelets/nodejitsu/creditcard/base.js
number
function number(event) { var element = event.element , value = element.value , key = this.digit(event) , valid; // // Input must be numerical. // if (!key.allowed && event.type !== 'blur') return; // // Always format if the event is of type blur. This will ensure the input // box does not stay red on blur if formatted value is valid. // if (event.type === 'blur') this.number.set('value', this.lib.format(value)); // // Check if the number is valid. // if (value.replace(/\D/g, '').length >= 16 || key.removal) { valid = this.lib.validate(value); // // Show card type or hide if invalid. // this.card[valid ? 'removeClass' : 'addClass']('gone'); this.card.find('strong').set('innerHTML', this.lib.cardscheme(value)); if (this.validate) { // // Check against testnumbers in production mode. Valid should be checked // as well, otherwise an incomplete credit card number would be valid. // if (this.production) { valid = valid && !~this.lib.testnumbers.indexOf(+value.replace(/\D/g, '')); } // // Update the styling of the input. // this.number.set('className', valid ? 'valid' : 'invalid'); } } // // Add spaces for each block of 4 characters. // this.number.set('value', this.lib.format(value)); }
javascript
function number(event) { var element = event.element , value = element.value , key = this.digit(event) , valid; // // Input must be numerical. // if (!key.allowed && event.type !== 'blur') return; // // Always format if the event is of type blur. This will ensure the input // box does not stay red on blur if formatted value is valid. // if (event.type === 'blur') this.number.set('value', this.lib.format(value)); // // Check if the number is valid. // if (value.replace(/\D/g, '').length >= 16 || key.removal) { valid = this.lib.validate(value); // // Show card type or hide if invalid. // this.card[valid ? 'removeClass' : 'addClass']('gone'); this.card.find('strong').set('innerHTML', this.lib.cardscheme(value)); if (this.validate) { // // Check against testnumbers in production mode. Valid should be checked // as well, otherwise an incomplete credit card number would be valid. // if (this.production) { valid = valid && !~this.lib.testnumbers.indexOf(+value.replace(/\D/g, '')); } // // Update the styling of the input. // this.number.set('className', valid ? 'valid' : 'invalid'); } } // // Add spaces for each block of 4 characters. // this.number.set('value', this.lib.format(value)); }
[ "function", "number", "(", "event", ")", "{", "var", "element", "=", "event", ".", "element", ",", "value", "=", "element", ".", "value", ",", "key", "=", "this", ".", "digit", "(", "event", ")", ",", "valid", ";", "//", "// Input must be numerical.", "//", "if", "(", "!", "key", ".", "allowed", "&&", "event", ".", "type", "!==", "'blur'", ")", "return", ";", "//", "// Always format if the event is of type blur. This will ensure the input", "// box does not stay red on blur if formatted value is valid.", "//", "if", "(", "event", ".", "type", "===", "'blur'", ")", "this", ".", "number", ".", "set", "(", "'value'", ",", "this", ".", "lib", ".", "format", "(", "value", ")", ")", ";", "//", "// Check if the number is valid.", "//", "if", "(", "value", ".", "replace", "(", "/", "\\D", "/", "g", ",", "''", ")", ".", "length", ">=", "16", "||", "key", ".", "removal", ")", "{", "valid", "=", "this", ".", "lib", ".", "validate", "(", "value", ")", ";", "//", "// Show card type or hide if invalid.", "//", "this", ".", "card", "[", "valid", "?", "'removeClass'", ":", "'addClass'", "]", "(", "'gone'", ")", ";", "this", ".", "card", ".", "find", "(", "'strong'", ")", ".", "set", "(", "'innerHTML'", ",", "this", ".", "lib", ".", "cardscheme", "(", "value", ")", ")", ";", "if", "(", "this", ".", "validate", ")", "{", "//", "// Check against testnumbers in production mode. Valid should be checked", "// as well, otherwise an incomplete credit card number would be valid.", "//", "if", "(", "this", ".", "production", ")", "{", "valid", "=", "valid", "&&", "!", "~", "this", ".", "lib", ".", "testnumbers", ".", "indexOf", "(", "+", "value", ".", "replace", "(", "/", "\\D", "/", "g", ",", "''", ")", ")", ";", "}", "//", "// Update the styling of the input.", "//", "this", ".", "number", ".", "set", "(", "'className'", ",", "valid", "?", "'valid'", ":", "'invalid'", ")", ";", "}", "}", "//", "// Add spaces for each block of 4 characters.", "//", "this", ".", "number", ".", "set", "(", "'value'", ",", "this", ".", "lib", ".", "format", "(", "value", ")", ")", ";", "}" ]
On credit card number changes, add spaces and check validaty. @param {Event} event @api private
[ "On", "credit", "card", "number", "changes", "add", "spaces", "and", "check", "validaty", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/creditcard/base.js#L99-L148
44,686
nodejitsu/contour
pagelets/nodejitsu/creditcard/base.js
cvv
function cvv(event) { var element = event.element , value = element.value , key = this.digit(event); // // Input must be numerical. // if (!key.allowed && event.type !== 'blur') return; // // Check if the number is valid. // if (this.validate && (value.length >= 3 || key.removal)) { this.cvv.set( 'className', this.lib.parse(this.number.get('value')).cvv === value.length ? 'valid' : 'invalid' ); } }
javascript
function cvv(event) { var element = event.element , value = element.value , key = this.digit(event); // // Input must be numerical. // if (!key.allowed && event.type !== 'blur') return; // // Check if the number is valid. // if (this.validate && (value.length >= 3 || key.removal)) { this.cvv.set( 'className', this.lib.parse(this.number.get('value')).cvv === value.length ? 'valid' : 'invalid' ); } }
[ "function", "cvv", "(", "event", ")", "{", "var", "element", "=", "event", ".", "element", ",", "value", "=", "element", ".", "value", ",", "key", "=", "this", ".", "digit", "(", "event", ")", ";", "//", "// Input must be numerical.", "//", "if", "(", "!", "key", ".", "allowed", "&&", "event", ".", "type", "!==", "'blur'", ")", "return", ";", "//", "// Check if the number is valid.", "//", "if", "(", "this", ".", "validate", "&&", "(", "value", ".", "length", ">=", "3", "||", "key", ".", "removal", ")", ")", "{", "this", ".", "cvv", ".", "set", "(", "'className'", ",", "this", ".", "lib", ".", "parse", "(", "this", ".", "number", ".", "get", "(", "'value'", ")", ")", ".", "cvv", "===", "value", ".", "length", "?", "'valid'", ":", "'invalid'", ")", ";", "}", "}" ]
On cvv changes check the content and validate. @param {Event} event @api private
[ "On", "cvv", "changes", "check", "the", "content", "and", "validate", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/creditcard/base.js#L156-L175
44,687
unshiftio/window.name
index.js
removeItem
function removeItem(key) { delete storage[key]; window.name = qs.stringify(storage, prefix); windowStorage.length--; }
javascript
function removeItem(key) { delete storage[key]; window.name = qs.stringify(storage, prefix); windowStorage.length--; }
[ "function", "removeItem", "(", "key", ")", "{", "delete", "storage", "[", "key", "]", ";", "window", ".", "name", "=", "qs", ".", "stringify", "(", "storage", ",", "prefix", ")", ";", "windowStorage", ".", "length", "--", ";", "}" ]
Remove a single item from the storage. @param {String} key Name of the value we need to remove. @returns {Undefined} @api pubilc
[ "Remove", "a", "single", "item", "from", "the", "storage", "." ]
525819d37de60aefc27b7307101888723cb31d3e
https://github.com/unshiftio/window.name/blob/525819d37de60aefc27b7307101888723cb31d3e/index.js#L81-L86
44,688
supersoaker/Grunt-RegPack
lib/packer.js
function(input, options) { this.preprocess(input, options); for (var inputIndex=0; inputIndex < this.inputList.length; ++inputIndex) { this.input = this.inputList[inputIndex][1][1].replace(/\\/g,'\\\\'); // first stage : configurable crusher var output = this.findRedundancies(options); this.inputList[inputIndex].push(output); // second stage : convert token string to regexp output = packer.packToRegexpCharClass(options); this.inputList[inputIndex].push(output); // third stage : try a negated regexp instead output = packer.packToNegatedRegexpCharClass(); this.inputList[inputIndex].push(output); } }
javascript
function(input, options) { this.preprocess(input, options); for (var inputIndex=0; inputIndex < this.inputList.length; ++inputIndex) { this.input = this.inputList[inputIndex][1][1].replace(/\\/g,'\\\\'); // first stage : configurable crusher var output = this.findRedundancies(options); this.inputList[inputIndex].push(output); // second stage : convert token string to regexp output = packer.packToRegexpCharClass(options); this.inputList[inputIndex].push(output); // third stage : try a negated regexp instead output = packer.packToNegatedRegexpCharClass(); this.inputList[inputIndex].push(output); } }
[ "function", "(", "input", ",", "options", ")", "{", "this", ".", "preprocess", "(", "input", ",", "options", ")", ";", "for", "(", "var", "inputIndex", "=", "0", ";", "inputIndex", "<", "this", ".", "inputList", ".", "length", ";", "++", "inputIndex", ")", "{", "this", ".", "input", "=", "this", ".", "inputList", "[", "inputIndex", "]", "[", "1", "]", "[", "1", "]", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'\\\\\\\\'", ")", ";", "// first stage : configurable crusher", "var", "output", "=", "this", ".", "findRedundancies", "(", "options", ")", ";", "this", ".", "inputList", "[", "inputIndex", "]", ".", "push", "(", "output", ")", ";", "// second stage : convert token string to regexp", "output", "=", "packer", ".", "packToRegexpCharClass", "(", "options", ")", ";", "this", ".", "inputList", "[", "inputIndex", "]", ".", "push", "(", "output", ")", ";", "// third stage : try a negated regexp instead", "output", "=", "packer", ".", "packToNegatedRegexpCharClass", "(", ")", ";", "this", ".", "inputList", "[", "inputIndex", "]", ".", "push", "(", "output", ")", ";", "}", "}" ]
Main entry point for RegPack
[ "Main", "entry", "point", "for", "RegPack" ]
848d995c673e7c6bd99188f4e37b6a02151ae884
https://github.com/supersoaker/Grunt-RegPack/blob/848d995c673e7c6bd99188f4e37b6a02151ae884/lib/packer.js#L90-L109
44,689
supersoaker/Grunt-RegPack
lib/packer.js
function(matchIndex) { var oldToken = this.matchesLookup[matchIndex].token; for (var j=0;j<this.matchesLookup.length;++j) { this.matchesLookup[j].usedBy = this.matchesLookup[j].usedBy.split(oldToken).join(""); } this.matchesLookup[matchIndex].cleared=true; }
javascript
function(matchIndex) { var oldToken = this.matchesLookup[matchIndex].token; for (var j=0;j<this.matchesLookup.length;++j) { this.matchesLookup[j].usedBy = this.matchesLookup[j].usedBy.split(oldToken).join(""); } this.matchesLookup[matchIndex].cleared=true; }
[ "function", "(", "matchIndex", ")", "{", "var", "oldToken", "=", "this", ".", "matchesLookup", "[", "matchIndex", "]", ".", "token", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "this", ".", "matchesLookup", ".", "length", ";", "++", "j", ")", "{", "this", ".", "matchesLookup", "[", "j", "]", ".", "usedBy", "=", "this", ".", "matchesLookup", "[", "j", "]", ".", "usedBy", ".", "split", "(", "oldToken", ")", ".", "join", "(", "\"\"", ")", ";", "}", "this", ".", "matchesLookup", "[", "matchIndex", "]", ".", "cleared", "=", "true", ";", "}" ]
Clears a match from matchesLookup for dependencies
[ "Clears", "a", "match", "from", "matchesLookup", "for", "dependencies" ]
848d995c673e7c6bd99188f4e37b6a02151ae884
https://github.com/supersoaker/Grunt-RegPack/blob/848d995c673e7c6bd99188f4e37b6a02151ae884/lib/packer.js#L863-L869
44,690
octet-stream/object-deep-from-entries
getTag.js
getTag
function getTag(val) { const tag = Object.prototype.toString.call(val).slice(8, -1) if (basicTypes.includes(tag.toLowerCase())) { return tag.toLowerCase() } return tag }
javascript
function getTag(val) { const tag = Object.prototype.toString.call(val).slice(8, -1) if (basicTypes.includes(tag.toLowerCase())) { return tag.toLowerCase() } return tag }
[ "function", "getTag", "(", "val", ")", "{", "const", "tag", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "val", ")", ".", "slice", "(", "8", ",", "-", "1", ")", "if", "(", "basicTypes", ".", "includes", "(", "tag", ".", "toLowerCase", "(", ")", ")", ")", "{", "return", "tag", ".", "toLowerCase", "(", ")", "}", "return", "tag", "}" ]
Get a string with type name of the given value @param {any} val @return {string} @api private
[ "Get", "a", "string", "with", "type", "name", "of", "the", "given", "value" ]
ea0c889c659150aeee6855f03ce7fbfba04ad99a
https://github.com/octet-stream/object-deep-from-entries/blob/ea0c889c659150aeee6855f03ce7fbfba04ad99a/getTag.js#L21-L29
44,691
jonschlinkert/question-cache
lib/question.js
Question
function Question(name, message, options) { if (utils.isObject(name)) { options = utils.merge({}, message, name); message = options.message; name = options.name; } if (utils.isObject(message)) { options = utils.merge({}, options, message); message = options.message; } utils.define(this, 'isQuestion', true); utils.define(this, 'cache', {}); this.options = options || {}; this.type = this.options.type || 'input'; this.message = message || this.options.message; this.name = name || this.options.name; if (!this.message) { this.message = this.name; } utils.merge(this, this.options); createNext(this); }
javascript
function Question(name, message, options) { if (utils.isObject(name)) { options = utils.merge({}, message, name); message = options.message; name = options.name; } if (utils.isObject(message)) { options = utils.merge({}, options, message); message = options.message; } utils.define(this, 'isQuestion', true); utils.define(this, 'cache', {}); this.options = options || {}; this.type = this.options.type || 'input'; this.message = message || this.options.message; this.name = name || this.options.name; if (!this.message) { this.message = this.name; } utils.merge(this, this.options); createNext(this); }
[ "function", "Question", "(", "name", ",", "message", ",", "options", ")", "{", "if", "(", "utils", ".", "isObject", "(", "name", ")", ")", "{", "options", "=", "utils", ".", "merge", "(", "{", "}", ",", "message", ",", "name", ")", ";", "message", "=", "options", ".", "message", ";", "name", "=", "options", ".", "name", ";", "}", "if", "(", "utils", ".", "isObject", "(", "message", ")", ")", "{", "options", "=", "utils", ".", "merge", "(", "{", "}", ",", "options", ",", "message", ")", ";", "message", "=", "options", ".", "message", ";", "}", "utils", ".", "define", "(", "this", ",", "'isQuestion'", ",", "true", ")", ";", "utils", ".", "define", "(", "this", ",", "'cache'", ",", "{", "}", ")", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "type", "=", "this", ".", "options", ".", "type", "||", "'input'", ";", "this", ".", "message", "=", "message", "||", "this", ".", "options", ".", "message", ";", "this", ".", "name", "=", "name", "||", "this", ".", "options", ".", "name", ";", "if", "(", "!", "this", ".", "message", ")", "{", "this", ".", "message", "=", "this", ".", "name", ";", "}", "utils", ".", "merge", "(", "this", ",", "this", ".", "options", ")", ";", "createNext", "(", "this", ")", ";", "}" ]
Create new `Question` store `name`, with the given `options`. ```js var question = new Question(name, options); ``` @param {String} `name` The question property name. @param {Object} `options` Store options @api public
[ "Create", "new", "Question", "store", "name", "with", "the", "given", "options", "." ]
85e4f1e00be1f230c435101f70c5da4227ce51ff
https://github.com/jonschlinkert/question-cache/blob/85e4f1e00be1f230c435101f70c5da4227ce51ff/lib/question.js#L25-L51
44,692
jonschlinkert/question-cache
lib/question.js
createNext
function createNext(question) { if (!question.options.next) return; if (typeof question.options.next === 'function') { question.next = function() { question.options.next.apply(question, arguments); }; return; } if (typeof question.options.next === 'string') { question.type = 'confirm'; question.next = function(answer, questions, answers, next) { if (answer === true) { questions.ask(question.options.next, next); } else { next(null, answers); } }; } }
javascript
function createNext(question) { if (!question.options.next) return; if (typeof question.options.next === 'function') { question.next = function() { question.options.next.apply(question, arguments); }; return; } if (typeof question.options.next === 'string') { question.type = 'confirm'; question.next = function(answer, questions, answers, next) { if (answer === true) { questions.ask(question.options.next, next); } else { next(null, answers); } }; } }
[ "function", "createNext", "(", "question", ")", "{", "if", "(", "!", "question", ".", "options", ".", "next", ")", "return", ";", "if", "(", "typeof", "question", ".", "options", ".", "next", "===", "'function'", ")", "{", "question", ".", "next", "=", "function", "(", ")", "{", "question", ".", "options", ".", "next", ".", "apply", "(", "question", ",", "arguments", ")", ";", "}", ";", "return", ";", "}", "if", "(", "typeof", "question", ".", "options", ".", "next", "===", "'string'", ")", "{", "question", ".", "type", "=", "'confirm'", ";", "question", ".", "next", "=", "function", "(", "answer", ",", "questions", ",", "answers", ",", "next", ")", "{", "if", "(", "answer", "===", "true", ")", "{", "questions", ".", "ask", "(", "question", ".", "options", ".", "next", ",", "next", ")", ";", "}", "else", "{", "next", "(", "null", ",", "answers", ")", ";", "}", "}", ";", "}", "}" ]
Create the next question to ask, if `next` is passed on the options. @param {Object} `app` question instance
[ "Create", "the", "next", "question", "to", "ask", "if", "next", "is", "passed", "on", "the", "options", "." ]
85e4f1e00be1f230c435101f70c5da4227ce51ff
https://github.com/jonschlinkert/question-cache/blob/85e4f1e00be1f230c435101f70c5da4227ce51ff/lib/question.js#L60-L80
44,693
Whitebolt/require-extra
src/eval.js
_parseConfig
function _parseConfig(config) { const _config = Object.assign({}, { filename:module.parent.filename, scope: settings.get('scope') || {}, includeGlobals:false, proxyGlobal:true, useSandbox: settings.get('useSandbox') || false, workspace: [workspaces.DEFAULT_WORKSPACE], squashErrors: !!(config.resolver || {}).squashErrors }, config); if (isBuffer(_config.content)) _config.content = _config.content.toString(); return _config; }
javascript
function _parseConfig(config) { const _config = Object.assign({}, { filename:module.parent.filename, scope: settings.get('scope') || {}, includeGlobals:false, proxyGlobal:true, useSandbox: settings.get('useSandbox') || false, workspace: [workspaces.DEFAULT_WORKSPACE], squashErrors: !!(config.resolver || {}).squashErrors }, config); if (isBuffer(_config.content)) _config.content = _config.content.toString(); return _config; }
[ "function", "_parseConfig", "(", "config", ")", "{", "const", "_config", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "filename", ":", "module", ".", "parent", ".", "filename", ",", "scope", ":", "settings", ".", "get", "(", "'scope'", ")", "||", "{", "}", ",", "includeGlobals", ":", "false", ",", "proxyGlobal", ":", "true", ",", "useSandbox", ":", "settings", ".", "get", "(", "'useSandbox'", ")", "||", "false", ",", "workspace", ":", "[", "workspaces", ".", "DEFAULT_WORKSPACE", "]", ",", "squashErrors", ":", "!", "!", "(", "config", ".", "resolver", "||", "{", "}", ")", ".", "squashErrors", "}", ",", "config", ")", ";", "if", "(", "isBuffer", "(", "_config", ".", "content", ")", ")", "_config", ".", "content", "=", "_config", ".", "content", ".", "toString", "(", ")", ";", "return", "_config", ";", "}" ]
Parse a config, adding defaults. @private @param {Object} config Config to parse. @returns {Object} Parsed config.
[ "Parse", "a", "config", "adding", "defaults", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L23-L37
44,694
Whitebolt/require-extra
src/eval.js
_createOptions
function _createOptions(config) { return { filename:config.filename, displayErrors:true, timeout: config.timeout || 20*1000 }; }
javascript
function _createOptions(config) { return { filename:config.filename, displayErrors:true, timeout: config.timeout || 20*1000 }; }
[ "function", "_createOptions", "(", "config", ")", "{", "return", "{", "filename", ":", "config", ".", "filename", ",", "displayErrors", ":", "true", ",", "timeout", ":", "config", ".", "timeout", "||", "20", "*", "1000", "}", ";", "}" ]
Given a config object create an options object for sandboxing operations. @private @param {Object} config Config for this creation. @returns {Object} Options for sandboxing operations.
[ "Given", "a", "config", "object", "create", "an", "options", "object", "for", "sandboxing", "operations", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L62-L68
44,695
Whitebolt/require-extra
src/eval.js
_createScript
function _createScript(config, options, scope={}) { if (!isString(config.content)) return config.content; const stringScript = wrap(config.content.replace(/^\#\!.*/, ''), scope); try { return new vm.Script(stringScript, options); } catch(error) { // These are not squashed as not evaluation errors but something else. if (_runError(error, module)) throw error; } }
javascript
function _createScript(config, options, scope={}) { if (!isString(config.content)) return config.content; const stringScript = wrap(config.content.replace(/^\#\!.*/, ''), scope); try { return new vm.Script(stringScript, options); } catch(error) { // These are not squashed as not evaluation errors but something else. if (_runError(error, module)) throw error; } }
[ "function", "_createScript", "(", "config", ",", "options", ",", "scope", "=", "{", "}", ")", "{", "if", "(", "!", "isString", "(", "config", ".", "content", ")", ")", "return", "config", ".", "content", ";", "const", "stringScript", "=", "wrap", "(", "config", ".", "content", ".", "replace", "(", "/", "^\\#\\!.*", "/", ",", "''", ")", ",", "scope", ")", ";", "try", "{", "return", "new", "vm", ".", "Script", "(", "stringScript", ",", "options", ")", ";", "}", "catch", "(", "error", ")", "{", "// These are not squashed as not evaluation errors but something else.", "if", "(", "_runError", "(", "error", ",", "module", ")", ")", "throw", "error", ";", "}", "}" ]
Given a config and some options create a script ready for vm sandboxing. @param {Object} config Config for this operation. @param {options} options Options for the script. @returns {VMScript} New script ready to use.
[ "Given", "a", "config", "and", "some", "options", "create", "a", "script", "ready", "for", "vm", "sandboxing", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L77-L85
44,696
Whitebolt/require-extra
src/eval.js
wrap
function wrap(content, scope) { const scopeParams = Object.keys(scope).join(','); const comma = ((scopeParams !== '')?', ':''); return `(function (exports, require, module, __filename, __dirname${comma}${scopeParams}) { ${content} });` }
javascript
function wrap(content, scope) { const scopeParams = Object.keys(scope).join(','); const comma = ((scopeParams !== '')?', ':''); return `(function (exports, require, module, __filename, __dirname${comma}${scopeParams}) { ${content} });` }
[ "function", "wrap", "(", "content", ",", "scope", ")", "{", "const", "scopeParams", "=", "Object", ".", "keys", "(", "scope", ")", ".", "join", "(", "','", ")", ";", "const", "comma", "=", "(", "(", "scopeParams", "!==", "''", ")", "?", "', '", ":", "''", ")", ";", "return", "`", "${", "comma", "}", "${", "scopeParams", "}", "${", "content", "}", "`", "}" ]
Wrap the script content with scape parameters, including optional extra ones. @param {string} content Content to wrap. @param {Object} scope Scope parameters to add. @returns {string} Wrapped script content.
[ "Wrap", "the", "script", "content", "with", "scape", "parameters", "including", "optional", "extra", "ones", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L94-L100
44,697
Whitebolt/require-extra
src/eval.js
_getScopeParams
function _getScopeParams(config, module, scope={}) { return [ module.exports, module.require, module, module.filename, config.basedir || path.dirname(module.filename), ...values(scope) ]; }
javascript
function _getScopeParams(config, module, scope={}) { return [ module.exports, module.require, module, module.filename, config.basedir || path.dirname(module.filename), ...values(scope) ]; }
[ "function", "_getScopeParams", "(", "config", ",", "module", ",", "scope", "=", "{", "}", ")", "{", "return", "[", "module", ".", "exports", ",", "module", ".", "require", ",", "module", ",", "module", ".", "filename", ",", "config", ".", "basedir", "||", "path", ".", "dirname", "(", "module", ".", "filename", ")", ",", "...", "values", "(", "scope", ")", "]", ";", "}" ]
Get scoped parameters to pass to wrap function. @private @param {Object} config The config options. @param {Module} module The module. @returns {Array.<*>} Parameters.
[ "Get", "scoped", "parameters", "to", "pass", "to", "wrap", "function", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L110-L119
44,698
Whitebolt/require-extra
src/eval.js
_runError
function _runError(error, module) { const _error = new emitter.Error({ target:module.filename, source:(module.parent || module).filename, error }); module.exports = _error; emitter.emit('error', _error); return (!!_error.ignore || (_error.ignore && isFunction(_error.ignore) && _error.ignore())); }
javascript
function _runError(error, module) { const _error = new emitter.Error({ target:module.filename, source:(module.parent || module).filename, error }); module.exports = _error; emitter.emit('error', _error); return (!!_error.ignore || (_error.ignore && isFunction(_error.ignore) && _error.ignore())); }
[ "function", "_runError", "(", "error", ",", "module", ")", "{", "const", "_error", "=", "new", "emitter", ".", "Error", "(", "{", "target", ":", "module", ".", "filename", ",", "source", ":", "(", "module", ".", "parent", "||", "module", ")", ".", "filename", ",", "error", "}", ")", ";", "module", ".", "exports", "=", "_error", ";", "emitter", ".", "emit", "(", "'error'", ",", "_error", ")", ";", "return", "(", "!", "!", "_error", ".", "ignore", "||", "(", "_error", ".", "ignore", "&&", "isFunction", "(", "_error", ".", "ignore", ")", "&&", "_error", ".", "ignore", "(", ")", ")", ")", ";", "}" ]
Handle run errors. @private @param {Error} error The error thrown. @param {Module} module The module.
[ "Handle", "run", "errors", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L128-L137
44,699
Whitebolt/require-extra
src/eval.js
_runScript
function _runScript(config, options) { const useSandbox = ((isFunction(config.useSandbox)) ? _config.useSandbox(_config) || false : config.useSandbox); const module = new Module(config); const scopeParams = _getScopeParams(config, module, config.scope); const script = _createScript(config, options, config.scope); try { if (useSandbox) { script.runInContext(_createSandbox(config), options)(...scopeParams); } else { script.runInThisContext(options)(...scopeParams); } } catch(error) { if (config.squashErrors) cache.delete(options.filename); if (!config.squashErrors) { if (_runError(error, module)) throw error; } else { throw error; } } return module; }
javascript
function _runScript(config, options) { const useSandbox = ((isFunction(config.useSandbox)) ? _config.useSandbox(_config) || false : config.useSandbox); const module = new Module(config); const scopeParams = _getScopeParams(config, module, config.scope); const script = _createScript(config, options, config.scope); try { if (useSandbox) { script.runInContext(_createSandbox(config), options)(...scopeParams); } else { script.runInThisContext(options)(...scopeParams); } } catch(error) { if (config.squashErrors) cache.delete(options.filename); if (!config.squashErrors) { if (_runError(error, module)) throw error; } else { throw error; } } return module; }
[ "function", "_runScript", "(", "config", ",", "options", ")", "{", "const", "useSandbox", "=", "(", "(", "isFunction", "(", "config", ".", "useSandbox", ")", ")", "?", "_config", ".", "useSandbox", "(", "_config", ")", "||", "false", ":", "config", ".", "useSandbox", ")", ";", "const", "module", "=", "new", "Module", "(", "config", ")", ";", "const", "scopeParams", "=", "_getScopeParams", "(", "config", ",", "module", ",", "config", ".", "scope", ")", ";", "const", "script", "=", "_createScript", "(", "config", ",", "options", ",", "config", ".", "scope", ")", ";", "try", "{", "if", "(", "useSandbox", ")", "{", "script", ".", "runInContext", "(", "_createSandbox", "(", "config", ")", ",", "options", ")", "(", "...", "scopeParams", ")", ";", "}", "else", "{", "script", ".", "runInThisContext", "(", "options", ")", "(", "...", "scopeParams", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "if", "(", "config", ".", "squashErrors", ")", "cache", ".", "delete", "(", "options", ".", "filename", ")", ";", "if", "(", "!", "config", ".", "squashErrors", ")", "{", "if", "(", "_runError", "(", "error", ",", "module", ")", ")", "throw", "error", ";", "}", "else", "{", "throw", "error", ";", "}", "}", "return", "module", ";", "}" ]
Run the given script in the given sandbox, according to the given config and options. @private @param {Object} config Config to use. @param {Object} options Options for running. @returns {Module} The module created.
[ "Run", "the", "given", "script", "in", "the", "given", "sandbox", "according", "to", "the", "given", "config", "and", "options", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/eval.js#L147-L169