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
40,800
andywer/postcss-debug
webdebugger/build/app.js
batchedMountComponentIntoNode
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); }
javascript
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); }
[ "function", "batchedMountComponentIntoNode", "(", "componentInstance", ",", "container", ",", "shouldReuseMarkup", ",", "context", ")", "{", "var", "transaction", "=", "ReactUpdates", ".", "ReactReconcileTransaction", ".", "getPooled", "(", "/* useCreateElement */", "!", "shouldReuseMarkup", "&&", "ReactDOMFeatureFlags", ".", "useCreateElement", ")", ";", "transaction", ".", "perform", "(", "mountComponentIntoNode", ",", "null", ",", "componentInstance", ",", "container", ",", "transaction", ",", "shouldReuseMarkup", ",", "context", ")", ";", "ReactUpdates", ".", "ReactReconcileTransaction", ".", "release", "(", "transaction", ")", ";", "}" ]
Batched mount. @param {ReactComponent} componentInstance The instance to mount. @param {DOMElement} container DOM element to mount into. @param {boolean} shouldReuseMarkup If true, do not insert markup
[ "Batched", "mount", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10375-L10381
40,801
andywer/postcss-debug
webdebugger/build/app.js
hasNonRootReactChild
function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } }
javascript
function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } }
[ "function", "hasNonRootReactChild", "(", "container", ")", "{", "var", "rootEl", "=", "getReactRootElementInContainer", "(", "container", ")", ";", "if", "(", "rootEl", ")", "{", "var", "inst", "=", "ReactDOMComponentTree", ".", "getInstanceFromNode", "(", "rootEl", ")", ";", "return", "!", "!", "(", "inst", "&&", "inst", ".", "_hostParent", ")", ";", "}", "}" ]
True if the supplied DOM node has a direct React-rendered child that is not a React root element. Useful for warning in `render`, `unmountComponentAtNode`, etc. @param {?DOMElement} node The candidate DOM node. @return {boolean} True if the DOM element contains a direct child that was rendered by React but is not a root element. @internal
[ "True", "if", "the", "supplied", "DOM", "node", "has", "a", "direct", "React", "-", "rendered", "child", "that", "is", "not", "a", "React", "root", "element", ".", "Useful", "for", "warning", "in", "render", "unmountComponentAtNode", "etc", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10421-L10427
40,802
andywer/postcss-debug
webdebugger/build/app.js
function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; if (process.env.NODE_ENV !== 'production') { // The instance here is TopLevelWrapper so we report mount for its child. ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID); } return componentInstance; }
javascript
function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; if (process.env.NODE_ENV !== 'production') { // The instance here is TopLevelWrapper so we report mount for its child. ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID); } return componentInstance; }
[ "function", "(", "nextElement", ",", "container", ",", "shouldReuseMarkup", ",", "context", ")", "{", "// Various parts of our code (such as ReactCompositeComponent's", "// _renderValidatedComponent) assume that calls to render aren't nested;", "// verify that that's the case.", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "warning", "(", "ReactCurrentOwner", ".", "current", "==", "null", ",", "'_renderNewRootComponent(): Render methods should be a pure function '", "+", "'of props and state; triggering nested component updates from '", "+", "'render is not allowed. If necessary, trigger nested updates in '", "+", "'componentDidUpdate. Check the render method of %s.'", ",", "ReactCurrentOwner", ".", "current", "&&", "ReactCurrentOwner", ".", "current", ".", "getName", "(", ")", "||", "'ReactCompositeComponent'", ")", ":", "void", "0", ";", "!", "(", "container", "&&", "(", "container", ".", "nodeType", "===", "ELEMENT_NODE_TYPE", "||", "container", ".", "nodeType", "===", "DOC_NODE_TYPE", "||", "container", ".", "nodeType", "===", "DOCUMENT_FRAGMENT_NODE_TYPE", ")", ")", "?", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "invariant", "(", "false", ",", "'_registerComponent(...): Target container is not a DOM element.'", ")", ":", "_prodInvariant", "(", "'37'", ")", ":", "void", "0", ";", "ReactBrowserEventEmitter", ".", "ensureScrollValueMonitoring", "(", ")", ";", "var", "componentInstance", "=", "instantiateReactComponent", "(", "nextElement", ",", "false", ")", ";", "// The initial render is synchronous but any updates that happen during", "// rendering, in componentWillMount or componentDidMount, will be batched", "// according to the current batching strategy.", "ReactUpdates", ".", "batchedUpdates", "(", "batchedMountComponentIntoNode", ",", "componentInstance", ",", "container", ",", "shouldReuseMarkup", ",", "context", ")", ";", "var", "wrapperID", "=", "componentInstance", ".", "_instance", ".", "rootID", ";", "instancesByReactRootID", "[", "wrapperID", "]", "=", "componentInstance", ";", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "// The instance here is TopLevelWrapper so we report mount for its child.", "ReactInstrumentation", ".", "debugTool", ".", "onMountRootComponent", "(", "componentInstance", ".", "_renderedComponent", ".", "_debugID", ")", ";", "}", "return", "componentInstance", ";", "}" ]
Render a new component into the DOM. Hooked by devtools! @param {ReactElement} nextElement element to render @param {DOMElement} container container to render into @param {boolean} shouldReuseMarkup if we should skip the markup insertion @return {ReactComponent} nextComponent
[ "Render", "a", "new", "component", "into", "the", "DOM", ".", "Hooked", "by", "devtools!" ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10523-L10549
40,803
andywer/postcss-debug
webdebugger/build/app.js
findDOMNode
function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44'); } else { process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)); } }
javascript
function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44'); } else { process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)); } }
[ "function", "findDOMNode", "(", "componentOrElement", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "var", "owner", "=", "ReactCurrentOwner", ".", "current", ";", "if", "(", "owner", "!==", "null", ")", "{", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "warning", "(", "owner", ".", "_warnedAboutRefsInRender", ",", "'%s is accessing findDOMNode inside its render(). '", "+", "'render() should be a pure function of props and state. It should '", "+", "'never access something that requires stale data from the previous '", "+", "'render, such as refs. Move this logic to componentDidMount and '", "+", "'componentDidUpdate instead.'", ",", "owner", ".", "getName", "(", ")", "||", "'A component'", ")", ":", "void", "0", ";", "owner", ".", "_warnedAboutRefsInRender", "=", "true", ";", "}", "}", "if", "(", "componentOrElement", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "componentOrElement", ".", "nodeType", "===", "1", ")", "{", "return", "componentOrElement", ";", "}", "var", "inst", "=", "ReactInstanceMap", ".", "get", "(", "componentOrElement", ")", ";", "if", "(", "inst", ")", "{", "inst", "=", "getHostComponentFromComposite", "(", "inst", ")", ";", "return", "inst", "?", "ReactDOMComponentTree", ".", "getNodeFromInstance", "(", "inst", ")", ":", "null", ";", "}", "if", "(", "typeof", "componentOrElement", ".", "render", "===", "'function'", ")", "{", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "invariant", "(", "false", ",", "'findDOMNode was called on an unmounted component.'", ")", ":", "_prodInvariant", "(", "'44'", ")", ";", "}", "else", "{", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "invariant", "(", "false", ",", "'Element appears to be neither ReactComponent nor DOMNode (keys: %s)'", ",", "Object", ".", "keys", "(", "componentOrElement", ")", ")", ":", "_prodInvariant", "(", "'45'", ",", "Object", ".", "keys", "(", "componentOrElement", ")", ")", ";", "}", "}" ]
Returns the DOM node rendered by this element. See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode @param {ReactComponent|DOMElement} componentOrElement @return {?DOMElement} The root node of this element.
[ "Returns", "the", "DOM", "node", "rendered", "by", "this", "element", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L10845-L10871
40,804
andywer/postcss-debug
webdebugger/build/app.js
function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } }
javascript
function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } }
[ "function", "(", "callback", ",", "a", ",", "b", ",", "c", ",", "d", ",", "e", ")", "{", "var", "alreadyBatchingUpdates", "=", "ReactDefaultBatchingStrategy", ".", "isBatchingUpdates", ";", "ReactDefaultBatchingStrategy", ".", "isBatchingUpdates", "=", "true", ";", "// The code is written this way to avoid extra allocations", "if", "(", "alreadyBatchingUpdates", ")", "{", "callback", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ")", ";", "}", "else", "{", "transaction", ".", "perform", "(", "callback", ",", "null", ",", "a", ",", "b", ",", "c", ",", "d", ",", "e", ")", ";", "}", "}" ]
Call the provided function in a context within which calls to `setState` and friends are batched such that components aren't updated unnecessarily.
[ "Call", "the", "provided", "function", "in", "a", "context", "within", "which", "calls", "to", "setState", "and", "friends", "are", "batched", "such", "that", "components", "aren", "t", "updated", "unnecessarily", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L14495-L14506
40,805
andywer/postcss-debug
webdebugger/build/app.js
hasArrayNature
function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); }
javascript
function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); }
[ "function", "hasArrayNature", "(", "obj", ")", "{", "return", "(", "// not null/false", "!", "!", "obj", "&&", "(", "// arrays are objects, NodeLists are functions in Safari", "typeof", "obj", "==", "'object'", "||", "typeof", "obj", "==", "'function'", ")", "&&", "// quacks like an array", "'length'", "in", "obj", "&&", "// not window", "!", "(", "'setInterval'", "in", "obj", ")", "&&", "// no DOM node should be considered an array-like", "// a 'select' element has 'length' and 'item' properties on IE8", "typeof", "obj", ".", "nodeType", "!=", "'number'", "&&", "(", "// a real array", "Array", ".", "isArray", "(", "obj", ")", "||", "// arguments", "'callee'", "in", "obj", "||", "// HTMLCollection/NodeList", "'item'", "in", "obj", ")", ")", ";", "}" ]
Perform a heuristic test to determine if an object is "array-like". A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" Joshu replied: "Mu." This function determines if its argument has "array nature": it returns true if the argument is an actual array, an `arguments' object, or an HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). It will return false for other array-like objects like Filelist. @param {*} obj @return {boolean}
[ "Perform", "a", "heuristic", "test", "to", "determine", "if", "an", "object", "is", "array", "-", "like", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L14723-L14743
40,806
andywer/postcss-debug
webdebugger/build/app.js
getParentInstance
function getParentInstance(inst) { !('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; }
javascript
function getParentInstance(inst) { !('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; }
[ "function", "getParentInstance", "(", "inst", ")", "{", "!", "(", "'_hostNode'", "in", "inst", ")", "?", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "invariant", "(", "false", ",", "'getParentInstance: Invalid argument.'", ")", ":", "_prodInvariant", "(", "'36'", ")", ":", "void", "0", ";", "return", "inst", ".", "_hostParent", ";", "}" ]
Return the parent instance of the passed-in instance.
[ "Return", "the", "parent", "instance", "of", "the", "passed", "-", "in", "instance", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L15375-L15379
40,807
andywer/postcss-debug
webdebugger/build/app.js
makeMove
function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; }
javascript
function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; }
[ "function", "makeMove", "(", "child", ",", "afterNode", ",", "toIndex", ")", "{", "// NOTE: Null values reduce hidden classes.", "return", "{", "type", ":", "ReactMultiChildUpdateTypes", ".", "MOVE_EXISTING", ",", "content", ":", "null", ",", "fromIndex", ":", "child", ".", "_mountIndex", ",", "fromNode", ":", "ReactReconciler", ".", "getHostNode", "(", "child", ")", ",", "toIndex", ":", "toIndex", ",", "afterNode", ":", "afterNode", "}", ";", "}" ]
Make an update for moving an existing element to another index. @param {number} fromIndex Source index of the existing element. @param {number} toIndex Destination index of the element. @private
[ "Make", "an", "update", "for", "moving", "an", "existing", "element", "to", "another", "index", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L16033-L16043
40,808
andywer/postcss-debug
webdebugger/build/app.js
function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }
javascript
function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }
[ "function", "(", "child", ",", "mountImage", ",", "afterNode", ",", "index", ",", "transaction", ",", "context", ")", "{", "child", ".", "_mountIndex", "=", "index", ";", "return", "this", ".", "createChild", "(", "child", ",", "afterNode", ",", "mountImage", ")", ";", "}" ]
Mounts a child with the supplied name. NOTE: This is part of `updateChildren` and is here for readability. @param {ReactComponent} child Component to mount. @param {string} name Name of the child. @param {number} index Index at which to insert the child. @param {ReactReconcileTransaction} transaction @private
[ "Mounts", "a", "child", "with", "the", "supplied", "name", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L16408-L16411
40,809
andywer/postcss-debug
webdebugger/build/app.js
function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; }
javascript
function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; }
[ "function", "(", "child", ",", "node", ")", "{", "var", "update", "=", "this", ".", "removeChild", "(", "child", ",", "node", ")", ";", "child", ".", "_mountIndex", "=", "null", ";", "return", "update", ";", "}" ]
Unmounts a rendered child. NOTE: This is part of `updateChildren` and is here for readability. @param {ReactComponent} child Component to unmount. @private
[ "Unmounts", "a", "rendered", "child", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L16421-L16425
40,810
andywer/postcss-debug
webdebugger/build/app.js
function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); }
javascript
function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); }
[ "function", "(", "parentInst", ",", "updates", ")", "{", "var", "node", "=", "ReactDOMComponentTree", ".", "getNodeFromInstance", "(", "parentInst", ")", ";", "DOMChildrenOperations", ".", "processUpdates", "(", "node", ",", "updates", ")", ";", "}" ]
Updates a component's children by processing a series of updates. @param {array<object>} updates List of update configurations. @internal
[ "Updates", "a", "component", "s", "children", "by", "processing", "a", "series", "of", "updates", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L17961-L17964
40,811
vorg/webgl-debug
index.js
function(msg) { if (window.console && window.console.error) { window.console.error(msg); } else { log(msg); } }
javascript
function(msg) { if (window.console && window.console.error) { window.console.error(msg); } else { log(msg); } }
[ "function", "(", "msg", ")", "{", "if", "(", "window", ".", "console", "&&", "window", ".", "console", ".", "error", ")", "{", "window", ".", "console", ".", "error", "(", "msg", ")", ";", "}", "else", "{", "log", "(", "msg", ")", ";", "}", "}" ]
Wrapped error logging function. @param {string} msg Message to log.
[ "Wrapped", "error", "logging", "function", "." ]
a0b141f64a9150d02f2e1714aad40e798fc5b124
https://github.com/vorg/webgl-debug/blob/a0b141f64a9150d02f2e1714aad40e798fc5b124/index.js#L50-L56
40,812
vorg/webgl-debug
index.js
makeFunctionWrapper
function makeFunctionWrapper(original, functionName) { //log("wrap fn: " + functionName); var f = original[functionName]; return function() { //log("call: " + functionName); var result = f.apply(original, arguments); return result; }; }
javascript
function makeFunctionWrapper(original, functionName) { //log("wrap fn: " + functionName); var f = original[functionName]; return function() { //log("call: " + functionName); var result = f.apply(original, arguments); return result; }; }
[ "function", "makeFunctionWrapper", "(", "original", ",", "functionName", ")", "{", "//log(\"wrap fn: \" + functionName);", "var", "f", "=", "original", "[", "functionName", "]", ";", "return", "function", "(", ")", "{", "//log(\"call: \" + functionName);", "var", "result", "=", "f", ".", "apply", "(", "original", ",", "arguments", ")", ";", "return", "result", ";", "}", ";", "}" ]
Makes a function that calls a function on another object.
[ "Makes", "a", "function", "that", "calls", "a", "function", "on", "another", "object", "." ]
a0b141f64a9150d02f2e1714aad40e798fc5b124
https://github.com/vorg/webgl-debug/blob/a0b141f64a9150d02f2e1714aad40e798fc5b124/index.js#L434-L442
40,813
vorg/webgl-debug
index.js
makeLostContextFunctionWrapper
function makeLostContextFunctionWrapper(ctx, functionName) { var f = ctx[functionName]; return function() { // log("calling:" + functionName); // Only call the functions if the context is not lost. loseContextIfTime(); if (!contextLost_) { //if (!checkResources(arguments)) { // glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true; // return; //} var result = f.apply(ctx, arguments); return result; } }; }
javascript
function makeLostContextFunctionWrapper(ctx, functionName) { var f = ctx[functionName]; return function() { // log("calling:" + functionName); // Only call the functions if the context is not lost. loseContextIfTime(); if (!contextLost_) { //if (!checkResources(arguments)) { // glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true; // return; //} var result = f.apply(ctx, arguments); return result; } }; }
[ "function", "makeLostContextFunctionWrapper", "(", "ctx", ",", "functionName", ")", "{", "var", "f", "=", "ctx", "[", "functionName", "]", ";", "return", "function", "(", ")", "{", "// log(\"calling:\" + functionName);", "// Only call the functions if the context is not lost.", "loseContextIfTime", "(", ")", ";", "if", "(", "!", "contextLost_", ")", "{", "//if (!checkResources(arguments)) {", "// glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true;", "// return;", "//}", "var", "result", "=", "f", ".", "apply", "(", "ctx", ",", "arguments", ")", ";", "return", "result", ";", "}", "}", ";", "}" ]
Makes a function that simulates WebGL when out of context.
[ "Makes", "a", "function", "that", "simulates", "WebGL", "when", "out", "of", "context", "." ]
a0b141f64a9150d02f2e1714aad40e798fc5b124
https://github.com/vorg/webgl-debug/blob/a0b141f64a9150d02f2e1714aad40e798fc5b124/index.js#L813-L828
40,814
postmanlabs/sails-mysql-transactions
lib/transactions.js
function (config) { // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup. if (Transaction.databases[config.identity]) { // @todo - emit wrror event instead of console.log console.log('Warn: duplicate setup of connection found in Transactions.setup'); this.teardown(); } var _db; // clone the configuration config = util.clone(config); delete config.replication; // allow special transaction related config util.each(config, function (value, name, config) { if (!/^transaction.+/g.test(name)) { return; } // remove transaction config prefix var baseName = name.replace(/^transaction/g, ''); baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1); delete config[name]; config[baseName] = value; }); _db = db.createSource(config); // Save a few configurations _db && (_db.transactionConfig = { rollbackOnError: config.rollbackTransactionOnError }); Transaction.databases[config.identity] = _db; }
javascript
function (config) { // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup. if (Transaction.databases[config.identity]) { // @todo - emit wrror event instead of console.log console.log('Warn: duplicate setup of connection found in Transactions.setup'); this.teardown(); } var _db; // clone the configuration config = util.clone(config); delete config.replication; // allow special transaction related config util.each(config, function (value, name, config) { if (!/^transaction.+/g.test(name)) { return; } // remove transaction config prefix var baseName = name.replace(/^transaction/g, ''); baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1); delete config[name]; config[baseName] = value; }); _db = db.createSource(config); // Save a few configurations _db && (_db.transactionConfig = { rollbackOnError: config.rollbackTransactionOnError }); Transaction.databases[config.identity] = _db; }
[ "function", "(", "config", ")", "{", "// at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.", "if", "(", "Transaction", ".", "databases", "[", "config", ".", "identity", "]", ")", "{", "// @todo - emit wrror event instead of console.log", "console", ".", "log", "(", "'Warn: duplicate setup of connection found in Transactions.setup'", ")", ";", "this", ".", "teardown", "(", ")", ";", "}", "var", "_db", ";", "// clone the configuration", "config", "=", "util", ".", "clone", "(", "config", ")", ";", "delete", "config", ".", "replication", ";", "// allow special transaction related config", "util", ".", "each", "(", "config", ",", "function", "(", "value", ",", "name", ",", "config", ")", "{", "if", "(", "!", "/", "^transaction.+", "/", "g", ".", "test", "(", "name", ")", ")", "{", "return", ";", "}", "// remove transaction config prefix", "var", "baseName", "=", "name", ".", "replace", "(", "/", "^transaction", "/", "g", ",", "''", ")", ";", "baseName", "=", "baseName", ".", "charAt", "(", "0", ")", ".", "toLowerCase", "(", ")", "+", "baseName", ".", "slice", "(", "1", ")", ";", "delete", "config", "[", "name", "]", ";", "config", "[", "baseName", "]", "=", "value", ";", "}", ")", ";", "_db", "=", "db", ".", "createSource", "(", "config", ")", ";", "// Save a few configurations", "_db", "&&", "(", "_db", ".", "transactionConfig", "=", "{", "rollbackOnError", ":", "config", ".", "rollbackTransactionOnError", "}", ")", ";", "Transaction", ".", "databases", "[", "config", ".", "identity", "]", "=", "_db", ";", "}" ]
For first run, the transactions environment needs to be setup. Without that, it is not possible to procure new database connections.
[ "For", "first", "run", "the", "transactions", "environment", "needs", "to", "be", "setup", ".", "Without", "that", "it", "is", "not", "possible", "to", "procure", "new", "database", "connections", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L79-L113
40,815
postmanlabs/sails-mysql-transactions
lib/transactions.js
function () { // just to be sure! clear all items in the connections object. they should be cleared by now util.each(this.connections, function (value, prop, conns) { try { value.release(); } catch (e) { } // nothing to do with error delete conns[prop]; }); // now execute end on the databases. will end pool if pool, or otherwise will execute whatever // `end` that has been exposed by db.js util.each(Transaction.databases, function (value, prop, databases) { value.end(); databases[prop] = null; }); }
javascript
function () { // just to be sure! clear all items in the connections object. they should be cleared by now util.each(this.connections, function (value, prop, conns) { try { value.release(); } catch (e) { } // nothing to do with error delete conns[prop]; }); // now execute end on the databases. will end pool if pool, or otherwise will execute whatever // `end` that has been exposed by db.js util.each(Transaction.databases, function (value, prop, databases) { value.end(); databases[prop] = null; }); }
[ "function", "(", ")", "{", "// just to be sure! clear all items in the connections object. they should be cleared by now", "util", ".", "each", "(", "this", ".", "connections", ",", "function", "(", "value", ",", "prop", ",", "conns", ")", "{", "try", "{", "value", ".", "release", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "// nothing to do with error", "delete", "conns", "[", "prop", "]", ";", "}", ")", ";", "// now execute end on the databases. will end pool if pool, or otherwise will execute whatever", "// `end` that has been exposed by db.js", "util", ".", "each", "(", "Transaction", ".", "databases", ",", "function", "(", "value", ",", "prop", ",", "databases", ")", "{", "value", ".", "end", "(", ")", ";", "databases", "[", "prop", "]", "=", "null", ";", "}", ")", ";", "}" ]
This function needs to be called at the end of app-lifecycle to ensure all db connections are closed.
[ "This", "function", "needs", "to", "be", "called", "at", "the", "end", "of", "app", "-", "lifecycle", "to", "ensure", "all", "db", "connections", "are", "closed", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L118-L134
40,816
postmanlabs/sails-mysql-transactions
lib/transactions.js
function () { var connection = this.connection(); // if a connection is defined, get the ID from connection if (connection) { if (!connection.transactionId) { throw new AdapterError(AdapterError.TRANSACTION_NOT_ASSOCIATED); } return (this._id = connection.transactionId); // save it just in case, during return } // at this point if we do not have an id, we know that we will need to return a dummy one return this._id || (this._id = util.uid()); }
javascript
function () { var connection = this.connection(); // if a connection is defined, get the ID from connection if (connection) { if (!connection.transactionId) { throw new AdapterError(AdapterError.TRANSACTION_NOT_ASSOCIATED); } return (this._id = connection.transactionId); // save it just in case, during return } // at this point if we do not have an id, we know that we will need to return a dummy one return this._id || (this._id = util.uid()); }
[ "function", "(", ")", "{", "var", "connection", "=", "this", ".", "connection", "(", ")", ";", "// if a connection is defined, get the ID from connection", "if", "(", "connection", ")", "{", "if", "(", "!", "connection", ".", "transactionId", ")", "{", "throw", "new", "AdapterError", "(", "AdapterError", ".", "TRANSACTION_NOT_ASSOCIATED", ")", ";", "}", "return", "(", "this", ".", "_id", "=", "connection", ".", "transactionId", ")", ";", "// save it just in case, during return", "}", "// at this point if we do not have an id, we know that we will need to return a dummy one", "return", "this", ".", "_id", "||", "(", "this", ".", "_id", "=", "util", ".", "uid", "(", ")", ")", ";", "}" ]
Returns the transaction id associated with this transaction instance. If the transaction is not connected, it creates a new ID and caches it if things are not connected @returns {string} @note that this function caches the id in `this._id` and that is directly used in constructor and the rollback and commit methods.
[ "Returns", "the", "transaction", "id", "associated", "with", "this", "transaction", "instance", ".", "If", "the", "transaction", "is", "not", "connected", "it", "creates", "a", "new", "ID", "and", "caches", "it", "if", "things", "are", "not", "connected" ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L198-L212
40,817
postmanlabs/sails-mysql-transactions
lib/transactions.js
function (connectionName, callback) { var self = this, _db = Transaction.databases[connectionName], transactionId; // validate db setup prior to every connection. this ensures nothing goes forward post teardown if (!_db) { callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP)); } // validate connection name if (!connectionName) { callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED)); } // if this transaction is already connected, then continue if (self.connection()) { // @todo implement error check when multi-db conn is attempted // // callback with error if connection name and current connection mismatch // if (connectionName !== self.connection().identity) { // callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED)); // } callback(undefined, self.connection()); return; } // at this point, it seems like the connection has not been setup yet, so we setup one and then move forward transactionId = self.id(); // this will return and cache a new transaction ID if not already present // set the actual connection name self._connectionName = connectionName; _db.getConnection(function (error, conn) { if (!error) { self._connection = conn; // save reference Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc } callback(error, self._connection); }); }
javascript
function (connectionName, callback) { var self = this, _db = Transaction.databases[connectionName], transactionId; // validate db setup prior to every connection. this ensures nothing goes forward post teardown if (!_db) { callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP)); } // validate connection name if (!connectionName) { callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED)); } // if this transaction is already connected, then continue if (self.connection()) { // @todo implement error check when multi-db conn is attempted // // callback with error if connection name and current connection mismatch // if (connectionName !== self.connection().identity) { // callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED)); // } callback(undefined, self.connection()); return; } // at this point, it seems like the connection has not been setup yet, so we setup one and then move forward transactionId = self.id(); // this will return and cache a new transaction ID if not already present // set the actual connection name self._connectionName = connectionName; _db.getConnection(function (error, conn) { if (!error) { self._connection = conn; // save reference Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc } callback(error, self._connection); }); }
[ "function", "(", "connectionName", ",", "callback", ")", "{", "var", "self", "=", "this", ",", "_db", "=", "Transaction", ".", "databases", "[", "connectionName", "]", ",", "transactionId", ";", "// validate db setup prior to every connection. this ensures nothing goes forward post teardown", "if", "(", "!", "_db", ")", "{", "callback", "(", "new", "AdapterError", "(", "AdapterError", ".", "TRANSACTION_NOT_SETUP", ")", ")", ";", "}", "// validate connection name", "if", "(", "!", "connectionName", ")", "{", "callback", "(", "new", "AdapterError", "(", "AdapterError", ".", "TRANSACTION_NOT_IDENTIFIED", ")", ")", ";", "}", "// if this transaction is already connected, then continue", "if", "(", "self", ".", "connection", "(", ")", ")", "{", "// @todo implement error check when multi-db conn is attempted", "// // callback with error if connection name and current connection mismatch", "// if (connectionName !== self.connection().identity) {", "// callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));", "// }", "callback", "(", "undefined", ",", "self", ".", "connection", "(", ")", ")", ";", "return", ";", "}", "// at this point, it seems like the connection has not been setup yet, so we setup one and then move forward", "transactionId", "=", "self", ".", "id", "(", ")", ";", "// this will return and cache a new transaction ID if not already present", "// set the actual connection name", "self", ".", "_connectionName", "=", "connectionName", ";", "_db", ".", "getConnection", "(", "function", "(", "error", ",", "conn", ")", "{", "if", "(", "!", "error", ")", "{", "self", ".", "_connection", "=", "conn", ";", "// save reference", "Transaction", ".", "associateConnection", "(", "conn", ",", "transactionId", ",", "_db", ".", "transactionConfig", ")", ";", "// @note disassociate on dc", "}", "callback", "(", "error", ",", "self", ".", "_connection", ")", ";", "}", ")", ";", "}" ]
Creates a connection if not already connected. @private @returns {mysql.Connection}
[ "Creates", "a", "connection", "if", "not", "already", "connected", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L232-L272
40,818
postmanlabs/sails-mysql-transactions
lib/transactions.js
function (connectionName, callback) { var self = this, conn = self.connection(); // if not yet connected, spawn new connection and initiate transaction if (!conn) { self.connect(connectionName, function (error, conn) { if (error) { callback(error, conn); return; } // now that we have the connection, we initiate transaction. note that this sql_start is part of the new // connection branch. it is always highly likely that this would be the program flow. in a very unlikely // case the alternate flow will kick in, which is the `conn.query` right after this if-block. conn.beginTransaction(function (error) { callback(error, self); }); }); return; // do not proceed with sql_start if connection wasn't initially present. } // if transaction is attempted across multiple connections, return an error if (connectionName !== self._connectionName) { return callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED)); } conn.beginTransaction(function (error) { // if callback mode is used, then execute it and send self as a parameter to match the new Constructor API. callback(error, self); }); }
javascript
function (connectionName, callback) { var self = this, conn = self.connection(); // if not yet connected, spawn new connection and initiate transaction if (!conn) { self.connect(connectionName, function (error, conn) { if (error) { callback(error, conn); return; } // now that we have the connection, we initiate transaction. note that this sql_start is part of the new // connection branch. it is always highly likely that this would be the program flow. in a very unlikely // case the alternate flow will kick in, which is the `conn.query` right after this if-block. conn.beginTransaction(function (error) { callback(error, self); }); }); return; // do not proceed with sql_start if connection wasn't initially present. } // if transaction is attempted across multiple connections, return an error if (connectionName !== self._connectionName) { return callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED)); } conn.beginTransaction(function (error) { // if callback mode is used, then execute it and send self as a parameter to match the new Constructor API. callback(error, self); }); }
[ "function", "(", "connectionName", ",", "callback", ")", "{", "var", "self", "=", "this", ",", "conn", "=", "self", ".", "connection", "(", ")", ";", "// if not yet connected, spawn new connection and initiate transaction", "if", "(", "!", "conn", ")", "{", "self", ".", "connect", "(", "connectionName", ",", "function", "(", "error", ",", "conn", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ",", "conn", ")", ";", "return", ";", "}", "// now that we have the connection, we initiate transaction. note that this sql_start is part of the new", "// connection branch. it is always highly likely that this would be the program flow. in a very unlikely", "// case the alternate flow will kick in, which is the `conn.query` right after this if-block.", "conn", ".", "beginTransaction", "(", "function", "(", "error", ")", "{", "callback", "(", "error", ",", "self", ")", ";", "}", ")", ";", "}", ")", ";", "return", ";", "// do not proceed with sql_start if connection wasn't initially present.", "}", "// if transaction is attempted across multiple connections, return an error", "if", "(", "connectionName", "!==", "self", ".", "_connectionName", ")", "{", "return", "callback", "(", "new", "AdapterError", "(", "AdapterError", ".", "TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED", ")", ")", ";", "}", "conn", ".", "beginTransaction", "(", "function", "(", "error", ")", "{", "// if callback mode is used, then execute it and send self as a parameter to match the new Constructor API.", "callback", "(", "error", ",", "self", ")", ";", "}", ")", ";", "}" ]
Start a new transaction. @param connectionName @param callback
[ "Start", "a", "new", "transaction", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L291-L322
40,819
postmanlabs/sails-mysql-transactions
lib/transactions.js
function (callback) { var conn = this.connection(), id = this._id; // use the raw ID object // prevent new transactions from using this connection. this.disconnect(); // if commit was called with no active conn, it implies, no transact action // was called. as such it is an error. if (!conn) { // allow one pseudo commit even without connection, so that programmatic call of repeated commits or // rollbacks can be trapped. // note that the absence of `_id` indicates that a `.disconnect` was called. return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_COMM)); } // we commit the connection and then release from hash conn.commit(function (error) { // try releasing the connection. // if that fails then treat it as a major error. try { conn.release(); } // if there was an error during release, set that as the main error. catch (err) { !error && (error = err); } // if failure to issue commit or release, then rollback if (error && conn.transactionConfig.rollbackOnError) { return conn.rollback(function () { // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); } // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); }
javascript
function (callback) { var conn = this.connection(), id = this._id; // use the raw ID object // prevent new transactions from using this connection. this.disconnect(); // if commit was called with no active conn, it implies, no transact action // was called. as such it is an error. if (!conn) { // allow one pseudo commit even without connection, so that programmatic call of repeated commits or // rollbacks can be trapped. // note that the absence of `_id` indicates that a `.disconnect` was called. return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_COMM)); } // we commit the connection and then release from hash conn.commit(function (error) { // try releasing the connection. // if that fails then treat it as a major error. try { conn.release(); } // if there was an error during release, set that as the main error. catch (err) { !error && (error = err); } // if failure to issue commit or release, then rollback if (error && conn.transactionConfig.rollbackOnError) { return conn.rollback(function () { // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); } // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); }
[ "function", "(", "callback", ")", "{", "var", "conn", "=", "this", ".", "connection", "(", ")", ",", "id", "=", "this", ".", "_id", ";", "// use the raw ID object", "// prevent new transactions from using this connection.", "this", ".", "disconnect", "(", ")", ";", "// if commit was called with no active conn, it implies, no transact action", "// was called. as such it is an error.", "if", "(", "!", "conn", ")", "{", "// allow one pseudo commit even without connection, so that programmatic call of repeated commits or", "// rollbacks can be trapped.", "// note that the absence of `_id` indicates that a `.disconnect` was called.", "return", "callback", "&&", "callback", "(", "id", "?", "null", ":", "new", "AdapterError", "(", "AdapterError", ".", "TRANSACTION_UNINITIATED_COMM", ")", ")", ";", "}", "// we commit the connection and then release from hash", "conn", ".", "commit", "(", "function", "(", "error", ")", "{", "// try releasing the connection.", "// if that fails then treat it as a major error.", "try", "{", "conn", ".", "release", "(", ")", ";", "}", "// if there was an error during release, set that as the main error.", "catch", "(", "err", ")", "{", "!", "error", "&&", "(", "error", "=", "err", ")", ";", "}", "// if failure to issue commit or release, then rollback", "if", "(", "error", "&&", "conn", ".", "transactionConfig", ".", "rollbackOnError", ")", "{", "return", "conn", ".", "rollback", "(", "function", "(", ")", "{", "// disassociate the connection from transaction and execute callback", "Transaction", ".", "disassociateConnection", "(", "conn", ")", ";", "callback", "&&", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "// disassociate the connection from transaction and execute callback", "Transaction", ".", "disassociateConnection", "(", "conn", ")", ";", "callback", "&&", "callback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Commit the transaction @param {function} callback - receives `error`
[ "Commit", "the", "transaction" ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L338-L379
40,820
postmanlabs/sails-mysql-transactions
lib/transactions.js
function (callback) { var conn = this.connection(), id = this._id; // use the raw ID object // prevent new transactions from using this connection. this.disconnect(); // if commit was called with no active conn, it implies, no transact action // was called. as such it is an error. if (!conn) { // allow one pseudo commit even without connection, so that programmatic call of repeated commits or // rollbacks can be trapped. // note that the absence of `_id` indicates that a `.disconnect` was called. return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_ROLL)); } conn.rollback(function (error) { // try releasing the connection. // if that fails then treat it as a major error. try { conn.release(); } // if there was an error during release, set that as the main error. catch (err) { !error && (error = err); } // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); }
javascript
function (callback) { var conn = this.connection(), id = this._id; // use the raw ID object // prevent new transactions from using this connection. this.disconnect(); // if commit was called with no active conn, it implies, no transact action // was called. as such it is an error. if (!conn) { // allow one pseudo commit even without connection, so that programmatic call of repeated commits or // rollbacks can be trapped. // note that the absence of `_id` indicates that a `.disconnect` was called. return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_ROLL)); } conn.rollback(function (error) { // try releasing the connection. // if that fails then treat it as a major error. try { conn.release(); } // if there was an error during release, set that as the main error. catch (err) { !error && (error = err); } // disassociate the connection from transaction and execute callback Transaction.disassociateConnection(conn); callback && callback(error); }); }
[ "function", "(", "callback", ")", "{", "var", "conn", "=", "this", ".", "connection", "(", ")", ",", "id", "=", "this", ".", "_id", ";", "// use the raw ID object", "// prevent new transactions from using this connection.", "this", ".", "disconnect", "(", ")", ";", "// if commit was called with no active conn, it implies, no transact action", "// was called. as such it is an error.", "if", "(", "!", "conn", ")", "{", "// allow one pseudo commit even without connection, so that programmatic call of repeated commits or", "// rollbacks can be trapped.", "// note that the absence of `_id` indicates that a `.disconnect` was called.", "return", "callback", "&&", "callback", "(", "id", "?", "null", ":", "new", "AdapterError", "(", "AdapterError", ".", "TRANSACTION_UNINITIATED_ROLL", ")", ")", ";", "}", "conn", ".", "rollback", "(", "function", "(", "error", ")", "{", "// try releasing the connection.", "// if that fails then treat it as a major error.", "try", "{", "conn", ".", "release", "(", ")", ";", "}", "// if there was an error during release, set that as the main error.", "catch", "(", "err", ")", "{", "!", "error", "&&", "(", "error", "=", "err", ")", ";", "}", "// disassociate the connection from transaction and execute callback", "Transaction", ".", "disassociateConnection", "(", "conn", ")", ";", "callback", "&&", "callback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Rollback the transaction @param {function} callback - receives `error`
[ "Rollback", "the", "transaction" ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L385-L416
40,821
postmanlabs/sails-mysql-transactions
lib/multiplexer.js
function (config) { if (!config) { return; } var replConfig, peerNames, sanitisePeerConfig, source = this.sources[config.identity]; // fn // at this stage, the source should not be there if (source) { source.end(); // in case sources exist (almost unlikely, end them) console.log('Warn: duplicate setup of connection found in replication setup for ' + config.identity); } // set default for configuration objects and also clone them // --------------------------------------------------------- // clone and set defaults for the configuration variables. config = util.clone(config); // clone config. do it here to clone replication config too replConfig = util.fill(config.replication || { enabled: false // blank config means replication disabled }, DEFAULT_REPL_SOURCE_CFG); // extract repl config from main config !replConfig.sources && (replConfig.sources = {}); // set default to no source if none specified delete config.replication; // we remove the recursive config from main config clone. // setup a dumb source as a precaution and since we should fall back to original connection if setup fails source = this.sources[config.identity] = db.oneDumbSource(); // replication explicitly disabled or no peers defined. we do this after ending any ongoing sources source._replication = !!replConfig.enabled; if (source._replication === false) { return; } // create default connection parameters for cluster // ------------------------------------------------ // get the list of peer names defined in sources and setup the config defaults for peer sources peerNames = _.filter(Object.keys(replConfig.sources) || [], function (peer) { // remove all disabled peers return (peer = replConfig.sources[peer]) && (peer.enabled !== false); }); sanitisePeerConfig = function (peerConfig) { return util.fill(util.extend(peerConfig, { database: peerConfig._database || config.database, // force db name to be same pool: true, waitForConnections: true, multipleStatements: true }), (replConfig.inheritMaster === true) && config); }; // depending upon the number of peers defined, create simple connection or clustered connection // -------------------------------------------------------------------------------------------- // nothing much to do, if there are no replication source defined if (peerNames.length === 0) { sails && sails.log.info('smt is re-using master as readonly source'); // if it is marked to inherit master in replication, we simply create a new source out of the master config if (replConfig.inheritMaster === true) { this.sources[config.identity] = db.createSource(sanitisePeerConfig({})); } return; } // for a single peer, the configuration is simple, we do not need a cluster but a simple pool if (peerNames.length === 1) { sails && sails.log.info('smt is using 1 "' + config.identity + '" readonly source - ' + peerNames[0]); // ensure that the single source's config is taken care of by setting the default and if needed inheriting // from master this.sources[config.identity] = db.createSource(sanitisePeerConfig(replConfig.sources[peerNames[0]])); return; } // iterate over all sources and normalise and validate their configuration util.each(replConfig.sources, sanitisePeerConfig); sails && sails.log.info('smt is using ' + peerNames.length + ' "' + config.identity + '" readonly sources - ' + peerNames.join(', ')); // create connections for read-replicas and add it to the peering list this.sources[config.identity] = db.createCluster(replConfig); }
javascript
function (config) { if (!config) { return; } var replConfig, peerNames, sanitisePeerConfig, source = this.sources[config.identity]; // fn // at this stage, the source should not be there if (source) { source.end(); // in case sources exist (almost unlikely, end them) console.log('Warn: duplicate setup of connection found in replication setup for ' + config.identity); } // set default for configuration objects and also clone them // --------------------------------------------------------- // clone and set defaults for the configuration variables. config = util.clone(config); // clone config. do it here to clone replication config too replConfig = util.fill(config.replication || { enabled: false // blank config means replication disabled }, DEFAULT_REPL_SOURCE_CFG); // extract repl config from main config !replConfig.sources && (replConfig.sources = {}); // set default to no source if none specified delete config.replication; // we remove the recursive config from main config clone. // setup a dumb source as a precaution and since we should fall back to original connection if setup fails source = this.sources[config.identity] = db.oneDumbSource(); // replication explicitly disabled or no peers defined. we do this after ending any ongoing sources source._replication = !!replConfig.enabled; if (source._replication === false) { return; } // create default connection parameters for cluster // ------------------------------------------------ // get the list of peer names defined in sources and setup the config defaults for peer sources peerNames = _.filter(Object.keys(replConfig.sources) || [], function (peer) { // remove all disabled peers return (peer = replConfig.sources[peer]) && (peer.enabled !== false); }); sanitisePeerConfig = function (peerConfig) { return util.fill(util.extend(peerConfig, { database: peerConfig._database || config.database, // force db name to be same pool: true, waitForConnections: true, multipleStatements: true }), (replConfig.inheritMaster === true) && config); }; // depending upon the number of peers defined, create simple connection or clustered connection // -------------------------------------------------------------------------------------------- // nothing much to do, if there are no replication source defined if (peerNames.length === 0) { sails && sails.log.info('smt is re-using master as readonly source'); // if it is marked to inherit master in replication, we simply create a new source out of the master config if (replConfig.inheritMaster === true) { this.sources[config.identity] = db.createSource(sanitisePeerConfig({})); } return; } // for a single peer, the configuration is simple, we do not need a cluster but a simple pool if (peerNames.length === 1) { sails && sails.log.info('smt is using 1 "' + config.identity + '" readonly source - ' + peerNames[0]); // ensure that the single source's config is taken care of by setting the default and if needed inheriting // from master this.sources[config.identity] = db.createSource(sanitisePeerConfig(replConfig.sources[peerNames[0]])); return; } // iterate over all sources and normalise and validate their configuration util.each(replConfig.sources, sanitisePeerConfig); sails && sails.log.info('smt is using ' + peerNames.length + ' "' + config.identity + '" readonly sources - ' + peerNames.join(', ')); // create connections for read-replicas and add it to the peering list this.sources[config.identity] = db.createCluster(replConfig); }
[ "function", "(", "config", ")", "{", "if", "(", "!", "config", ")", "{", "return", ";", "}", "var", "replConfig", ",", "peerNames", ",", "sanitisePeerConfig", ",", "source", "=", "this", ".", "sources", "[", "config", ".", "identity", "]", ";", "// fn", "// at this stage, the source should not be there", "if", "(", "source", ")", "{", "source", ".", "end", "(", ")", ";", "// in case sources exist (almost unlikely, end them)", "console", ".", "log", "(", "'Warn: duplicate setup of connection found in replication setup for '", "+", "config", ".", "identity", ")", ";", "}", "// set default for configuration objects and also clone them", "// ---------------------------------------------------------", "// clone and set defaults for the configuration variables.", "config", "=", "util", ".", "clone", "(", "config", ")", ";", "// clone config. do it here to clone replication config too", "replConfig", "=", "util", ".", "fill", "(", "config", ".", "replication", "||", "{", "enabled", ":", "false", "// blank config means replication disabled", "}", ",", "DEFAULT_REPL_SOURCE_CFG", ")", ";", "// extract repl config from main config", "!", "replConfig", ".", "sources", "&&", "(", "replConfig", ".", "sources", "=", "{", "}", ")", ";", "// set default to no source if none specified", "delete", "config", ".", "replication", ";", "// we remove the recursive config from main config clone.", "// setup a dumb source as a precaution and since we should fall back to original connection if setup fails", "source", "=", "this", ".", "sources", "[", "config", ".", "identity", "]", "=", "db", ".", "oneDumbSource", "(", ")", ";", "// replication explicitly disabled or no peers defined. we do this after ending any ongoing sources", "source", ".", "_replication", "=", "!", "!", "replConfig", ".", "enabled", ";", "if", "(", "source", ".", "_replication", "===", "false", ")", "{", "return", ";", "}", "// create default connection parameters for cluster", "// ------------------------------------------------", "// get the list of peer names defined in sources and setup the config defaults for peer sources", "peerNames", "=", "_", ".", "filter", "(", "Object", ".", "keys", "(", "replConfig", ".", "sources", ")", "||", "[", "]", ",", "function", "(", "peer", ")", "{", "// remove all disabled peers", "return", "(", "peer", "=", "replConfig", ".", "sources", "[", "peer", "]", ")", "&&", "(", "peer", ".", "enabled", "!==", "false", ")", ";", "}", ")", ";", "sanitisePeerConfig", "=", "function", "(", "peerConfig", ")", "{", "return", "util", ".", "fill", "(", "util", ".", "extend", "(", "peerConfig", ",", "{", "database", ":", "peerConfig", ".", "_database", "||", "config", ".", "database", ",", "// force db name to be same", "pool", ":", "true", ",", "waitForConnections", ":", "true", ",", "multipleStatements", ":", "true", "}", ")", ",", "(", "replConfig", ".", "inheritMaster", "===", "true", ")", "&&", "config", ")", ";", "}", ";", "// depending upon the number of peers defined, create simple connection or clustered connection", "// --------------------------------------------------------------------------------------------", "// nothing much to do, if there are no replication source defined", "if", "(", "peerNames", ".", "length", "===", "0", ")", "{", "sails", "&&", "sails", ".", "log", ".", "info", "(", "'smt is re-using master as readonly source'", ")", ";", "// if it is marked to inherit master in replication, we simply create a new source out of the master config", "if", "(", "replConfig", ".", "inheritMaster", "===", "true", ")", "{", "this", ".", "sources", "[", "config", ".", "identity", "]", "=", "db", ".", "createSource", "(", "sanitisePeerConfig", "(", "{", "}", ")", ")", ";", "}", "return", ";", "}", "// for a single peer, the configuration is simple, we do not need a cluster but a simple pool", "if", "(", "peerNames", ".", "length", "===", "1", ")", "{", "sails", "&&", "sails", ".", "log", ".", "info", "(", "'smt is using 1 \"'", "+", "config", ".", "identity", "+", "'\" readonly source - '", "+", "peerNames", "[", "0", "]", ")", ";", "// ensure that the single source's config is taken care of by setting the default and if needed inheriting", "// from master", "this", ".", "sources", "[", "config", ".", "identity", "]", "=", "db", ".", "createSource", "(", "sanitisePeerConfig", "(", "replConfig", ".", "sources", "[", "peerNames", "[", "0", "]", "]", ")", ")", ";", "return", ";", "}", "// iterate over all sources and normalise and validate their configuration", "util", ".", "each", "(", "replConfig", ".", "sources", ",", "sanitisePeerConfig", ")", ";", "sails", "&&", "sails", ".", "log", ".", "info", "(", "'smt is using '", "+", "peerNames", ".", "length", "+", "' \"'", "+", "config", ".", "identity", "+", "'\" readonly sources - '", "+", "peerNames", ".", "join", "(", "', '", ")", ")", ";", "// create connections for read-replicas and add it to the peering list", "this", ".", "sources", "[", "config", ".", "identity", "]", "=", "db", ".", "createCluster", "(", "replConfig", ")", ";", "}" ]
Creates ORM setup sequencing for all replica set pools. @param {object} config
[ "Creates", "ORM", "setup", "sequencing", "for", "all", "replica", "set", "pools", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L78-L160
40,822
postmanlabs/sails-mysql-transactions
lib/multiplexer.js
function () { // release all pending connections util.each(this.connections, function (connection, threadId, connections) { try { connection.release(); } catch (e) { } // nothing to do with error delete connections[threadId]; }); // execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been // exposed by db.js util.each(this.sources, function (source, identity, sources) { try { source && source.end(); } catch (e) { } // nothing to do with error delete sources[identity]; }); }
javascript
function () { // release all pending connections util.each(this.connections, function (connection, threadId, connections) { try { connection.release(); } catch (e) { } // nothing to do with error delete connections[threadId]; }); // execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been // exposed by db.js util.each(this.sources, function (source, identity, sources) { try { source && source.end(); } catch (e) { } // nothing to do with error delete sources[identity]; }); }
[ "function", "(", ")", "{", "// release all pending connections", "util", ".", "each", "(", "this", ".", "connections", ",", "function", "(", "connection", ",", "threadId", ",", "connections", ")", "{", "try", "{", "connection", ".", "release", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "// nothing to do with error", "delete", "connections", "[", "threadId", "]", ";", "}", ")", ";", "// execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been", "// exposed by db.js", "util", ".", "each", "(", "this", ".", "sources", ",", "function", "(", "source", ",", "identity", ",", "sources", ")", "{", "try", "{", "source", "&&", "source", ".", "end", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "// nothing to do with error", "delete", "sources", "[", "identity", "]", ";", "}", ")", ";", "}" ]
ORM teardown sequencing for all replica set pools
[ "ORM", "teardown", "sequencing", "for", "all", "replica", "set", "pools" ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L165-L184
40,823
postmanlabs/sails-mysql-transactions
lib/multiplexer.js
function (callback) { var self = this; if (!Multiplexer.sources[self._connectionName]) { return callback(new AdapterError(AdapterError.UNKNOWN_CONNECTION)); } Multiplexer.sources[self._connectionName].getConnection(function (error, connection) { if (error) { return callback(error); } // give a unique id to the connection and store it if not already self._threadId = util.uid(); Multiplexer.connections[self._threadId] = connection; callback(null, self._threadId, connection); }); }
javascript
function (callback) { var self = this; if (!Multiplexer.sources[self._connectionName]) { return callback(new AdapterError(AdapterError.UNKNOWN_CONNECTION)); } Multiplexer.sources[self._connectionName].getConnection(function (error, connection) { if (error) { return callback(error); } // give a unique id to the connection and store it if not already self._threadId = util.uid(); Multiplexer.connections[self._threadId] = connection; callback(null, self._threadId, connection); }); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "Multiplexer", ".", "sources", "[", "self", ".", "_connectionName", "]", ")", "{", "return", "callback", "(", "new", "AdapterError", "(", "AdapterError", ".", "UNKNOWN_CONNECTION", ")", ")", ";", "}", "Multiplexer", ".", "sources", "[", "self", ".", "_connectionName", "]", ".", "getConnection", "(", "function", "(", "error", ",", "connection", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "// give a unique id to the connection and store it if not already", "self", ".", "_threadId", "=", "util", ".", "uid", "(", ")", ";", "Multiplexer", ".", "connections", "[", "self", ".", "_threadId", "]", "=", "connection", ";", "callback", "(", "null", ",", "self", ".", "_threadId", ",", "connection", ")", ";", "}", ")", ";", "}" ]
Retrieves a new connection for initialising queries from the pool specified as parameter. @param {function} callback receives `error`, `threadId`, `connection` as parameter
[ "Retrieves", "a", "new", "connection", "for", "initialising", "queries", "from", "the", "pool", "specified", "as", "parameter", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L203-L219
40,824
postmanlabs/sails-mysql-transactions
lib/multiplexer.js
function (threadId) { Multiplexer.connections[threadId] && Multiplexer.connections[threadId].release(); delete Multiplexer.connections[threadId]; }
javascript
function (threadId) { Multiplexer.connections[threadId] && Multiplexer.connections[threadId].release(); delete Multiplexer.connections[threadId]; }
[ "function", "(", "threadId", ")", "{", "Multiplexer", ".", "connections", "[", "threadId", "]", "&&", "Multiplexer", ".", "connections", "[", "threadId", "]", ".", "release", "(", ")", ";", "delete", "Multiplexer", ".", "connections", "[", "threadId", "]", ";", "}" ]
Release the connection associated with this multiplexer @param {string} threadId
[ "Release", "the", "connection", "associated", "with", "this", "multiplexer" ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L225-L228
40,825
postmanlabs/sails-mysql-transactions
lib/adapter.js
function (connectionName, collectionName, obj, cb) { if (_.isObject(obj)) { try { var modelInstance = new this._model(obj); return cb(null, modelInstance); } catch (err) { return cb(err, null); } } }
javascript
function (connectionName, collectionName, obj, cb) { if (_.isObject(obj)) { try { var modelInstance = new this._model(obj); return cb(null, modelInstance); } catch (err) { return cb(err, null); } } }
[ "function", "(", "connectionName", ",", "collectionName", ",", "obj", ",", "cb", ")", "{", "if", "(", "_", ".", "isObject", "(", "obj", ")", ")", "{", "try", "{", "var", "modelInstance", "=", "new", "this", ".", "_model", "(", "obj", ")", ";", "return", "cb", "(", "null", ",", "modelInstance", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "cb", "(", "err", ",", "null", ")", ";", "}", "}", "}" ]
This allows one to create a model instance. @param {string} connectionName @param {string} collectionName @param {Object} obj @param {Function} cb @returns {Object} Model Instance
[ "This", "allows", "one", "to", "create", "a", "model", "instance", "." ]
4c8bae4d428afb942860a51d4deb66aa5b9cd405
https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/adapter.js#L203-L213
40,826
dmachat/angular-datamaps
dist/angular-datamaps.js
mapOptions
function mapOptions() { return { element: element[0], scope: 'usa', height: scope.height, width: scope.width, fills: { defaultFill: '#b9b9b9' }, data: {}, done: function (datamap) { function redraw() { datamap.svg.selectAll('g').attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')'); } if (angular.isDefined(attrs.onClick)) { datamap.svg.selectAll('.datamaps-subunit').on('click', function (geography) { scope.onClick()(geography); }); } if (angular.isDefined(attrs.zoomable)) { datamap.svg.call(d3.behavior.zoom().on('zoom', redraw)); } } }; }
javascript
function mapOptions() { return { element: element[0], scope: 'usa', height: scope.height, width: scope.width, fills: { defaultFill: '#b9b9b9' }, data: {}, done: function (datamap) { function redraw() { datamap.svg.selectAll('g').attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')'); } if (angular.isDefined(attrs.onClick)) { datamap.svg.selectAll('.datamaps-subunit').on('click', function (geography) { scope.onClick()(geography); }); } if (angular.isDefined(attrs.zoomable)) { datamap.svg.call(d3.behavior.zoom().on('zoom', redraw)); } } }; }
[ "function", "mapOptions", "(", ")", "{", "return", "{", "element", ":", "element", "[", "0", "]", ",", "scope", ":", "'usa'", ",", "height", ":", "scope", ".", "height", ",", "width", ":", "scope", ".", "width", ",", "fills", ":", "{", "defaultFill", ":", "'#b9b9b9'", "}", ",", "data", ":", "{", "}", ",", "done", ":", "function", "(", "datamap", ")", "{", "function", "redraw", "(", ")", "{", "datamap", ".", "svg", ".", "selectAll", "(", "'g'", ")", ".", "attr", "(", "'transform'", ",", "'translate('", "+", "d3", ".", "event", ".", "translate", "+", "')scale('", "+", "d3", ".", "event", ".", "scale", "+", "')'", ")", ";", "}", "if", "(", "angular", ".", "isDefined", "(", "attrs", ".", "onClick", ")", ")", "{", "datamap", ".", "svg", ".", "selectAll", "(", "'.datamaps-subunit'", ")", ".", "on", "(", "'click'", ",", "function", "(", "geography", ")", "{", "scope", ".", "onClick", "(", ")", "(", "geography", ")", ";", "}", ")", ";", "}", "if", "(", "angular", ".", "isDefined", "(", "attrs", ".", "zoomable", ")", ")", "{", "datamap", ".", "svg", ".", "call", "(", "d3", ".", "behavior", ".", "zoom", "(", ")", ".", "on", "(", "'zoom'", ",", "redraw", ")", ")", ";", "}", "}", "}", ";", "}" ]
Generate base map options
[ "Generate", "base", "map", "options" ]
1813d387a7d32bf59c353455c06b1b2ff62f06e1
https://github.com/dmachat/angular-datamaps/blob/1813d387a7d32bf59c353455c06b1b2ff62f06e1/dist/angular-datamaps.js#L18-L40
40,827
hugs/node-castro
castro.js
function(path) { // TODO: Does file exist at the file location path? If so, do something about it... //var defaultManager = $.NSFileManager('alloc')('init') //if (defaultManager('fileExistsAtPath',NSlocation)) { // console.log("File already exists!") //} if (!path){ // Default Destination: e.g. "/Users/hugs/Desktop/Castro_uul3di.mov" var homeDir = $.NSHomeDirectory(); var desktopDir = homeDir.toString() + '/Desktop/'; var randomString = (Math.random() + 1).toString(36).substring(12); var filename = 'Castro_' + randomString + '.mp4'; this.location = desktopDir + filename; } else { // TODO: Make sure path is legit. this.location = path; } this.NSlocation = $.NSString('stringWithUTF8String', this.location); this.NSlocationURL = $.NSURL('fileURLWithPath', this.NSlocation); }
javascript
function(path) { // TODO: Does file exist at the file location path? If so, do something about it... //var defaultManager = $.NSFileManager('alloc')('init') //if (defaultManager('fileExistsAtPath',NSlocation)) { // console.log("File already exists!") //} if (!path){ // Default Destination: e.g. "/Users/hugs/Desktop/Castro_uul3di.mov" var homeDir = $.NSHomeDirectory(); var desktopDir = homeDir.toString() + '/Desktop/'; var randomString = (Math.random() + 1).toString(36).substring(12); var filename = 'Castro_' + randomString + '.mp4'; this.location = desktopDir + filename; } else { // TODO: Make sure path is legit. this.location = path; } this.NSlocation = $.NSString('stringWithUTF8String', this.location); this.NSlocationURL = $.NSURL('fileURLWithPath', this.NSlocation); }
[ "function", "(", "path", ")", "{", "// TODO: Does file exist at the file location path? If so, do something about it...", "//var defaultManager = $.NSFileManager('alloc')('init')", "//if (defaultManager('fileExistsAtPath',NSlocation)) {", "// console.log(\"File already exists!\")", "//}", "if", "(", "!", "path", ")", "{", "// Default Destination: e.g. \"/Users/hugs/Desktop/Castro_uul3di.mov\"", "var", "homeDir", "=", "$", ".", "NSHomeDirectory", "(", ")", ";", "var", "desktopDir", "=", "homeDir", ".", "toString", "(", ")", "+", "'/Desktop/'", ";", "var", "randomString", "=", "(", "Math", ".", "random", "(", ")", "+", "1", ")", ".", "toString", "(", "36", ")", ".", "substring", "(", "12", ")", ";", "var", "filename", "=", "'Castro_'", "+", "randomString", "+", "'.mp4'", ";", "this", ".", "location", "=", "desktopDir", "+", "filename", ";", "}", "else", "{", "// TODO: Make sure path is legit.", "this", ".", "location", "=", "path", ";", "}", "this", ".", "NSlocation", "=", "$", ".", "NSString", "(", "'stringWithUTF8String'", ",", "this", ".", "location", ")", ";", "this", ".", "NSlocationURL", "=", "$", ".", "NSURL", "(", "'fileURLWithPath'", ",", "this", ".", "NSlocation", ")", ";", "}" ]
Set recording file location
[ "Set", "recording", "file", "location" ]
a1499ec73dcb2517fcb7ddb5b8ccc359c5740462
https://github.com/hugs/node-castro/blob/a1499ec73dcb2517fcb7ddb5b8ccc359c5740462/castro.js#L41-L61
40,828
neurospeech/web-atoms.js
plugins/videojs/video.dev.js
function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options, element, or create using player ID and unique ID this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ ); this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } }
javascript
function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options, element, or create using player ID and unique ID this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ ); this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } }
[ "function", "(", "player", ",", "options", ",", "ready", ")", "{", "this", ".", "player_", "=", "player", ";", "// Make a copy of prototype.options_ to protect against overriding global defaults", "this", ".", "options_", "=", "vjs", ".", "obj", ".", "copy", "(", "this", ".", "options_", ")", ";", "// Updated options with supplied options", "options", "=", "this", ".", "options", "(", "options", ")", ";", "// Get ID from options, element, or create using player ID and unique ID", "this", ".", "id_", "=", "options", "[", "'id'", "]", "||", "(", "(", "options", "[", "'el'", "]", "&&", "options", "[", "'el'", "]", "[", "'id'", "]", ")", "?", "options", "[", "'el'", "]", "[", "'id'", "]", ":", "player", ".", "id", "(", ")", "+", "'_component_'", "+", "vjs", ".", "guid", "++", ")", ";", "this", ".", "name_", "=", "options", "[", "'name'", "]", "||", "null", ";", "// Create element if one wasn't provided in options", "this", ".", "el_", "=", "options", "[", "'el'", "]", "||", "this", ".", "createEl", "(", ")", ";", "this", ".", "children_", "=", "[", "]", ";", "this", ".", "childIndex_", "=", "{", "}", ";", "this", ".", "childNameIndex_", "=", "{", "}", ";", "// Add any child components in options", "this", ".", "initChildren", "(", ")", ";", "this", ".", "ready", "(", "ready", ")", ";", "// Don't want to trigger ready here or it will before init is actually", "// finished for all children that run this constructor", "if", "(", "options", ".", "reportTouchActivity", "!==", "false", ")", "{", "this", ".", "enableTouchActivity", "(", ")", ";", "}", "}" ]
the constructor function for the class @constructor
[ "the", "constructor", "function", "for", "the", "class" ]
136a2d0987ef9fe492e99badf8ff177e9a2cc6ba
https://github.com/neurospeech/web-atoms.js/blob/136a2d0987ef9fe492e99badf8ff177e9a2cc6ba/plugins/videojs/video.dev.js#L1395-L1426
40,829
neurospeech/web-atoms.js
plugins/videojs/video.dev.js
function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster']; // Set controls this.controls_ = options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Firstplay event implimentation. Not sold on the event yet. // Could probably just check currentTime==0? this.one('play', function(e){ var fpEvent = { type: 'firstplay', target: this.el_ }; // Using vjs.trigger so we can check if default was prevented var keepGoing = vjs.trigger(this.el_, fpEvent); if (!keepGoing) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); } }); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('error', this.onError); this.on('fullscreenchange', this.onFullscreenChange); // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); }
javascript
function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster']; // Set controls this.controls_ = options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Firstplay event implimentation. Not sold on the event yet. // Could probably just check currentTime==0? this.one('play', function(e){ var fpEvent = { type: 'firstplay', target: this.el_ }; // Using vjs.trigger so we can check if default was prevented var keepGoing = vjs.trigger(this.el_, fpEvent); if (!keepGoing) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); } }); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('error', this.onError); this.on('fullscreenchange', this.onFullscreenChange); // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); }
[ "function", "(", "tag", ",", "options", ",", "ready", ")", "{", "this", ".", "tag", "=", "tag", ";", "// Store the original tag used to set options", "// Make sure tag ID exists", "tag", ".", "id", "=", "tag", ".", "id", "||", "'vjs_video_'", "+", "vjs", ".", "guid", "++", ";", "// Set Options", "// The options argument overrides options set in the video tag", "// which overrides globally set options.", "// This latter part coincides with the load order", "// (tag must exist before Player)", "options", "=", "vjs", ".", "obj", ".", "merge", "(", "this", ".", "getTagSettings", "(", "tag", ")", ",", "options", ")", ";", "// Cache for video property values.", "this", ".", "cache_", "=", "{", "}", ";", "// Set poster", "this", ".", "poster_", "=", "options", "[", "'poster'", "]", ";", "// Set controls", "this", ".", "controls_", "=", "options", "[", "'controls'", "]", ";", "// Original tag settings stored in options", "// now remove immediately so native controls don't flash.", "// May be turned back on by HTML5 tech if nativeControlsForTouch is true", "tag", ".", "controls", "=", "false", ";", "// we don't want the player to report touch activity on itself", "// see enableTouchActivity in Component", "options", ".", "reportTouchActivity", "=", "false", ";", "// Run base component initializing with new options.", "// Builds the element through createEl()", "// Inits and embeds any child components in opts", "vjs", ".", "Component", ".", "call", "(", "this", ",", "this", ",", "options", ",", "ready", ")", ";", "// Update controls className. Can't do this when the controls are initially", "// set because the element doesn't exist yet.", "if", "(", "this", ".", "controls", "(", ")", ")", "{", "this", ".", "addClass", "(", "'vjs-controls-enabled'", ")", ";", "}", "else", "{", "this", ".", "addClass", "(", "'vjs-controls-disabled'", ")", ";", "}", "// TODO: Make this smarter. Toggle user state between touching/mousing", "// using events, since devices can have both touch and mouse events.", "// if (vjs.TOUCH_ENABLED) {", "// this.addClass('vjs-touch-enabled');", "// }", "// Firstplay event implimentation. Not sold on the event yet.", "// Could probably just check currentTime==0?", "this", ".", "one", "(", "'play'", ",", "function", "(", "e", ")", "{", "var", "fpEvent", "=", "{", "type", ":", "'firstplay'", ",", "target", ":", "this", ".", "el_", "}", ";", "// Using vjs.trigger so we can check if default was prevented", "var", "keepGoing", "=", "vjs", ".", "trigger", "(", "this", ".", "el_", ",", "fpEvent", ")", ";", "if", "(", "!", "keepGoing", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "e", ".", "stopImmediatePropagation", "(", ")", ";", "}", "}", ")", ";", "this", ".", "on", "(", "'ended'", ",", "this", ".", "onEnded", ")", ";", "this", ".", "on", "(", "'play'", ",", "this", ".", "onPlay", ")", ";", "this", ".", "on", "(", "'firstplay'", ",", "this", ".", "onFirstPlay", ")", ";", "this", ".", "on", "(", "'pause'", ",", "this", ".", "onPause", ")", ";", "this", ".", "on", "(", "'progress'", ",", "this", ".", "onProgress", ")", ";", "this", ".", "on", "(", "'durationchange'", ",", "this", ".", "onDurationChange", ")", ";", "this", ".", "on", "(", "'error'", ",", "this", ".", "onError", ")", ";", "this", ".", "on", "(", "'fullscreenchange'", ",", "this", ".", "onFullscreenChange", ")", ";", "// Make player easily findable by ID", "vjs", ".", "players", "[", "this", ".", "id_", "]", "=", "this", ";", "if", "(", "options", "[", "'plugins'", "]", ")", "{", "vjs", ".", "obj", ".", "each", "(", "options", "[", "'plugins'", "]", ",", "function", "(", "key", ",", "val", ")", "{", "this", "[", "key", "]", "(", "val", ")", ";", "}", ",", "this", ")", ";", "}", "this", ".", "listenForUserActivity", "(", ")", ";", "}" ]
player's constructor function @constructs @method init @param {Element} tag The original video tag used for configuring options @param {Object=} options Player options @param {Function=} ready Ready callback function
[ "player", "s", "constructor", "function" ]
136a2d0987ef9fe492e99badf8ff177e9a2cc6ba
https://github.com/neurospeech/web-atoms.js/blob/136a2d0987ef9fe492e99badf8ff177e9a2cc6ba/plugins/videojs/video.dev.js#L2836-L2917
40,830
lastboy/package-script
utils/Logger.js
function (data) { if (!isLog()) { return undefined; } try { _fs.appendFileSync("pkgscript.log", (_utils.now() + " " + data + "\n"), "utf8"); } catch (e) { console.error(_utils.now + " [package-script] Package Script, ERROR:", e); } }
javascript
function (data) { if (!isLog()) { return undefined; } try { _fs.appendFileSync("pkgscript.log", (_utils.now() + " " + data + "\n"), "utf8"); } catch (e) { console.error(_utils.now + " [package-script] Package Script, ERROR:", e); } }
[ "function", "(", "data", ")", "{", "if", "(", "!", "isLog", "(", ")", ")", "{", "return", "undefined", ";", "}", "try", "{", "_fs", ".", "appendFileSync", "(", "\"pkgscript.log\"", ",", "(", "_utils", ".", "now", "(", ")", "+", "\" \"", "+", "data", "+", "\"\\n\"", ")", ",", "\"utf8\"", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "_utils", ".", "now", "+", "\" [package-script] Package Script, ERROR:\"", ",", "e", ")", ";", "}", "}" ]
Print the given data to a file @param data The data to be write
[ "Print", "the", "given", "data", "to", "a", "file" ]
f0be6bdfc7b4e6689f9040ebe034407f907cabd5
https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/utils/Logger.js#L22-L34
40,831
lastboy/package-script
utils/Logger.js
function (msg) { if (!isLog()) { return undefined; } if (msg) { console.log(_utils.now() + " " + msg); this.log2file(msg); } }
javascript
function (msg) { if (!isLog()) { return undefined; } if (msg) { console.log(_utils.now() + " " + msg); this.log2file(msg); } }
[ "function", "(", "msg", ")", "{", "if", "(", "!", "isLog", "(", ")", ")", "{", "return", "undefined", ";", "}", "if", "(", "msg", ")", "{", "console", ".", "log", "(", "_utils", ".", "now", "(", ")", "+", "\" \"", "+", "msg", ")", ";", "this", ".", "log2file", "(", "msg", ")", ";", "}", "}" ]
Log a message to the console and to a file. @param msg
[ "Log", "a", "message", "to", "the", "console", "and", "to", "a", "file", "." ]
f0be6bdfc7b4e6689f9040ebe034407f907cabd5
https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/utils/Logger.js#L41-L51
40,832
lastboy/package-script
pkgscript.js
setSpawnObject
function setSpawnObject(admin) { admin = ((admin === undefined) ? getDefaultAdmin() : admin); if (isLinux && admin) { spawn = sudoarg; } else { spawn = cparg.spawn; } return admin; }
javascript
function setSpawnObject(admin) { admin = ((admin === undefined) ? getDefaultAdmin() : admin); if (isLinux && admin) { spawn = sudoarg; } else { spawn = cparg.spawn; } return admin; }
[ "function", "setSpawnObject", "(", "admin", ")", "{", "admin", "=", "(", "(", "admin", "===", "undefined", ")", "?", "getDefaultAdmin", "(", ")", ":", "admin", ")", ";", "if", "(", "isLinux", "&&", "admin", ")", "{", "spawn", "=", "sudoarg", ";", "}", "else", "{", "spawn", "=", "cparg", ".", "spawn", ";", "}", "return", "admin", ";", "}" ]
Set the current spawn object. Can be sudo for getting the admin prompt or child_process @param admin
[ "Set", "the", "current", "spawn", "object", ".", "Can", "be", "sudo", "for", "getting", "the", "admin", "prompt", "or", "child_process" ]
f0be6bdfc7b4e6689f9040ebe034407f907cabd5
https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/pkgscript.js#L49-L57
40,833
lastboy/package-script
pkgscript.js
install
function install(items, callback) { var item = items[next], command = item.command, args = item.args, admin = item.admin, spawnopt = (item.spawnopt || {}), print; // set the spawn object according to the passed admin argument admin = setSpawnObject(admin); // run the command if (isLinux) { if (admin) { // use sudo args.unshift(command); print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + print); sudoopt.spawnOptions = {}; jsutils.Object.copy(spawnopt, sudoopt.spawnOptions); cprocess = spawn(args, sudoopt); } else { //use child_process print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + command + " " + print); cprocess = spawn(command, args, spawnopt); } } else { args.unshift(command); args.unshift("/c"); command = "cmd"; print = [command, args.join(" ")].join(" "); logger.console.log("[package-script] Running Installer command: " + print); cprocess = spawn(command, args, spawnopt); } // -- Spawn Listeners cprocess.stdout.on('data', function (data) { var log = 'CAT Installer: ' + data; logger.logall(log); }); cprocess.stderr.on('data', function (data) { if (data && (new String(data)).indexOf("npm ERR") != -1) { logger.logall('Package Script : ' + data); } else { logger.log2file('Package Script : ' + data); } }); cprocess.on('close', function (code) { logger.log2file('Package Script Complete ' + code); next++; if (next < size) { install(items, callback); } else { // callback if (callback && _.isFunction(callback)) { callback.call(this, code); } } }); }
javascript
function install(items, callback) { var item = items[next], command = item.command, args = item.args, admin = item.admin, spawnopt = (item.spawnopt || {}), print; // set the spawn object according to the passed admin argument admin = setSpawnObject(admin); // run the command if (isLinux) { if (admin) { // use sudo args.unshift(command); print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + print); sudoopt.spawnOptions = {}; jsutils.Object.copy(spawnopt, sudoopt.spawnOptions); cprocess = spawn(args, sudoopt); } else { //use child_process print = args.join(" "); logger.console.log("[package-script] Running Installer command: " + command + " " + print); cprocess = spawn(command, args, spawnopt); } } else { args.unshift(command); args.unshift("/c"); command = "cmd"; print = [command, args.join(" ")].join(" "); logger.console.log("[package-script] Running Installer command: " + print); cprocess = spawn(command, args, spawnopt); } // -- Spawn Listeners cprocess.stdout.on('data', function (data) { var log = 'CAT Installer: ' + data; logger.logall(log); }); cprocess.stderr.on('data', function (data) { if (data && (new String(data)).indexOf("npm ERR") != -1) { logger.logall('Package Script : ' + data); } else { logger.log2file('Package Script : ' + data); } }); cprocess.on('close', function (code) { logger.log2file('Package Script Complete ' + code); next++; if (next < size) { install(items, callback); } else { // callback if (callback && _.isFunction(callback)) { callback.call(this, code); } } }); }
[ "function", "install", "(", "items", ",", "callback", ")", "{", "var", "item", "=", "items", "[", "next", "]", ",", "command", "=", "item", ".", "command", ",", "args", "=", "item", ".", "args", ",", "admin", "=", "item", ".", "admin", ",", "spawnopt", "=", "(", "item", ".", "spawnopt", "||", "{", "}", ")", ",", "print", ";", "// set the spawn object according to the passed admin argument", "admin", "=", "setSpawnObject", "(", "admin", ")", ";", "// run the command", "if", "(", "isLinux", ")", "{", "if", "(", "admin", ")", "{", "// use sudo", "args", ".", "unshift", "(", "command", ")", ";", "print", "=", "args", ".", "join", "(", "\" \"", ")", ";", "logger", ".", "console", ".", "log", "(", "\"[package-script] Running Installer command: \"", "+", "print", ")", ";", "sudoopt", ".", "spawnOptions", "=", "{", "}", ";", "jsutils", ".", "Object", ".", "copy", "(", "spawnopt", ",", "sudoopt", ".", "spawnOptions", ")", ";", "cprocess", "=", "spawn", "(", "args", ",", "sudoopt", ")", ";", "}", "else", "{", "//use child_process", "print", "=", "args", ".", "join", "(", "\" \"", ")", ";", "logger", ".", "console", ".", "log", "(", "\"[package-script] Running Installer command: \"", "+", "command", "+", "\" \"", "+", "print", ")", ";", "cprocess", "=", "spawn", "(", "command", ",", "args", ",", "spawnopt", ")", ";", "}", "}", "else", "{", "args", ".", "unshift", "(", "command", ")", ";", "args", ".", "unshift", "(", "\"/c\"", ")", ";", "command", "=", "\"cmd\"", ";", "print", "=", "[", "command", ",", "args", ".", "join", "(", "\" \"", ")", "]", ".", "join", "(", "\" \"", ")", ";", "logger", ".", "console", ".", "log", "(", "\"[package-script] Running Installer command: \"", "+", "print", ")", ";", "cprocess", "=", "spawn", "(", "command", ",", "args", ",", "spawnopt", ")", ";", "}", "// -- Spawn Listeners", "cprocess", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "var", "log", "=", "'CAT Installer: '", "+", "data", ";", "logger", ".", "logall", "(", "log", ")", ";", "}", ")", ";", "cprocess", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "data", "&&", "(", "new", "String", "(", "data", ")", ")", ".", "indexOf", "(", "\"npm ERR\"", ")", "!=", "-", "1", ")", "{", "logger", ".", "logall", "(", "'Package Script : '", "+", "data", ")", ";", "}", "else", "{", "logger", ".", "log2file", "(", "'Package Script : '", "+", "data", ")", ";", "}", "}", ")", ";", "cprocess", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "logger", ".", "log2file", "(", "'Package Script Complete '", "+", "code", ")", ";", "next", "++", ";", "if", "(", "next", "<", "size", ")", "{", "install", "(", "items", ",", "callback", ")", ";", "}", "else", "{", "// callback", "if", "(", "callback", "&&", "_", ".", "isFunction", "(", "callback", ")", ")", "{", "callback", ".", "call", "(", "this", ",", "code", ")", ";", "}", "}", "}", ")", ";", "}" ]
Run a single spawn operation according to the given configuration @param items The passed configuration items @param callback The functionality to be called on complete
[ "Run", "a", "single", "spawn", "operation", "according", "to", "the", "given", "configuration" ]
f0be6bdfc7b4e6689f9040ebe034407f907cabd5
https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/pkgscript.js#L76-L144
40,834
lastboy/package-script
pkgscript.js
function(config, init, callback) { var me = this; // first initialize if (init) { this.init(init); } logger.log2file("\n\n************ Package Script ************************************* process id: " + process.pid); if (config && _.isArray(config)) { commands = commands.concat(config); size = commands.length; if (size > 0) { install(commands, function() { logger.logall("[package-script] process completed, see pkgscript.log for more information"); if (callback) { callback.call(me); } }); } } else { logger.logall("[package-script] No valid configuration for 'install' function, see the docs for more information "); } }
javascript
function(config, init, callback) { var me = this; // first initialize if (init) { this.init(init); } logger.log2file("\n\n************ Package Script ************************************* process id: " + process.pid); if (config && _.isArray(config)) { commands = commands.concat(config); size = commands.length; if (size > 0) { install(commands, function() { logger.logall("[package-script] process completed, see pkgscript.log for more information"); if (callback) { callback.call(me); } }); } } else { logger.logall("[package-script] No valid configuration for 'install' function, see the docs for more information "); } }
[ "function", "(", "config", ",", "init", ",", "callback", ")", "{", "var", "me", "=", "this", ";", "// first initialize", "if", "(", "init", ")", "{", "this", ".", "init", "(", "init", ")", ";", "}", "logger", ".", "log2file", "(", "\"\\n\\n************ Package Script ************************************* process id: \"", "+", "process", ".", "pid", ")", ";", "if", "(", "config", "&&", "_", ".", "isArray", "(", "config", ")", ")", "{", "commands", "=", "commands", ".", "concat", "(", "config", ")", ";", "size", "=", "commands", ".", "length", ";", "if", "(", "size", ">", "0", ")", "{", "install", "(", "commands", ",", "function", "(", ")", "{", "logger", ".", "logall", "(", "\"[package-script] process completed, see pkgscript.log for more information\"", ")", ";", "if", "(", "callback", ")", "{", "callback", ".", "call", "(", "me", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "logger", ".", "logall", "(", "\"[package-script] No valid configuration for 'install' function, see the docs for more information \"", ")", ";", "}", "}" ]
spawn additional command according to the config @param config The configuration for the spawn e.g. [{ admin: true, [optional (for now, linux support only)], spawnopt: {cwd: '.'} [optional] (see child_process spawn docs) command: 'npm', args: ["--version"] }] @param init The initial configuration, can be set in separate method (see 'init') @param callback The callback functionality
[ "spawn", "additional", "command", "according", "to", "the", "config" ]
f0be6bdfc7b4e6689f9040ebe034407f907cabd5
https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/pkgscript.js#L277-L303
40,835
eladnava/koa-mysql
wrapper.js
wrapQueryMethod
function wrapQueryMethod(fn, ctx) { return function() { // Obtain function arguments var args = [].slice.call(arguments); // Return a thunkified function that receives a done callback return function(done) { // Add a custom callback to provided args args.push(function(err, result) { // Query failed? if (err) { return done(err); } // Query succeeded done(null, result); }); // Execute the query fn.apply(ctx, args); }; }; }
javascript
function wrapQueryMethod(fn, ctx) { return function() { // Obtain function arguments var args = [].slice.call(arguments); // Return a thunkified function that receives a done callback return function(done) { // Add a custom callback to provided args args.push(function(err, result) { // Query failed? if (err) { return done(err); } // Query succeeded done(null, result); }); // Execute the query fn.apply(ctx, args); }; }; }
[ "function", "wrapQueryMethod", "(", "fn", ",", "ctx", ")", "{", "return", "function", "(", ")", "{", "// Obtain function arguments", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "// Return a thunkified function that receives a done callback", "return", "function", "(", "done", ")", "{", "// Add a custom callback to provided args", "args", ".", "push", "(", "function", "(", "err", ",", "result", ")", "{", "// Query failed?", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "// Query succeeded", "done", "(", "null", ",", "result", ")", ";", "}", ")", ";", "// Execute the query", "fn", ".", "apply", "(", "ctx", ",", "args", ")", ";", "}", ";", "}", ";", "}" ]
Thunkify query methods
[ "Thunkify", "query", "methods" ]
3d5aac1646ed5084466cebf689d412c81d8d12e2
https://github.com/eladnava/koa-mysql/blob/3d5aac1646ed5084466cebf689d412c81d8d12e2/wrapper.js#L4-L26
40,836
eladnava/koa-mysql
wrapper.js
wrapConnection
function wrapConnection(conn) { // Already wrapped this function? if (conn._coWrapped) { return conn; } // Set flag to avoid re-wrapping conn._coWrapped = true; // Functions to thunkify var queryMethods = [ 'query', 'execute' ]; // Traverse query methods list queryMethods.forEach(function(name) { // Thunkify the method conn[name] = wrapQueryMethod(conn[name], conn); }); // Return co-friendly connection return conn; }
javascript
function wrapConnection(conn) { // Already wrapped this function? if (conn._coWrapped) { return conn; } // Set flag to avoid re-wrapping conn._coWrapped = true; // Functions to thunkify var queryMethods = [ 'query', 'execute' ]; // Traverse query methods list queryMethods.forEach(function(name) { // Thunkify the method conn[name] = wrapQueryMethod(conn[name], conn); }); // Return co-friendly connection return conn; }
[ "function", "wrapConnection", "(", "conn", ")", "{", "// Already wrapped this function?", "if", "(", "conn", ".", "_coWrapped", ")", "{", "return", "conn", ";", "}", "// Set flag to avoid re-wrapping", "conn", ".", "_coWrapped", "=", "true", ";", "// Functions to thunkify", "var", "queryMethods", "=", "[", "'query'", ",", "'execute'", "]", ";", "// Traverse query methods list", "queryMethods", ".", "forEach", "(", "function", "(", "name", ")", "{", "// Thunkify the method", "conn", "[", "name", "]", "=", "wrapQueryMethod", "(", "conn", "[", "name", "]", ",", "conn", ")", ";", "}", ")", ";", "// Return co-friendly connection", "return", "conn", ";", "}" ]
Wrap a MySQL connection object's query methods
[ "Wrap", "a", "MySQL", "connection", "object", "s", "query", "methods" ]
3d5aac1646ed5084466cebf689d412c81d8d12e2
https://github.com/eladnava/koa-mysql/blob/3d5aac1646ed5084466cebf689d412c81d8d12e2/wrapper.js#L29-L52
40,837
thlorenz/phe
phe.js
evaluateCardCodes
function evaluateCardCodes(codes) { const len = codes.length if (len === 5) return evaluate5cards.apply(null, codes) if (len === 6) return evaluate6cards.apply(null, codes) if (len === 7) return evaluate7cards.apply(null, codes) throw new Error(`Can only evaluate 5, 6 or 7 cards, you gave me ${len}`) }
javascript
function evaluateCardCodes(codes) { const len = codes.length if (len === 5) return evaluate5cards.apply(null, codes) if (len === 6) return evaluate6cards.apply(null, codes) if (len === 7) return evaluate7cards.apply(null, codes) throw new Error(`Can only evaluate 5, 6 or 7 cards, you gave me ${len}`) }
[ "function", "evaluateCardCodes", "(", "codes", ")", "{", "const", "len", "=", "codes", ".", "length", "if", "(", "len", "===", "5", ")", "return", "evaluate5cards", ".", "apply", "(", "null", ",", "codes", ")", "if", "(", "len", "===", "6", ")", "return", "evaluate6cards", ".", "apply", "(", "null", ",", "codes", ")", "if", "(", "len", "===", "7", ")", "return", "evaluate7cards", ".", "apply", "(", "null", ",", "codes", ")", "throw", "new", "Error", "(", "`", "${", "len", "}", "`", ")", "}" ]
Evaluates the 5 - 7 card codes to arrive at a number representing the hand strength, smaller is better. @name evaluateCardCodes @function @param {Array.<Number>} cards the cards, i.e. `[ 49, 36, 4, 48, 41 ]` @return {Number} the strength of the hand comprised by the card codes
[ "Evaluates", "the", "5", "-", "7", "card", "codes", "to", "arrive", "at", "a", "number", "representing", "the", "hand", "strength", "smaller", "is", "better", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L41-L47
40,838
thlorenz/phe
phe.js
evaluateBoard
function evaluateBoard(board) { if (typeof board !== 'string') throw new Error('board needs to be a string') const cards = board.trim().split(/ /) return evaluateCardsFast(cards) }
javascript
function evaluateBoard(board) { if (typeof board !== 'string') throw new Error('board needs to be a string') const cards = board.trim().split(/ /) return evaluateCardsFast(cards) }
[ "function", "evaluateBoard", "(", "board", ")", "{", "if", "(", "typeof", "board", "!==", "'string'", ")", "throw", "new", "Error", "(", "'board needs to be a string'", ")", "const", "cards", "=", "board", ".", "trim", "(", ")", ".", "split", "(", "/", " ", "/", ")", "return", "evaluateCardsFast", "(", "cards", ")", "}" ]
Evaluates the given board of 5 to 7 cards provided as part of the board to arrive at a number representing the hand strength, smaller is better. @name evaluateBoard @function @param {String} board the board, i.e. `'Ah Ks Td 3c Ad'` @return {Number} the strength of the hand comprised by the cards of the board
[ "Evaluates", "the", "given", "board", "of", "5", "to", "7", "cards", "provided", "as", "part", "of", "the", "board", "to", "arrive", "at", "a", "number", "representing", "the", "hand", "strength", "smaller", "is", "better", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L83-L87
40,839
thlorenz/phe
phe.js
setCardCodes
function setCardCodes(set) { const codeSet = new Set() for (const v of set) codeSet.add(cardCode(v)) return codeSet }
javascript
function setCardCodes(set) { const codeSet = new Set() for (const v of set) codeSet.add(cardCode(v)) return codeSet }
[ "function", "setCardCodes", "(", "set", ")", "{", "const", "codeSet", "=", "new", "Set", "(", ")", "for", "(", "const", "v", "of", "set", ")", "codeSet", ".", "add", "(", "cardCode", "(", "v", ")", ")", "return", "codeSet", "}" ]
Converts a set of cards to card codes. @name setCardCodes @function @param {Set.<String>} set card strings set, i.e. `Set({'Ah', 'Ks', 'Td', '3c, 'Ad'})` @return {Set.<Number>} card code set
[ "Converts", "a", "set", "of", "cards", "to", "card", "codes", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L145-L149
40,840
thlorenz/phe
phe.js
setStringifyCardCodes
function setStringifyCardCodes(set) { const stringSet = new Set() for (const v of set) stringSet.add(stringifyCardCode(v)) return stringSet }
javascript
function setStringifyCardCodes(set) { const stringSet = new Set() for (const v of set) stringSet.add(stringifyCardCode(v)) return stringSet }
[ "function", "setStringifyCardCodes", "(", "set", ")", "{", "const", "stringSet", "=", "new", "Set", "(", ")", "for", "(", "const", "v", "of", "set", ")", "stringSet", ".", "add", "(", "stringifyCardCode", "(", "v", ")", ")", "return", "stringSet", "}" ]
Converts a set of card codes to their string representations. @name setStringifyCardCodes @function @param {Set.<Number>} set card code set @return {Set.<String>} set with string representations of the card codes, i.e. `Set({'Ah', 'Ks', 'Td', '3c, 'Ad'})`
[ "Converts", "a", "set", "of", "card", "codes", "to", "their", "string", "representations", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L160-L164
40,841
thlorenz/phe
lib/hash.js
hash_binary
function hash_binary(q, len, k) { var sum = 0 for (var i = 0; i < len; i++) { if (q[i]) { if (len - i - 1 >= k) { sum += choose[len - i - 1][k] } k-- if (k === 0) break } } return sum }
javascript
function hash_binary(q, len, k) { var sum = 0 for (var i = 0; i < len; i++) { if (q[i]) { if (len - i - 1 >= k) { sum += choose[len - i - 1][k] } k-- if (k === 0) break } } return sum }
[ "function", "hash_binary", "(", "q", ",", "len", ",", "k", ")", "{", "var", "sum", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "q", "[", "i", "]", ")", "{", "if", "(", "len", "-", "i", "-", "1", ">=", "k", ")", "{", "sum", "+=", "choose", "[", "len", "-", "i", "-", "1", "]", "[", "k", "]", "}", "k", "--", "if", "(", "k", "===", "0", ")", "break", "}", "}", "return", "sum", "}" ]
Calculates the binary hash using the choose table. @name hash_binary @function @private @param {Array} q array with an element for each rank, usually total of 13 @param {Number} len number of ranks, usually 13 @param {Number} k number of cards that make up the hand, 5, 6 or 7 @return {Number} hash sum
[ "Calculates", "the", "binary", "hash", "using", "the", "choose", "table", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/lib/hash.js#L43-L58
40,842
vihanb/babel-plugin-loop-optimizer
src/index.js
Handle_forEach
function Handle_forEach(t, path, aggressive_optimization, possible_undefined) { var arrayName = path.scope.generateUidIdentifier("a"), funcName = path.scope.generateUidIdentifier("f"), iterator = path.scope.generateUidIdentifier("i"), call = t.expressionStatement ( t.callExpression(funcName, [ t.memberExpression ( arrayName, iterator, true ), iterator, arrayName ]) ) path.getStatementParent().insertBefore ([ t.variableDeclaration("let", [ t.variableDeclarator ( arrayName, path.node.callee.object ) ]), t.variableDeclaration("let", [ t.variableDeclarator ( funcName, path.node.arguments[0] ) ]), aggressive_optimization ? t.forStatement ( t.variableDeclaration("let", [ t.variableDeclarator ( iterator, t.memberExpression ( arrayName, t.identifier("length") ) ) ]), possible_undefined ? t.logicalExpression ( "&&", t.updateExpression("--", iterator), t.binaryExpression ( "!==", t.memberExpression ( arrayName, iterator, true ), t.identifier("undefined") ) ) : t.updateExpression("--", iterator), null, call ) : t.forStatement ( t.variableDeclaration("let", [ t.variableDeclarator ( iterator, t.numericLiteral(0) ) ]), possible_undefined ? t.logicalExpression ( "&&", t.binaryExpression ( "<", iterator, t.memberExpression ( arrayName, t.identifier("length") ) ), t.binaryExpression ( "!==", t.memberExpression ( arrayName, iterator, true ), t.identifier("undefined") ) ) : t.updateExpression("--", iterator), t.updateExpression("++", iterator), call ) ]) path.remove() }
javascript
function Handle_forEach(t, path, aggressive_optimization, possible_undefined) { var arrayName = path.scope.generateUidIdentifier("a"), funcName = path.scope.generateUidIdentifier("f"), iterator = path.scope.generateUidIdentifier("i"), call = t.expressionStatement ( t.callExpression(funcName, [ t.memberExpression ( arrayName, iterator, true ), iterator, arrayName ]) ) path.getStatementParent().insertBefore ([ t.variableDeclaration("let", [ t.variableDeclarator ( arrayName, path.node.callee.object ) ]), t.variableDeclaration("let", [ t.variableDeclarator ( funcName, path.node.arguments[0] ) ]), aggressive_optimization ? t.forStatement ( t.variableDeclaration("let", [ t.variableDeclarator ( iterator, t.memberExpression ( arrayName, t.identifier("length") ) ) ]), possible_undefined ? t.logicalExpression ( "&&", t.updateExpression("--", iterator), t.binaryExpression ( "!==", t.memberExpression ( arrayName, iterator, true ), t.identifier("undefined") ) ) : t.updateExpression("--", iterator), null, call ) : t.forStatement ( t.variableDeclaration("let", [ t.variableDeclarator ( iterator, t.numericLiteral(0) ) ]), possible_undefined ? t.logicalExpression ( "&&", t.binaryExpression ( "<", iterator, t.memberExpression ( arrayName, t.identifier("length") ) ), t.binaryExpression ( "!==", t.memberExpression ( arrayName, iterator, true ), t.identifier("undefined") ) ) : t.updateExpression("--", iterator), t.updateExpression("++", iterator), call ) ]) path.remove() }
[ "function", "Handle_forEach", "(", "t", ",", "path", ",", "aggressive_optimization", ",", "possible_undefined", ")", "{", "var", "arrayName", "=", "path", ".", "scope", ".", "generateUidIdentifier", "(", "\"a\"", ")", ",", "funcName", "=", "path", ".", "scope", ".", "generateUidIdentifier", "(", "\"f\"", ")", ",", "iterator", "=", "path", ".", "scope", ".", "generateUidIdentifier", "(", "\"i\"", ")", ",", "call", "=", "t", ".", "expressionStatement", "(", "t", ".", "callExpression", "(", "funcName", ",", "[", "t", ".", "memberExpression", "(", "arrayName", ",", "iterator", ",", "true", ")", ",", "iterator", ",", "arrayName", "]", ")", ")", "path", ".", "getStatementParent", "(", ")", ".", "insertBefore", "(", "[", "t", ".", "variableDeclaration", "(", "\"let\"", ",", "[", "t", ".", "variableDeclarator", "(", "arrayName", ",", "path", ".", "node", ".", "callee", ".", "object", ")", "]", ")", ",", "t", ".", "variableDeclaration", "(", "\"let\"", ",", "[", "t", ".", "variableDeclarator", "(", "funcName", ",", "path", ".", "node", ".", "arguments", "[", "0", "]", ")", "]", ")", ",", "aggressive_optimization", "?", "t", ".", "forStatement", "(", "t", ".", "variableDeclaration", "(", "\"let\"", ",", "[", "t", ".", "variableDeclarator", "(", "iterator", ",", "t", ".", "memberExpression", "(", "arrayName", ",", "t", ".", "identifier", "(", "\"length\"", ")", ")", ")", "]", ")", ",", "possible_undefined", "?", "t", ".", "logicalExpression", "(", "\"&&\"", ",", "t", ".", "updateExpression", "(", "\"--\"", ",", "iterator", ")", ",", "t", ".", "binaryExpression", "(", "\"!==\"", ",", "t", ".", "memberExpression", "(", "arrayName", ",", "iterator", ",", "true", ")", ",", "t", ".", "identifier", "(", "\"undefined\"", ")", ")", ")", ":", "t", ".", "updateExpression", "(", "\"--\"", ",", "iterator", ")", ",", "null", ",", "call", ")", ":", "t", ".", "forStatement", "(", "t", ".", "variableDeclaration", "(", "\"let\"", ",", "[", "t", ".", "variableDeclarator", "(", "iterator", ",", "t", ".", "numericLiteral", "(", "0", ")", ")", "]", ")", ",", "possible_undefined", "?", "t", ".", "logicalExpression", "(", "\"&&\"", ",", "t", ".", "binaryExpression", "(", "\"<\"", ",", "iterator", ",", "t", ".", "memberExpression", "(", "arrayName", ",", "t", ".", "identifier", "(", "\"length\"", ")", ")", ")", ",", "t", ".", "binaryExpression", "(", "\"!==\"", ",", "t", ".", "memberExpression", "(", "arrayName", ",", "iterator", ",", "true", ")", ",", "t", ".", "identifier", "(", "\"undefined\"", ")", ")", ")", ":", "t", ".", "updateExpression", "(", "\"--\"", ",", "iterator", ")", ",", "t", ".", "updateExpression", "(", "\"++\"", ",", "iterator", ")", ",", "call", ")", "]", ")", "path", ".", "remove", "(", ")", "}" ]
NON-RETURNING
[ "NON", "-", "RETURNING" ]
a87652cb3b939ee04acc28a5c13f72458a41fef1
https://github.com/vihanb/babel-plugin-loop-optimizer/blob/a87652cb3b939ee04acc28a5c13f72458a41fef1/src/index.js#L2-L97
40,843
thlorenz/phe
lib/hand-code.js
stringifyCardCode
function stringifyCardCode(code) { const rank = code & 0b111100 const suit = code & 0b000011 return rankCodeStrings[rank] + suitCodeStrings[suit] }
javascript
function stringifyCardCode(code) { const rank = code & 0b111100 const suit = code & 0b000011 return rankCodeStrings[rank] + suitCodeStrings[suit] }
[ "function", "stringifyCardCode", "(", "code", ")", "{", "const", "rank", "=", "code", "&", "0b111100", "const", "suit", "=", "code", "&", "0b000011", "return", "rankCodeStrings", "[", "rank", "]", "+", "suitCodeStrings", "[", "suit", "]", "}" ]
Converts the given card code into a string presentation. @name stringifyCardCode @function @param {Number} code the card code, i.e. obtained via `cardCode(rank, suit)`. @return {String} a string representation of the card in question, i.e. `Ah`
[ "Converts", "the", "given", "card", "code", "into", "a", "string", "presentation", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/lib/hand-code.js#L97-L101
40,844
thlorenz/phe
lib/hand-rank.js
handRank
function handRank(val) { if (val > 6185) return HIGH_CARD // 1277 high card if (val > 3325) return ONE_PAIR // 2860 one pair if (val > 2467) return TWO_PAIR // 858 two pair if (val > 1609) return THREE_OF_A_KIND // 858 three-kind if (val > 1599) return STRAIGHT // 10 straights if (val > 322) return FLUSH // 1277 flushes if (val > 166) return FULL_HOUSE // 156 full house if (val > 10) return FOUR_OF_A_KIND // 156 four-kind return STRAIGHT_FLUSH // 10 straight-flushes }
javascript
function handRank(val) { if (val > 6185) return HIGH_CARD // 1277 high card if (val > 3325) return ONE_PAIR // 2860 one pair if (val > 2467) return TWO_PAIR // 858 two pair if (val > 1609) return THREE_OF_A_KIND // 858 three-kind if (val > 1599) return STRAIGHT // 10 straights if (val > 322) return FLUSH // 1277 flushes if (val > 166) return FULL_HOUSE // 156 full house if (val > 10) return FOUR_OF_A_KIND // 156 four-kind return STRAIGHT_FLUSH // 10 straight-flushes }
[ "function", "handRank", "(", "val", ")", "{", "if", "(", "val", ">", "6185", ")", "return", "HIGH_CARD", "// 1277 high card", "if", "(", "val", ">", "3325", ")", "return", "ONE_PAIR", "// 2860 one pair", "if", "(", "val", ">", "2467", ")", "return", "TWO_PAIR", "// 858 two pair", "if", "(", "val", ">", "1609", ")", "return", "THREE_OF_A_KIND", "// 858 three-kind", "if", "(", "val", ">", "1599", ")", "return", "STRAIGHT", "// 10 straights", "if", "(", "val", ">", "322", ")", "return", "FLUSH", "// 1277 flushes", "if", "(", "val", ">", "166", ")", "return", "FULL_HOUSE", "// 156 full house", "if", "(", "val", ">", "10", ")", "return", "FOUR_OF_A_KIND", "// 156 four-kind", "return", "STRAIGHT_FLUSH", "// 10 straight-flushes", "}" ]
Converts a hand strength number into a hand rank number `0 - 8` for `STRAIGHT_FLUSH - HIGH_CARD`. @name handRank @function @param {Number} val hand strength (result of an `evaluate` function) @return {Number} the hand rank
[ "Converts", "a", "hand", "strength", "number", "into", "a", "hand", "rank", "number", "0", "-", "8", "for", "STRAIGHT_FLUSH", "-", "HIGH_CARD", "." ]
6cfea3703b050fda8dfc8d934ceeb4d3df331d6d
https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/lib/hand-rank.js#L43-L53
40,845
senecajs/seneca-web-adapter-express
seneca-web-adapter-express.js
handleRoute
function handleRoute(seneca, options, request, reply, route, next) { if (options.parseBody) { return ReadBody(request, finish) } finish(null, request.body || {}) // Express requires a body parser to work in production // This util creates a body obj without neededing a parser // but doesn't impact loading one in. function finish(err, body) { if (err) { return next(err) } // This is what the seneca handler will get // Note! request$ and response$ will be stripped // if the message is sent over transport. const payload = { request$: request, response$: reply, args: { body: body, route: route, params: request.params, query: request.query, user: request.user || null } } // Call the seneca action specified in the config seneca.act(route.pattern, payload, (err, response) => { if (err) { return next(err) } // Redirect or reply depending on config. if (route.redirect) { return reply.redirect(route.redirect) } if (route.autoreply) { return reply.send(response) } }) } }
javascript
function handleRoute(seneca, options, request, reply, route, next) { if (options.parseBody) { return ReadBody(request, finish) } finish(null, request.body || {}) // Express requires a body parser to work in production // This util creates a body obj without neededing a parser // but doesn't impact loading one in. function finish(err, body) { if (err) { return next(err) } // This is what the seneca handler will get // Note! request$ and response$ will be stripped // if the message is sent over transport. const payload = { request$: request, response$: reply, args: { body: body, route: route, params: request.params, query: request.query, user: request.user || null } } // Call the seneca action specified in the config seneca.act(route.pattern, payload, (err, response) => { if (err) { return next(err) } // Redirect or reply depending on config. if (route.redirect) { return reply.redirect(route.redirect) } if (route.autoreply) { return reply.send(response) } }) } }
[ "function", "handleRoute", "(", "seneca", ",", "options", ",", "request", ",", "reply", ",", "route", ",", "next", ")", "{", "if", "(", "options", ".", "parseBody", ")", "{", "return", "ReadBody", "(", "request", ",", "finish", ")", "}", "finish", "(", "null", ",", "request", ".", "body", "||", "{", "}", ")", "// Express requires a body parser to work in production", "// This util creates a body obj without neededing a parser", "// but doesn't impact loading one in.", "function", "finish", "(", "err", ",", "body", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "// This is what the seneca handler will get", "// Note! request$ and response$ will be stripped", "// if the message is sent over transport.", "const", "payload", "=", "{", "request$", ":", "request", ",", "response$", ":", "reply", ",", "args", ":", "{", "body", ":", "body", ",", "route", ":", "route", ",", "params", ":", "request", ".", "params", ",", "query", ":", "request", ".", "query", ",", "user", ":", "request", ".", "user", "||", "null", "}", "}", "// Call the seneca action specified in the config", "seneca", ".", "act", "(", "route", ".", "pattern", ",", "payload", ",", "(", "err", ",", "response", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "// Redirect or reply depending on config.", "if", "(", "route", ".", "redirect", ")", "{", "return", "reply", ".", "redirect", "(", "route", ".", "redirect", ")", "}", "if", "(", "route", ".", "autoreply", ")", "{", "return", "reply", ".", "send", "(", "response", ")", "}", "}", ")", "}", "}" ]
All routes ultimately get handled by this handler if they have not already be redirected or responded.
[ "All", "routes", "ultimately", "get", "handled", "by", "this", "handler", "if", "they", "have", "not", "already", "be", "redirected", "or", "responded", "." ]
9b43f4c80b3310f2494750c8af200b768bd47bdf
https://github.com/senecajs/seneca-web-adapter-express/blob/9b43f4c80b3310f2494750c8af200b768bd47bdf/seneca-web-adapter-express.js#L65-L109
40,846
senecajs/seneca-web-adapter-express
seneca-web-adapter-express.js
unsecuredRoute
function unsecuredRoute(seneca, options, context, method, middleware, route) { const routeArgs = [route.path].concat(middleware).concat([ (request, reply, next) => { handleRoute(seneca, options, request, reply, route, next) } ]) context[method].apply(context, routeArgs) }
javascript
function unsecuredRoute(seneca, options, context, method, middleware, route) { const routeArgs = [route.path].concat(middleware).concat([ (request, reply, next) => { handleRoute(seneca, options, request, reply, route, next) } ]) context[method].apply(context, routeArgs) }
[ "function", "unsecuredRoute", "(", "seneca", ",", "options", ",", "context", ",", "method", ",", "middleware", ",", "route", ")", "{", "const", "routeArgs", "=", "[", "route", ".", "path", "]", ".", "concat", "(", "middleware", ")", ".", "concat", "(", "[", "(", "request", ",", "reply", ",", "next", ")", "=>", "{", "handleRoute", "(", "seneca", ",", "options", ",", "request", ",", "reply", ",", "route", ",", "next", ")", "}", "]", ")", "context", "[", "method", "]", ".", "apply", "(", "context", ",", "routeArgs", ")", "}" ]
Unsecured routes just call the handler directly, no magic.
[ "Unsecured", "routes", "just", "call", "the", "handler", "directly", "no", "magic", "." ]
9b43f4c80b3310f2494750c8af200b768bd47bdf
https://github.com/senecajs/seneca-web-adapter-express/blob/9b43f4c80b3310f2494750c8af200b768bd47bdf/seneca-web-adapter-express.js#L112-L120
40,847
senecajs/seneca-web-adapter-express
seneca-web-adapter-express.js
authRoute
function authRoute(seneca, options, context, method, route, middleware, auth) { const opts = { failureRedirect: route.auth.fail, successRedirect: route.auth.pass } const routeArgs = [route.path] .concat([auth.authenticate(route.auth.strategy, opts)]) .concat(middleware) .concat([ (request, reply, next) => { handleRoute(seneca, options, request, reply, route, next) } ]) context[method].apply(context, routeArgs) }
javascript
function authRoute(seneca, options, context, method, route, middleware, auth) { const opts = { failureRedirect: route.auth.fail, successRedirect: route.auth.pass } const routeArgs = [route.path] .concat([auth.authenticate(route.auth.strategy, opts)]) .concat(middleware) .concat([ (request, reply, next) => { handleRoute(seneca, options, request, reply, route, next) } ]) context[method].apply(context, routeArgs) }
[ "function", "authRoute", "(", "seneca", ",", "options", ",", "context", ",", "method", ",", "route", ",", "middleware", ",", "auth", ")", "{", "const", "opts", "=", "{", "failureRedirect", ":", "route", ".", "auth", ".", "fail", ",", "successRedirect", ":", "route", ".", "auth", ".", "pass", "}", "const", "routeArgs", "=", "[", "route", ".", "path", "]", ".", "concat", "(", "[", "auth", ".", "authenticate", "(", "route", ".", "auth", ".", "strategy", ",", "opts", ")", "]", ")", ".", "concat", "(", "middleware", ")", ".", "concat", "(", "[", "(", "request", ",", "reply", ",", "next", ")", "=>", "{", "handleRoute", "(", "seneca", ",", "options", ",", "request", ",", "reply", ",", "route", ",", "next", ")", "}", "]", ")", "context", "[", "method", "]", ".", "apply", "(", "context", ",", "routeArgs", ")", "}" ]
Auth routes call passport.authenticate and can and do redirect depending on pass or failure. Generally this means you don't need a seneca handler set as the redirects happend instead.
[ "Auth", "routes", "call", "passport", ".", "authenticate", "and", "can", "and", "do", "redirect", "depending", "on", "pass", "or", "failure", ".", "Generally", "this", "means", "you", "don", "t", "need", "a", "seneca", "handler", "set", "as", "the", "redirects", "happend", "instead", "." ]
9b43f4c80b3310f2494750c8af200b768bd47bdf
https://github.com/senecajs/seneca-web-adapter-express/blob/9b43f4c80b3310f2494750c8af200b768bd47bdf/seneca-web-adapter-express.js#L125-L141
40,848
vangj/jsbayes
jsbayes.js
initCpt
function initCpt(numValues) { var cpt = []; var sum = 0; for(var i=0; i < numValues; i++) { cpt[i] = Math.random(); sum += cpt[i]; } for(var i=0; i < numValues; i++) { cpt[i] = cpt[i] / sum; } return cpt; }
javascript
function initCpt(numValues) { var cpt = []; var sum = 0; for(var i=0; i < numValues; i++) { cpt[i] = Math.random(); sum += cpt[i]; } for(var i=0; i < numValues; i++) { cpt[i] = cpt[i] / sum; } return cpt; }
[ "function", "initCpt", "(", "numValues", ")", "{", "var", "cpt", "=", "[", "]", ";", "var", "sum", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numValues", ";", "i", "++", ")", "{", "cpt", "[", "i", "]", "=", "Math", ".", "random", "(", ")", ";", "sum", "+=", "cpt", "[", "i", "]", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numValues", ";", "i", "++", ")", "{", "cpt", "[", "i", "]", "=", "cpt", "[", "i", "]", "/", "sum", ";", "}", "return", "cpt", ";", "}" ]
Initializes a conditional probability table. @param {Number} numValues Number of values. @returns {Array} Array of doubles that sum to 1.0.
[ "Initializes", "a", "conditional", "probability", "table", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L9-L20
40,849
vangj/jsbayes
jsbayes.js
initCptWithParents
function initCptWithParents(values, parents, paIndex) { if(parents && parents.length > 0) { if(parents.length === 1 || paIndex === parents.length - 1) { var idx = parents.length === 1 ? 0 : paIndex; var numPaVals = parents[idx].values.length; var cpts = []; for(var i=0; i < numPaVals; i++) { var cpt = initCpt(values.length); cpts.push(cpt); } return cpts; } else { var cpts = []; var numPaVals = parents[paIndex].values.length; for(var i=0; i < numPaVals; i++) { var cpt = initCptWithParents(values, parents, paIndex+1); cpts.push(cpt); } return cpts; } } else { return initCpt(values.length); } }
javascript
function initCptWithParents(values, parents, paIndex) { if(parents && parents.length > 0) { if(parents.length === 1 || paIndex === parents.length - 1) { var idx = parents.length === 1 ? 0 : paIndex; var numPaVals = parents[idx].values.length; var cpts = []; for(var i=0; i < numPaVals; i++) { var cpt = initCpt(values.length); cpts.push(cpt); } return cpts; } else { var cpts = []; var numPaVals = parents[paIndex].values.length; for(var i=0; i < numPaVals; i++) { var cpt = initCptWithParents(values, parents, paIndex+1); cpts.push(cpt); } return cpts; } } else { return initCpt(values.length); } }
[ "function", "initCptWithParents", "(", "values", ",", "parents", ",", "paIndex", ")", "{", "if", "(", "parents", "&&", "parents", ".", "length", ">", "0", ")", "{", "if", "(", "parents", ".", "length", "===", "1", "||", "paIndex", "===", "parents", ".", "length", "-", "1", ")", "{", "var", "idx", "=", "parents", ".", "length", "===", "1", "?", "0", ":", "paIndex", ";", "var", "numPaVals", "=", "parents", "[", "idx", "]", ".", "values", ".", "length", ";", "var", "cpts", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPaVals", ";", "i", "++", ")", "{", "var", "cpt", "=", "initCpt", "(", "values", ".", "length", ")", ";", "cpts", ".", "push", "(", "cpt", ")", ";", "}", "return", "cpts", ";", "}", "else", "{", "var", "cpts", "=", "[", "]", ";", "var", "numPaVals", "=", "parents", "[", "paIndex", "]", ".", "values", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPaVals", ";", "i", "++", ")", "{", "var", "cpt", "=", "initCptWithParents", "(", "values", ",", "parents", ",", "paIndex", "+", "1", ")", ";", "cpts", ".", "push", "(", "cpt", ")", ";", "}", "return", "cpts", ";", "}", "}", "else", "{", "return", "initCpt", "(", "values", ".", "length", ")", ";", "}", "}" ]
Initializes a CPT with fake and normalized values using recursion. @param {Array} values Values of variables (array of values). @param {Array} parents Array of JSON nodes that are parents of the variable. @param {Number} paIndex The current parent index. @returns {Array} An array of nested arrays representing the CPT.
[ "Initializes", "a", "CPT", "with", "fake", "and", "normalized", "values", "using", "recursion", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L29-L52
40,850
vangj/jsbayes
jsbayes.js
async
function async(f, args) { return new Promise( function(resolve, reject) { try { var r = f.apply(undefined, args); resolve(r); } catch(e) { reject(e); } } ); }
javascript
function async(f, args) { return new Promise( function(resolve, reject) { try { var r = f.apply(undefined, args); resolve(r); } catch(e) { reject(e); } } ); }
[ "function", "async", "(", "f", ",", "args", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "try", "{", "var", "r", "=", "f", ".", "apply", "(", "undefined", ",", "args", ")", ";", "resolve", "(", "r", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Creates a Promise. @param {Object} f Function. @param {Array} args List of arguments. @returns {Promise} Promise.
[ "Creates", "a", "Promise", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L60-L71
40,851
vangj/jsbayes
jsbayes.js
isArrayOfArray
function isArrayOfArray(o) { if(isArray(o)) { if(o.length > 0) { if(isArray(o[0])) { return true; } } } return false; }
javascript
function isArrayOfArray(o) { if(isArray(o)) { if(o.length > 0) { if(isArray(o[0])) { return true; } } } return false; }
[ "function", "isArrayOfArray", "(", "o", ")", "{", "if", "(", "isArray", "(", "o", ")", ")", "{", "if", "(", "o", ".", "length", ">", "0", ")", "{", "if", "(", "isArray", "(", "o", "[", "0", "]", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Checks if an object is an array of arrays. @param {*} o Object. @returns {Boolean} A boolean to indicate if the object is array of arrays.
[ "Checks", "if", "an", "object", "is", "an", "array", "of", "arrays", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L87-L96
40,852
vangj/jsbayes
jsbayes.js
setNodeCptProbs
function setNodeCptProbs(cpt, probs, index) { if(!isArrayOfArray(cpt)) { for(var i=0; i < cpt.length; i++) { cpt[i] = probs[index][i]; } var nextIndex = index + 1; return nextIndex; } else { var next = index; for(var i=0; i < cpt.length; i++) { next = setNodeCptProbs(cpt[i], probs, next); } return next; } }
javascript
function setNodeCptProbs(cpt, probs, index) { if(!isArrayOfArray(cpt)) { for(var i=0; i < cpt.length; i++) { cpt[i] = probs[index][i]; } var nextIndex = index + 1; return nextIndex; } else { var next = index; for(var i=0; i < cpt.length; i++) { next = setNodeCptProbs(cpt[i], probs, next); } return next; } }
[ "function", "setNodeCptProbs", "(", "cpt", ",", "probs", ",", "index", ")", "{", "if", "(", "!", "isArrayOfArray", "(", "cpt", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cpt", ".", "length", ";", "i", "++", ")", "{", "cpt", "[", "i", "]", "=", "probs", "[", "index", "]", "[", "i", "]", ";", "}", "var", "nextIndex", "=", "index", "+", "1", ";", "return", "nextIndex", ";", "}", "else", "{", "var", "next", "=", "index", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cpt", ".", "length", ";", "i", "++", ")", "{", "next", "=", "setNodeCptProbs", "(", "cpt", "[", "i", "]", ",", "probs", ",", "next", ")", ";", "}", "return", "next", ";", "}", "}" ]
Sets the CPT entries to the specified probabilities. @param {Array} cpt Array of nested arrays representing a CPT. @param {Array} probs Array of arrays of probabilities representing a CPT. @param {Number} index The current index. @returns {Number} The next index.
[ "Sets", "the", "CPT", "entries", "to", "the", "specified", "probabilities", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L105-L119
40,853
vangj/jsbayes
jsbayes.js
initNodeCpt
function initNodeCpt(values, parents, probs) { var cpt = initCptWithParents(values, parents, 0); setNodeCptProbs(cpt, probs, 0); return cpt; }
javascript
function initNodeCpt(values, parents, probs) { var cpt = initCptWithParents(values, parents, 0); setNodeCptProbs(cpt, probs, 0); return cpt; }
[ "function", "initNodeCpt", "(", "values", ",", "parents", ",", "probs", ")", "{", "var", "cpt", "=", "initCptWithParents", "(", "values", ",", "parents", ",", "0", ")", ";", "setNodeCptProbs", "(", "cpt", ",", "probs", ",", "0", ")", ";", "return", "cpt", ";", "}" ]
Initializes a node's CPT. @param {Array} values Array of values. @param {Array} parents Array of parents. @param {Array} probs Array of arrays of probabilities. @returns {Array} Array of nested arrays representing a CPT.
[ "Initializes", "a", "node", "s", "CPT", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L128-L132
40,854
vangj/jsbayes
jsbayes.js
normalizeProbs
function normalizeProbs(arr) { var probs = []; var sum = 0.0; for (var i=0; i < arr.length; i++) { probs[i] = arr[i] + 0.001 sum += probs[i] } for (var i=0; i < arr.length; i++) { probs[i] = probs[i] / sum; } return probs; }
javascript
function normalizeProbs(arr) { var probs = []; var sum = 0.0; for (var i=0; i < arr.length; i++) { probs[i] = arr[i] + 0.001 sum += probs[i] } for (var i=0; i < arr.length; i++) { probs[i] = probs[i] / sum; } return probs; }
[ "function", "normalizeProbs", "(", "arr", ")", "{", "var", "probs", "=", "[", "]", ";", "var", "sum", "=", "0.0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "probs", "[", "i", "]", "=", "arr", "[", "i", "]", "+", "0.001", "sum", "+=", "probs", "[", "i", "]", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "probs", "[", "i", "]", "=", "probs", "[", "i", "]", "/", "sum", ";", "}", "return", "probs", ";", "}" ]
Normalizes an array of values such that the elements sum to 1.0. Note that 0.001 is added to every value to avoid 0.0 probabilities. This adjustment helps with visualization downstream. @param {Array} arr Array of probabilities. @returns {Array} Normalized probailities.
[ "Normalizes", "an", "array", "of", "values", "such", "that", "the", "elements", "sum", "to", "1", ".", "0", ".", "Note", "that", "0", ".", "001", "is", "added", "to", "every", "value", "to", "avoid", "0", ".", "0", "probabilities", ".", "This", "adjustment", "helps", "with", "visualization", "downstream", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L141-L152
40,855
vangj/jsbayes
jsbayes.js
normalizeCpts
function normalizeCpts(cpts) { var probs = [] for (var i=0; i < cpts.length; i++) { probs.push(normalizeProbs(cpts[i])); } return probs; }
javascript
function normalizeCpts(cpts) { var probs = [] for (var i=0; i < cpts.length; i++) { probs.push(normalizeProbs(cpts[i])); } return probs; }
[ "function", "normalizeCpts", "(", "cpts", ")", "{", "var", "probs", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cpts", ".", "length", ";", "i", "++", ")", "{", "probs", ".", "push", "(", "normalizeProbs", "(", "cpts", "[", "i", "]", ")", ")", ";", "}", "return", "probs", ";", "}" ]
Normalizes a CPT. @param {Array} cpts Array of arrays (matrix) representing a CPT. @returns {Array} Normalized CPT.
[ "Normalizes", "a", "CPT", "." ]
f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52
https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L159-L165
40,856
Alex-D/check-disk-space
index.js
check
function check(cmd, filter, mapping, coefficient = 1) { return new Promise((resolve, reject) => { exec(cmd, (error, stdout) => { if (error) { reject(error) } try { resolve(mapOutput(stdout, filter, mapping, coefficient)) } catch (err) { reject(err) } }) }) }
javascript
function check(cmd, filter, mapping, coefficient = 1) { return new Promise((resolve, reject) => { exec(cmd, (error, stdout) => { if (error) { reject(error) } try { resolve(mapOutput(stdout, filter, mapping, coefficient)) } catch (err) { reject(err) } }) }) }
[ "function", "check", "(", "cmd", ",", "filter", ",", "mapping", ",", "coefficient", "=", "1", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "exec", "(", "cmd", ",", "(", "error", ",", "stdout", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", "}", "try", "{", "resolve", "(", "mapOutput", "(", "stdout", ",", "filter", ",", "mapping", ",", "coefficient", ")", ")", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", "}", "}", ")", "}", ")", "}" ]
Run the command and do common things between win32 and unix @param {String} cmd - The command to execute @param {Function} filter - To filter drives (only used for win32) @param {Object} mapping - Map between column index and normalized column name @param {Number} coefficient - The size coefficient to get bytes instead of kB @return {Promise} -
[ "Run", "the", "command", "and", "do", "common", "things", "between", "win32", "and", "unix" ]
510b32e2cab4b27a21cb523fea4b45be189ea348
https://github.com/Alex-D/check-disk-space/blob/510b32e2cab4b27a21cb523fea4b45be189ea348/index.js#L60-L74
40,857
Alex-D/check-disk-space
index.js
checkWin32
function checkWin32(directoryPath) { if (directoryPath.charAt(1) !== ':') { return new Promise((resolve, reject) => { reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`)) }) } return check( `wmic logicaldisk get size,freespace,caption`, driveData => { // Only get the drive which match the path const driveLetter = driveData[0] return directoryPath.startsWith(driveLetter) }, { diskPath: 0, free: 1, size: 2 } ) }
javascript
function checkWin32(directoryPath) { if (directoryPath.charAt(1) !== ':') { return new Promise((resolve, reject) => { reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`)) }) } return check( `wmic logicaldisk get size,freespace,caption`, driveData => { // Only get the drive which match the path const driveLetter = driveData[0] return directoryPath.startsWith(driveLetter) }, { diskPath: 0, free: 1, size: 2 } ) }
[ "function", "checkWin32", "(", "directoryPath", ")", "{", "if", "(", "directoryPath", ".", "charAt", "(", "1", ")", "!==", "':'", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "reject", "(", "new", "InvalidPathError", "(", "`", "\\\\", "${", "directoryPath", "}", "`", ")", ")", "}", ")", "}", "return", "check", "(", "`", "`", ",", "driveData", "=>", "{", "// Only get the drive which match the path", "const", "driveLetter", "=", "driveData", "[", "0", "]", "return", "directoryPath", ".", "startsWith", "(", "driveLetter", ")", "}", ",", "{", "diskPath", ":", "0", ",", "free", ":", "1", ",", "size", ":", "2", "}", ")", "}" ]
Build the check call for win32 @param {String} directoryPath - The file/folder path from where we want to know disk space @return {Promise} -
[ "Build", "the", "check", "call", "for", "win32" ]
510b32e2cab4b27a21cb523fea4b45be189ea348
https://github.com/Alex-D/check-disk-space/blob/510b32e2cab4b27a21cb523fea4b45be189ea348/index.js#L82-L102
40,858
Alex-D/check-disk-space
index.js
checkUnix
function checkUnix(directoryPath) { if (!path.normalize(directoryPath).startsWith(path.sep)) { return new Promise((resolve, reject) => { reject(new InvalidPathError(`The following path is invalid (should start by ${path.sep}): ${directoryPath}`)) }) } return check( `df -Pk "${module.exports.getFirstExistingParentPath(directoryPath)}"`, () => true, // We should only get one line, so we did not need to filter { diskPath: 5, free: 3, size: 1 }, 1024 // We get sizes in kB, we need to convert that to bytes ) }
javascript
function checkUnix(directoryPath) { if (!path.normalize(directoryPath).startsWith(path.sep)) { return new Promise((resolve, reject) => { reject(new InvalidPathError(`The following path is invalid (should start by ${path.sep}): ${directoryPath}`)) }) } return check( `df -Pk "${module.exports.getFirstExistingParentPath(directoryPath)}"`, () => true, // We should only get one line, so we did not need to filter { diskPath: 5, free: 3, size: 1 }, 1024 // We get sizes in kB, we need to convert that to bytes ) }
[ "function", "checkUnix", "(", "directoryPath", ")", "{", "if", "(", "!", "path", ".", "normalize", "(", "directoryPath", ")", ".", "startsWith", "(", "path", ".", "sep", ")", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "reject", "(", "new", "InvalidPathError", "(", "`", "${", "path", ".", "sep", "}", "${", "directoryPath", "}", "`", ")", ")", "}", ")", "}", "return", "check", "(", "`", "${", "module", ".", "exports", ".", "getFirstExistingParentPath", "(", "directoryPath", ")", "}", "`", ",", "(", ")", "=>", "true", ",", "// We should only get one line, so we did not need to filter", "{", "diskPath", ":", "5", ",", "free", ":", "3", ",", "size", ":", "1", "}", ",", "1024", "// We get sizes in kB, we need to convert that to bytes", ")", "}" ]
Build the check call for unix @param {String} directoryPath - The file/folder path from where we want to know disk space @return {Promise} -
[ "Build", "the", "check", "call", "for", "unix" ]
510b32e2cab4b27a21cb523fea4b45be189ea348
https://github.com/Alex-D/check-disk-space/blob/510b32e2cab4b27a21cb523fea4b45be189ea348/index.js#L110-L127
40,859
RemiAWE/ng-flat-datepicker
dist/ng-flat-datepicker.js
init
function init() { element.wrap('<div class="ng-flat-datepicker-wrapper"></div>'); $compile(template)(scope); element.after(template); if (angular.isDefined(ngModel.$modelValue) && moment.isDate(ngModel.$modelValue)) { scope.calendarCursor = ngModel.$modelValue; } }
javascript
function init() { element.wrap('<div class="ng-flat-datepicker-wrapper"></div>'); $compile(template)(scope); element.after(template); if (angular.isDefined(ngModel.$modelValue) && moment.isDate(ngModel.$modelValue)) { scope.calendarCursor = ngModel.$modelValue; } }
[ "function", "init", "(", ")", "{", "element", ".", "wrap", "(", "'<div class=\"ng-flat-datepicker-wrapper\"></div>'", ")", ";", "$compile", "(", "template", ")", "(", "scope", ")", ";", "element", ".", "after", "(", "template", ")", ";", "if", "(", "angular", ".", "isDefined", "(", "ngModel", ".", "$modelValue", ")", "&&", "moment", ".", "isDate", "(", "ngModel", ".", "$modelValue", ")", ")", "{", "scope", ".", "calendarCursor", "=", "ngModel", ".", "$modelValue", ";", "}", "}" ]
Init the directive @return {}
[ "Init", "the", "directive" ]
a349e5da015c714b01ca84d087d760fe31e473b5
https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L137-L147
40,860
RemiAWE/ng-flat-datepicker
dist/ng-flat-datepicker.js
getWeeks
function getWeeks (date) { var weeks = []; var date = moment.utc(date); var firstDayOfMonth = moment(date).date(1); var lastDayOfMonth = moment(date).date(date.daysInMonth()); var startDay = moment(firstDayOfMonth); var endDay = moment(lastDayOfMonth); // NB: We use weekday() to get a locale aware weekday startDay = firstDayOfMonth.weekday() === 0 ? startDay : startDay.weekday(0); endDay = lastDayOfMonth.weekday() === 6 ? endDay : endDay.weekday(6); var currentWeek = []; for (var start = moment(startDay); start.isBefore(moment(endDay).add(1, 'days')); start.add(1, 'days')) { var afterMinDate = !scope.config.minDate || start.isAfter(scope.config.minDate, 'day'); var beforeMaxDate = !scope.config.maxDate || start.isBefore(scope.config.maxDate, 'day'); var isFuture = start.isAfter(today); var beforeFuture = scope.config.allowFuture || !isFuture; var day = { date: moment(start).toDate(), isToday: start.isSame(today, 'day'), isInMonth: start.isSame(firstDayOfMonth, 'month'), isSelected: start.isSame(dateSelected, 'day'), isSelectable: afterMinDate && beforeMaxDate && beforeFuture }; currentWeek.push(day); if (start.weekday() === 6 || start === endDay) { weeks.push(currentWeek); currentWeek = []; } } return weeks; }
javascript
function getWeeks (date) { var weeks = []; var date = moment.utc(date); var firstDayOfMonth = moment(date).date(1); var lastDayOfMonth = moment(date).date(date.daysInMonth()); var startDay = moment(firstDayOfMonth); var endDay = moment(lastDayOfMonth); // NB: We use weekday() to get a locale aware weekday startDay = firstDayOfMonth.weekday() === 0 ? startDay : startDay.weekday(0); endDay = lastDayOfMonth.weekday() === 6 ? endDay : endDay.weekday(6); var currentWeek = []; for (var start = moment(startDay); start.isBefore(moment(endDay).add(1, 'days')); start.add(1, 'days')) { var afterMinDate = !scope.config.minDate || start.isAfter(scope.config.minDate, 'day'); var beforeMaxDate = !scope.config.maxDate || start.isBefore(scope.config.maxDate, 'day'); var isFuture = start.isAfter(today); var beforeFuture = scope.config.allowFuture || !isFuture; var day = { date: moment(start).toDate(), isToday: start.isSame(today, 'day'), isInMonth: start.isSame(firstDayOfMonth, 'month'), isSelected: start.isSame(dateSelected, 'day'), isSelectable: afterMinDate && beforeMaxDate && beforeFuture }; currentWeek.push(day); if (start.weekday() === 6 || start === endDay) { weeks.push(currentWeek); currentWeek = []; } } return weeks; }
[ "function", "getWeeks", "(", "date", ")", "{", "var", "weeks", "=", "[", "]", ";", "var", "date", "=", "moment", ".", "utc", "(", "date", ")", ";", "var", "firstDayOfMonth", "=", "moment", "(", "date", ")", ".", "date", "(", "1", ")", ";", "var", "lastDayOfMonth", "=", "moment", "(", "date", ")", ".", "date", "(", "date", ".", "daysInMonth", "(", ")", ")", ";", "var", "startDay", "=", "moment", "(", "firstDayOfMonth", ")", ";", "var", "endDay", "=", "moment", "(", "lastDayOfMonth", ")", ";", "// NB: We use weekday() to get a locale aware weekday", "startDay", "=", "firstDayOfMonth", ".", "weekday", "(", ")", "===", "0", "?", "startDay", ":", "startDay", ".", "weekday", "(", "0", ")", ";", "endDay", "=", "lastDayOfMonth", ".", "weekday", "(", ")", "===", "6", "?", "endDay", ":", "endDay", ".", "weekday", "(", "6", ")", ";", "var", "currentWeek", "=", "[", "]", ";", "for", "(", "var", "start", "=", "moment", "(", "startDay", ")", ";", "start", ".", "isBefore", "(", "moment", "(", "endDay", ")", ".", "add", "(", "1", ",", "'days'", ")", ")", ";", "start", ".", "add", "(", "1", ",", "'days'", ")", ")", "{", "var", "afterMinDate", "=", "!", "scope", ".", "config", ".", "minDate", "||", "start", ".", "isAfter", "(", "scope", ".", "config", ".", "minDate", ",", "'day'", ")", ";", "var", "beforeMaxDate", "=", "!", "scope", ".", "config", ".", "maxDate", "||", "start", ".", "isBefore", "(", "scope", ".", "config", ".", "maxDate", ",", "'day'", ")", ";", "var", "isFuture", "=", "start", ".", "isAfter", "(", "today", ")", ";", "var", "beforeFuture", "=", "scope", ".", "config", ".", "allowFuture", "||", "!", "isFuture", ";", "var", "day", "=", "{", "date", ":", "moment", "(", "start", ")", ".", "toDate", "(", ")", ",", "isToday", ":", "start", ".", "isSame", "(", "today", ",", "'day'", ")", ",", "isInMonth", ":", "start", ".", "isSame", "(", "firstDayOfMonth", ",", "'month'", ")", ",", "isSelected", ":", "start", ".", "isSame", "(", "dateSelected", ",", "'day'", ")", ",", "isSelectable", ":", "afterMinDate", "&&", "beforeMaxDate", "&&", "beforeFuture", "}", ";", "currentWeek", ".", "push", "(", "day", ")", ";", "if", "(", "start", ".", "weekday", "(", ")", "===", "6", "||", "start", "===", "endDay", ")", "{", "weeks", ".", "push", "(", "currentWeek", ")", ";", "currentWeek", "=", "[", "]", ";", "}", "}", "return", "weeks", ";", "}" ]
Get all weeks needed to display a month on the Datepicker @return {array} list of weeks objects
[ "Get", "all", "weeks", "needed", "to", "display", "a", "month", "on", "the", "Datepicker" ]
a349e5da015c714b01ca84d087d760fe31e473b5
https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L153-L192
40,861
RemiAWE/ng-flat-datepicker
dist/ng-flat-datepicker.js
resetSelectedDays
function resetSelectedDays () { scope.currentWeeks.forEach(function(week, wIndex){ week.forEach(function(day, dIndex){ scope.currentWeeks[wIndex][dIndex].isSelected = false; }); }); }
javascript
function resetSelectedDays () { scope.currentWeeks.forEach(function(week, wIndex){ week.forEach(function(day, dIndex){ scope.currentWeeks[wIndex][dIndex].isSelected = false; }); }); }
[ "function", "resetSelectedDays", "(", ")", "{", "scope", ".", "currentWeeks", ".", "forEach", "(", "function", "(", "week", ",", "wIndex", ")", "{", "week", ".", "forEach", "(", "function", "(", "day", ",", "dIndex", ")", "{", "scope", ".", "currentWeeks", "[", "wIndex", "]", "[", "dIndex", "]", ".", "isSelected", "=", "false", ";", "}", ")", ";", "}", ")", ";", "}" ]
Reset all selected days
[ "Reset", "all", "selected", "days" ]
a349e5da015c714b01ca84d087d760fe31e473b5
https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L197-L203
40,862
RemiAWE/ng-flat-datepicker
dist/ng-flat-datepicker.js
getYearsList
function getYearsList() { var yearsList = []; for (var i = 2005; i <= moment().year(); i++) { yearsList.push(i); } return yearsList; }
javascript
function getYearsList() { var yearsList = []; for (var i = 2005; i <= moment().year(); i++) { yearsList.push(i); } return yearsList; }
[ "function", "getYearsList", "(", ")", "{", "var", "yearsList", "=", "[", "]", ";", "for", "(", "var", "i", "=", "2005", ";", "i", "<=", "moment", "(", ")", ".", "year", "(", ")", ";", "i", "++", ")", "{", "yearsList", ".", "push", "(", "i", ")", ";", "}", "return", "yearsList", ";", "}" ]
List all years for the select @return {[type]} [description]
[ "List", "all", "years", "for", "the", "select" ]
a349e5da015c714b01ca84d087d760fe31e473b5
https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L229-L235
40,863
RemiAWE/ng-flat-datepicker
dist/ng-flat-datepicker.js
getDaysNames
function getDaysNames () { var daysNameList = []; for (var i = 0; i < 7 ; i++) { daysNameList.push(moment().weekday(i).format('ddd')); } return daysNameList; }
javascript
function getDaysNames () { var daysNameList = []; for (var i = 0; i < 7 ; i++) { daysNameList.push(moment().weekday(i).format('ddd')); } return daysNameList; }
[ "function", "getDaysNames", "(", ")", "{", "var", "daysNameList", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "7", ";", "i", "++", ")", "{", "daysNameList", ".", "push", "(", "moment", "(", ")", ".", "weekday", "(", "i", ")", ".", "format", "(", "'ddd'", ")", ")", ";", "}", "return", "daysNameList", ";", "}" ]
List all days name in the current locale @return {[type]} [description]
[ "List", "all", "days", "name", "in", "the", "current", "locale" ]
a349e5da015c714b01ca84d087d760fe31e473b5
https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L241-L247
40,864
plasticrake/tplink-smarthome-crypto
lib/index.js
encrypt
function encrypt (input, firstKey = 0xAB) { const buf = Buffer.from(input); let key = firstKey; for (let i = 0; i < buf.length; i++) { buf[i] = buf[i] ^ key; key = buf[i]; } return buf; }
javascript
function encrypt (input, firstKey = 0xAB) { const buf = Buffer.from(input); let key = firstKey; for (let i = 0; i < buf.length; i++) { buf[i] = buf[i] ^ key; key = buf[i]; } return buf; }
[ "function", "encrypt", "(", "input", ",", "firstKey", "=", "0xAB", ")", "{", "const", "buf", "=", "Buffer", ".", "from", "(", "input", ")", ";", "let", "key", "=", "firstKey", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "buf", ".", "length", ";", "i", "++", ")", "{", "buf", "[", "i", "]", "=", "buf", "[", "i", "]", "^", "key", ";", "key", "=", "buf", "[", "i", "]", ";", "}", "return", "buf", ";", "}" ]
TP-Link Smarthome Crypto TCP communication includes a 4 byte header, UDP does not. @module tplink-smarthome-crypto Encrypts input where each byte is XOR'd with the previous encrypted byte. @alias module:tplink-smarthome-crypto.encrypt @param {(Buffer|string)} input Buffer/string to encrypt @param {number} [firstKey=0xAB] @return {Buffer} encrypted buffer
[ "TP", "-", "Link", "Smarthome", "Crypto" ]
12a6a3bbcce60913b2c55193818a9fb1854d2b8d
https://github.com/plasticrake/tplink-smarthome-crypto/blob/12a6a3bbcce60913b2c55193818a9fb1854d2b8d/lib/index.js#L15-L23
40,865
plasticrake/tplink-smarthome-crypto
lib/index.js
encryptWithHeader
function encryptWithHeader (input, firstKey = 0xAB) { const msgBuf = encrypt(input, firstKey); const outBuf = Buffer.alloc(msgBuf.length + 4); outBuf.writeUInt32BE(msgBuf.length, 0); msgBuf.copy(outBuf, 4); return outBuf; }
javascript
function encryptWithHeader (input, firstKey = 0xAB) { const msgBuf = encrypt(input, firstKey); const outBuf = Buffer.alloc(msgBuf.length + 4); outBuf.writeUInt32BE(msgBuf.length, 0); msgBuf.copy(outBuf, 4); return outBuf; }
[ "function", "encryptWithHeader", "(", "input", ",", "firstKey", "=", "0xAB", ")", "{", "const", "msgBuf", "=", "encrypt", "(", "input", ",", "firstKey", ")", ";", "const", "outBuf", "=", "Buffer", ".", "alloc", "(", "msgBuf", ".", "length", "+", "4", ")", ";", "outBuf", ".", "writeUInt32BE", "(", "msgBuf", ".", "length", ",", "0", ")", ";", "msgBuf", ".", "copy", "(", "outBuf", ",", "4", ")", ";", "return", "outBuf", ";", "}" ]
Encrypts input that has a 4 byte big-endian length header; each byte is XOR'd with the previous encrypted byte. @alias module:tplink-smarthome-crypto.encryptWithHeader @param {(Buffer|string)} input Buffer/string to encrypt @param {number} [firstKey=0xAB] @return {Buffer} encrypted buffer with header
[ "Encrypts", "input", "that", "has", "a", "4", "byte", "big", "-", "endian", "length", "header", ";", "each", "byte", "is", "XOR", "d", "with", "the", "previous", "encrypted", "byte", "." ]
12a6a3bbcce60913b2c55193818a9fb1854d2b8d
https://github.com/plasticrake/tplink-smarthome-crypto/blob/12a6a3bbcce60913b2c55193818a9fb1854d2b8d/lib/index.js#L32-L38
40,866
plasticrake/tplink-smarthome-crypto
lib/index.js
decrypt
function decrypt (input, firstKey = 0xAB) { const buf = Buffer.from(input); let key = firstKey; let nextKey; for (let i = 0; i < buf.length; i++) { nextKey = buf[i]; buf[i] = buf[i] ^ key; key = nextKey; } return buf; }
javascript
function decrypt (input, firstKey = 0xAB) { const buf = Buffer.from(input); let key = firstKey; let nextKey; for (let i = 0; i < buf.length; i++) { nextKey = buf[i]; buf[i] = buf[i] ^ key; key = nextKey; } return buf; }
[ "function", "decrypt", "(", "input", ",", "firstKey", "=", "0xAB", ")", "{", "const", "buf", "=", "Buffer", ".", "from", "(", "input", ")", ";", "let", "key", "=", "firstKey", ";", "let", "nextKey", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "buf", ".", "length", ";", "i", "++", ")", "{", "nextKey", "=", "buf", "[", "i", "]", ";", "buf", "[", "i", "]", "=", "buf", "[", "i", "]", "^", "key", ";", "key", "=", "nextKey", ";", "}", "return", "buf", ";", "}" ]
Decrypts input where each byte is XOR'd with the previous encrypted byte. @alias module:tplink-smarthome-crypto.decrypt @param {Buffer} input encrypted Buffer @param {number} [firstKey=0xAB] @return {Buffer} decrypted buffer
[ "Decrypts", "input", "where", "each", "byte", "is", "XOR", "d", "with", "the", "previous", "encrypted", "byte", "." ]
12a6a3bbcce60913b2c55193818a9fb1854d2b8d
https://github.com/plasticrake/tplink-smarthome-crypto/blob/12a6a3bbcce60913b2c55193818a9fb1854d2b8d/lib/index.js#L46-L56
40,867
Dev1an/Atem
index.js
getPendingPacket
function getPendingPacket(ls){ var i; for (i = pendingPackets.length - 1; i >= 0; i--) if (pendingPackets[i].header.ls == ls) return pendingPackets[i]; }
javascript
function getPendingPacket(ls){ var i; for (i = pendingPackets.length - 1; i >= 0; i--) if (pendingPackets[i].header.ls == ls) return pendingPackets[i]; }
[ "function", "getPendingPacket", "(", "ls", ")", "{", "var", "i", ";", "for", "(", "i", "=", "pendingPackets", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "if", "(", "pendingPackets", "[", "i", "]", ".", "header", ".", "ls", "==", "ls", ")", "return", "pendingPackets", "[", "i", "]", ";", "}" ]
When an error is encountered during communication, this event will be fired. @event Device#error @type {Error} @property {String} Message Find a pending packet by local sequence number @param {Number} ls Local sequence number @return {UserPacket} The packet
[ "When", "an", "error", "is", "encountered", "during", "communication", "this", "event", "will", "be", "fired", "." ]
22436f436687fcf54a84883b3c9a0c072d55f43a
https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L278-L283
40,868
Dev1an/Atem
index.js
UserPacket
function UserPacket(commands){ Packet.call(this); this.interval = undefined; // If the packet contains commands if (typeof commands !== 'undefined'){ // If it is a connect packet if (commands === null) { this.header.flags = flags.connect; this.body.commands = [{ get length() { return 8; }, serialize: function() { const connectCmd = '0100000000000000'; return (new Buffer(connectCmd, 'hex')); } }]; } else { this.body.commands = commands; this.header.flags = flags.sync; } } // If the packet contains no commands else { this.header.flags = flags.sync; } }
javascript
function UserPacket(commands){ Packet.call(this); this.interval = undefined; // If the packet contains commands if (typeof commands !== 'undefined'){ // If it is a connect packet if (commands === null) { this.header.flags = flags.connect; this.body.commands = [{ get length() { return 8; }, serialize: function() { const connectCmd = '0100000000000000'; return (new Buffer(connectCmd, 'hex')); } }]; } else { this.body.commands = commands; this.header.flags = flags.sync; } } // If the packet contains no commands else { this.header.flags = flags.sync; } }
[ "function", "UserPacket", "(", "commands", ")", "{", "Packet", ".", "call", "(", "this", ")", ";", "this", ".", "interval", "=", "undefined", ";", "// If the packet contains commands", "if", "(", "typeof", "commands", "!==", "'undefined'", ")", "{", "// If it is a connect packet", "if", "(", "commands", "===", "null", ")", "{", "this", ".", "header", ".", "flags", "=", "flags", ".", "connect", ";", "this", ".", "body", ".", "commands", "=", "[", "{", "get", "length", "(", ")", "{", "return", "8", ";", "}", ",", "serialize", ":", "function", "(", ")", "{", "const", "connectCmd", "=", "'0100000000000000'", ";", "return", "(", "new", "Buffer", "(", "connectCmd", ",", "'hex'", ")", ")", ";", "}", "}", "]", ";", "}", "else", "{", "this", ".", "body", ".", "commands", "=", "commands", ";", "this", ".", "header", ".", "flags", "=", "flags", ".", "sync", ";", "}", "}", "// If the packet contains no commands", "else", "{", "this", ".", "header", ".", "flags", "=", "flags", ".", "sync", ";", "}", "}" ]
Create a custom UserPacket. @constructor UserPacket @augments Packet @classdesc A Packet commissiond by the user. This is used to send messages to the ATEM. @param {Command[]|null} [commands] An array of commands. If null, a connect packet will be created
[ "Create", "a", "custom", "UserPacket", "." ]
22436f436687fcf54a84883b3c9a0c072d55f43a
https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L304-L331
40,869
Dev1an/Atem
index.js
AtemPacket
function AtemPacket(msg){ Packet.call(this); this.header.flags = msg[0]>>>3; this.header.uid = msg.readUInt16BE(2); this.header.fs = msg.readUInt16BE(4); this.header.ls = msg.readUInt16BE(10); if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!'); if (state === ConnectionState.attempting) { if (this.isSync()){ atem.state = ConnectionState.establishing; uid = this.header.uid; } } else if (state === ConnectionState.establishing){ if (msg.length==12 && !this.isConnect()){ atem.state = ConnectionState.open; clearInterval(syncInterval); syncInterval = setInterval(sync, 600); } } if (this.isConnect()) { //Do something } else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){ const body = msg.slice(12); var name, data, cmd, cmdLength, cursor=0; while (cursor < body.length-1) { cmdLength = body.readUInt16BE(cursor); name = body.toString('utf8', cursor+4, cursor+8); data = body.slice(cursor+8, cursor+cmdLength); cmd = new Command(name, data); this.body.commands.push(cmd); cursor += cmdLength; /** * @event Device#rawCommand * @type {Command} */ // todo: check foreign sequence number, to prevent the event emitter // from emitting the same message twice. atem.emit('rawCommand', cmd); atem.emit(cmd.name, cmd.data); } } else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) { const err = new Error('Message length mismatch'); self.emit('error', err); } else { const err2 = new Error('UID mismatch'); self.emit('error', err2); } }
javascript
function AtemPacket(msg){ Packet.call(this); this.header.flags = msg[0]>>>3; this.header.uid = msg.readUInt16BE(2); this.header.fs = msg.readUInt16BE(4); this.header.ls = msg.readUInt16BE(10); if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!'); if (state === ConnectionState.attempting) { if (this.isSync()){ atem.state = ConnectionState.establishing; uid = this.header.uid; } } else if (state === ConnectionState.establishing){ if (msg.length==12 && !this.isConnect()){ atem.state = ConnectionState.open; clearInterval(syncInterval); syncInterval = setInterval(sync, 600); } } if (this.isConnect()) { //Do something } else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){ const body = msg.slice(12); var name, data, cmd, cmdLength, cursor=0; while (cursor < body.length-1) { cmdLength = body.readUInt16BE(cursor); name = body.toString('utf8', cursor+4, cursor+8); data = body.slice(cursor+8, cursor+cmdLength); cmd = new Command(name, data); this.body.commands.push(cmd); cursor += cmdLength; /** * @event Device#rawCommand * @type {Command} */ // todo: check foreign sequence number, to prevent the event emitter // from emitting the same message twice. atem.emit('rawCommand', cmd); atem.emit(cmd.name, cmd.data); } } else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) { const err = new Error('Message length mismatch'); self.emit('error', err); } else { const err2 = new Error('UID mismatch'); self.emit('error', err2); } }
[ "function", "AtemPacket", "(", "msg", ")", "{", "Packet", ".", "call", "(", "this", ")", ";", "this", ".", "header", ".", "flags", "=", "msg", "[", "0", "]", ">>>", "3", ";", "this", ".", "header", ".", "uid", "=", "msg", ".", "readUInt16BE", "(", "2", ")", ";", "this", ".", "header", ".", "fs", "=", "msg", ".", "readUInt16BE", "(", "4", ")", ";", "this", ".", "header", ".", "ls", "=", "msg", ".", "readUInt16BE", "(", "10", ")", ";", "if", "(", "(", "this", ".", "header", ".", "flags", "&", "flags", ".", "unknown", ")", "==", "flags", ".", "unknown", ")", "console", ".", "log", "(", "'Unknown Packet flag!'", ")", ";", "if", "(", "state", "===", "ConnectionState", ".", "attempting", ")", "{", "if", "(", "this", ".", "isSync", "(", ")", ")", "{", "atem", ".", "state", "=", "ConnectionState", ".", "establishing", ";", "uid", "=", "this", ".", "header", ".", "uid", ";", "}", "}", "else", "if", "(", "state", "===", "ConnectionState", ".", "establishing", ")", "{", "if", "(", "msg", ".", "length", "==", "12", "&&", "!", "this", ".", "isConnect", "(", ")", ")", "{", "atem", ".", "state", "=", "ConnectionState", ".", "open", ";", "clearInterval", "(", "syncInterval", ")", ";", "syncInterval", "=", "setInterval", "(", "sync", ",", "600", ")", ";", "}", "}", "if", "(", "this", ".", "isConnect", "(", ")", ")", "{", "//Do something", "}", "else", "if", "(", "(", "msg", ".", "length", "==", "(", "msg", ".", "readUInt16BE", "(", "0", ")", "&", "0x7FF", ")", "&&", "this", ".", "header", ".", "uid", "==", "uid", ")", ")", "{", "const", "body", "=", "msg", ".", "slice", "(", "12", ")", ";", "var", "name", ",", "data", ",", "cmd", ",", "cmdLength", ",", "cursor", "=", "0", ";", "while", "(", "cursor", "<", "body", ".", "length", "-", "1", ")", "{", "cmdLength", "=", "body", ".", "readUInt16BE", "(", "cursor", ")", ";", "name", "=", "body", ".", "toString", "(", "'utf8'", ",", "cursor", "+", "4", ",", "cursor", "+", "8", ")", ";", "data", "=", "body", ".", "slice", "(", "cursor", "+", "8", ",", "cursor", "+", "cmdLength", ")", ";", "cmd", "=", "new", "Command", "(", "name", ",", "data", ")", ";", "this", ".", "body", ".", "commands", ".", "push", "(", "cmd", ")", ";", "cursor", "+=", "cmdLength", ";", "/**\n\t\t\t\t * @event Device#rawCommand\n\t\t\t\t * @type {Command}\n\t\t\t\t */", "// todo: check foreign sequence number, to prevent the event emitter", "// from emitting the same message twice.", "atem", ".", "emit", "(", "'rawCommand'", ",", "cmd", ")", ";", "atem", ".", "emit", "(", "cmd", ".", "name", ",", "cmd", ".", "data", ")", ";", "}", "}", "else", "if", "(", "msg", ".", "length", "!=", "(", "msg", ".", "readUInt16BE", "(", "0", ")", "&", "0x7FF", ")", ")", "{", "const", "err", "=", "new", "Error", "(", "'Message length mismatch'", ")", ";", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "else", "{", "const", "err2", "=", "new", "Error", "(", "'UID mismatch'", ")", ";", "self", ".", "emit", "(", "'error'", ",", "err2", ")", ";", "}", "}" ]
Parse an ATEM UDP message @constructor AtemPacket @augments Packet @classdesc Used to parse an UDP message from the Atem @param {Buffer} msg The message to parse
[ "Parse", "an", "ATEM", "UDP", "message" ]
22436f436687fcf54a84883b3c9a0c072d55f43a
https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L435-L492
40,870
Dev1an/Atem
index.js
handleQueue
function handleQueue() { const count = commandQueue.length if (count>0) { const packet = new UserPacket(commandQueue.slice(0)); commandQueue = []; packet.transmit(); } return count }
javascript
function handleQueue() { const count = commandQueue.length if (count>0) { const packet = new UserPacket(commandQueue.slice(0)); commandQueue = []; packet.transmit(); } return count }
[ "function", "handleQueue", "(", ")", "{", "const", "count", "=", "commandQueue", ".", "length", "if", "(", "count", ">", "0", ")", "{", "const", "packet", "=", "new", "UserPacket", "(", "commandQueue", ".", "slice", "(", "0", ")", ")", ";", "commandQueue", "=", "[", "]", ";", "packet", ".", "transmit", "(", ")", ";", "}", "return", "count", "}" ]
Sends a packet with all the remaining command of the commandQueue
[ "Sends", "a", "packet", "with", "all", "the", "remaining", "command", "of", "the", "commandQueue" ]
22436f436687fcf54a84883b3c9a0c072d55f43a
https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L540-L551
40,871
bojand/json-schema-test-data-generator
lib/index.js
generate
function generate(schema) { const ret = []; if (!validate(schema)) { return ret; } const fullSample = jsf(schema); if (!fullSample) { return ret; } ret.push({ valid: true, data: fullSample, message: 'should work with all required properties' }); ret.push(...generateFromRequired(schema)); ret.push(...generateFromRequired(schema, false)); ret.push(...generateForTypes(schema)); return ret; }
javascript
function generate(schema) { const ret = []; if (!validate(schema)) { return ret; } const fullSample = jsf(schema); if (!fullSample) { return ret; } ret.push({ valid: true, data: fullSample, message: 'should work with all required properties' }); ret.push(...generateFromRequired(schema)); ret.push(...generateFromRequired(schema, false)); ret.push(...generateForTypes(schema)); return ret; }
[ "function", "generate", "(", "schema", ")", "{", "const", "ret", "=", "[", "]", ";", "if", "(", "!", "validate", "(", "schema", ")", ")", "{", "return", "ret", ";", "}", "const", "fullSample", "=", "jsf", "(", "schema", ")", ";", "if", "(", "!", "fullSample", ")", "{", "return", "ret", ";", "}", "ret", ".", "push", "(", "{", "valid", ":", "true", ",", "data", ":", "fullSample", ",", "message", ":", "'should work with all required properties'", "}", ")", ";", "ret", ".", "push", "(", "...", "generateFromRequired", "(", "schema", ")", ")", ";", "ret", ".", "push", "(", "...", "generateFromRequired", "(", "schema", ",", "false", ")", ")", ";", "ret", ".", "push", "(", "...", "generateForTypes", "(", "schema", ")", ")", ";", "return", "ret", ";", "}" ]
Generates test data based on JSON schema @param {Object} schema Fully expanded (no <code>$ref</code>) JSON Schema @return {Array} Array of test data objects
[ "Generates", "test", "data", "based", "on", "JSON", "schema" ]
32c07f7e7a767ec87c2403acad2018754bea862d
https://github.com/bojand/json-schema-test-data-generator/blob/32c07f7e7a767ec87c2403acad2018754bea862d/lib/index.js#L420-L442
40,872
noderaider/localsync
packages/serversync/lib/index.js
serversync
function serversync(key, action, handler) { var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, _ref$tracing = _ref.tracing, tracing = _ref$tracing === undefined ? false : _ref$tracing, _ref$logger = _ref.logger, logger = _ref$logger === undefined ? console : _ref$logger, _ref$logLevel = _ref.logLevel, logLevel = _ref$logLevel === undefined ? 'info' : _ref$logLevel; (0, _invariant2.default)(key, 'key is required'); (0, _invariant2.default)(action, 'action is required'); (0, _invariant2.default)(handler, 'handler is required'); var log = function log() { return tracing ? logger[logLevel].apply(logger, arguments) : function () {}; }; var isRunning = false; var trigger = function trigger() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log('serversync#trigger', args); var value = action.apply(undefined, args); log('serversync#trigger action output ignored', args, value); }; var start = function start() { log('serversync#start'); isRunning = true; }; var stop = function stop() { log('serversync#stop'); isRunning = false; }; return { start: start, stop: stop, trigger: trigger, get isRunning() { return isRunning; }, mechanism: mechanism, isFallback: false, isServer: true }; }
javascript
function serversync(key, action, handler) { var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, _ref$tracing = _ref.tracing, tracing = _ref$tracing === undefined ? false : _ref$tracing, _ref$logger = _ref.logger, logger = _ref$logger === undefined ? console : _ref$logger, _ref$logLevel = _ref.logLevel, logLevel = _ref$logLevel === undefined ? 'info' : _ref$logLevel; (0, _invariant2.default)(key, 'key is required'); (0, _invariant2.default)(action, 'action is required'); (0, _invariant2.default)(handler, 'handler is required'); var log = function log() { return tracing ? logger[logLevel].apply(logger, arguments) : function () {}; }; var isRunning = false; var trigger = function trigger() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } log('serversync#trigger', args); var value = action.apply(undefined, args); log('serversync#trigger action output ignored', args, value); }; var start = function start() { log('serversync#start'); isRunning = true; }; var stop = function stop() { log('serversync#stop'); isRunning = false; }; return { start: start, stop: stop, trigger: trigger, get isRunning() { return isRunning; }, mechanism: mechanism, isFallback: false, isServer: true }; }
[ "function", "serversync", "(", "key", ",", "action", ",", "handler", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "{", "}", ",", "_ref$tracing", "=", "_ref", ".", "tracing", ",", "tracing", "=", "_ref$tracing", "===", "undefined", "?", "false", ":", "_ref$tracing", ",", "_ref$logger", "=", "_ref", ".", "logger", ",", "logger", "=", "_ref$logger", "===", "undefined", "?", "console", ":", "_ref$logger", ",", "_ref$logLevel", "=", "_ref", ".", "logLevel", ",", "logLevel", "=", "_ref$logLevel", "===", "undefined", "?", "'info'", ":", "_ref$logLevel", ";", "(", "0", ",", "_invariant2", ".", "default", ")", "(", "key", ",", "'key is required'", ")", ";", "(", "0", ",", "_invariant2", ".", "default", ")", "(", "action", ",", "'action is required'", ")", ";", "(", "0", ",", "_invariant2", ".", "default", ")", "(", "handler", ",", "'handler is required'", ")", ";", "var", "log", "=", "function", "log", "(", ")", "{", "return", "tracing", "?", "logger", "[", "logLevel", "]", ".", "apply", "(", "logger", ",", "arguments", ")", ":", "function", "(", ")", "{", "}", ";", "}", ";", "var", "isRunning", "=", "false", ";", "var", "trigger", "=", "function", "trigger", "(", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "_len", ")", ",", "_key", "=", "0", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "]", "=", "arguments", "[", "_key", "]", ";", "}", "log", "(", "'serversync#trigger'", ",", "args", ")", ";", "var", "value", "=", "action", ".", "apply", "(", "undefined", ",", "args", ")", ";", "log", "(", "'serversync#trigger action output ignored'", ",", "args", ",", "value", ")", ";", "}", ";", "var", "start", "=", "function", "start", "(", ")", "{", "log", "(", "'serversync#start'", ")", ";", "isRunning", "=", "true", ";", "}", ";", "var", "stop", "=", "function", "stop", "(", ")", "{", "log", "(", "'serversync#stop'", ")", ";", "isRunning", "=", "false", ";", "}", ";", "return", "{", "start", ":", "start", ",", "stop", ":", "stop", ",", "trigger", ":", "trigger", ",", "get", "isRunning", "(", ")", "{", "return", "isRunning", ";", "}", ",", "mechanism", ":", "mechanism", ",", "isFallback", ":", "false", ",", "isServer", ":", "true", "}", ";", "}" ]
Creates a mock synchronizer which uses a server safe interface equivalent to serversync @param {string} key The key to synchronize on. @param {function} action The action to run when trigger is executed. Should return the payload to be transmitted to the handlers on other tabs. @param {function} handler The handler which is executed on other tabs when a synchronization is triggered. Argument is the return value of the action. @param {boolean} [options.tracing=false] Option to turn on tracing for debugging. @param {Object} [options.logger=console] The logger to debug to. @param {string} [options.logLevel=info] The log level to trace at. @return {Object} serversync instance with start, stop, trigger, isRunning, and isFallback mock properties.
[ "Creates", "a", "mock", "synchronizer", "which", "uses", "a", "server", "safe", "interface", "equivalent", "to", "serversync" ]
489c68f57203b79c2403aaf045e194ff6b7b7d38
https://github.com/noderaider/localsync/blob/489c68f57203b79c2403aaf045e194ff6b7b7d38/packages/serversync/lib/index.js#L26-L73
40,873
ArminTamzarian/node-calendar
node-calendar.js
_extractLocaleDays
function _extractLocaleDays(abbr, locale) { if(abbr) { return cldr ? cldr.extractDayNames(locale).format.abbreviated : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; } else { return cldr ? cldr.extractDayNames(locale).format.wide : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; } }
javascript
function _extractLocaleDays(abbr, locale) { if(abbr) { return cldr ? cldr.extractDayNames(locale).format.abbreviated : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; } else { return cldr ? cldr.extractDayNames(locale).format.wide : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; } }
[ "function", "_extractLocaleDays", "(", "abbr", ",", "locale", ")", "{", "if", "(", "abbr", ")", "{", "return", "cldr", "?", "cldr", ".", "extractDayNames", "(", "locale", ")", ".", "format", ".", "abbreviated", ":", "[", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", ",", "'Sun'", "]", ";", "}", "else", "{", "return", "cldr", "?", "cldr", ".", "extractDayNames", "(", "locale", ")", ".", "format", ".", "wide", ":", "[", "'Monday'", ",", "'Tuesday'", ",", "'Wednesday'", ",", "'Thursday'", ",", "'Friday'", ",", "'Saturday'", ",", "'Sunday'", "]", ";", "}", "}" ]
Extracts the wide or abbreviated day names for a specified locale. If cldr is not installed values default to that for locale en_US. @param {Boolean} abbr @param {String} locale @api private
[ "Extracts", "the", "wide", "or", "abbreviated", "day", "names", "for", "a", "specified", "locale", ".", "If", "cldr", "is", "not", "installed", "values", "default", "to", "that", "for", "locale", "en_US", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L37-L44
40,874
ArminTamzarian/node-calendar
node-calendar.js
_extractLocaleMonths
function _extractLocaleMonths(abbr, locale) { var months = [] if(abbr) { months = cldr ? cldr.extractMonthNames(locale).format.abbreviated : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; } else { months = cldr ? cldr.extractMonthNames(locale).format.wide : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; } months.unshift(''); return months; }
javascript
function _extractLocaleMonths(abbr, locale) { var months = [] if(abbr) { months = cldr ? cldr.extractMonthNames(locale).format.abbreviated : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; } else { months = cldr ? cldr.extractMonthNames(locale).format.wide : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; } months.unshift(''); return months; }
[ "function", "_extractLocaleMonths", "(", "abbr", ",", "locale", ")", "{", "var", "months", "=", "[", "]", "if", "(", "abbr", ")", "{", "months", "=", "cldr", "?", "cldr", ".", "extractMonthNames", "(", "locale", ")", ".", "format", ".", "abbreviated", ":", "[", "'Jan'", ",", "'Feb'", ",", "'Mar'", ",", "'Apr'", ",", "'May'", ",", "'Jun'", ",", "'Jul'", ",", "'Aug'", ",", "'Sep'", ",", "'Oct'", ",", "'Nov'", ",", "'Dec'", "]", ";", "}", "else", "{", "months", "=", "cldr", "?", "cldr", ".", "extractMonthNames", "(", "locale", ")", ".", "format", ".", "wide", ":", "[", "'January'", ",", "'February'", ",", "'March'", ",", "'April'", ",", "'May'", ",", "'June'", ",", "'July'", ",", "'August'", ",", "'September'", ",", "'October'", ",", "'November'", ",", "'December'", "]", ";", "}", "months", ".", "unshift", "(", "''", ")", ";", "return", "months", ";", "}" ]
Extracts the wide or abbreviated month names for a specified locale. If cldr is not installed values default to that for locale en_US. @param {Boolean} abbr @param {String} locale @api private
[ "Extracts", "the", "wide", "or", "abbreviated", "month", "names", "for", "a", "specified", "locale", ".", "If", "cldr", "is", "not", "installed", "values", "default", "to", "that", "for", "locale", "en_US", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L54-L65
40,875
ArminTamzarian/node-calendar
node-calendar.js
_toordinal
function _toordinal(year, month, day) { var days_before_year = ((year - 1) * 365) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400); var days_before_month = _DAYS_BEFORE_MONTH[month] + (month > 2 && isleap(year) ? 1 : 0); return (days_before_year + days_before_month + day); }
javascript
function _toordinal(year, month, day) { var days_before_year = ((year - 1) * 365) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400); var days_before_month = _DAYS_BEFORE_MONTH[month] + (month > 2 && isleap(year) ? 1 : 0); return (days_before_year + days_before_month + day); }
[ "function", "_toordinal", "(", "year", ",", "month", ",", "day", ")", "{", "var", "days_before_year", "=", "(", "(", "year", "-", "1", ")", "*", "365", ")", "+", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "4", ")", "-", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "100", ")", "+", "Math", ".", "floor", "(", "(", "year", "-", "1", ")", "/", "400", ")", ";", "var", "days_before_month", "=", "_DAYS_BEFORE_MONTH", "[", "month", "]", "+", "(", "month", ">", "2", "&&", "isleap", "(", "year", ")", "?", "1", ":", "0", ")", ";", "return", "(", "days_before_year", "+", "days_before_month", "+", "day", ")", ";", "}" ]
Calculates the ordinal time from given year, month, day values. @param {Number} year @param {Number} month @param {Number} day @api private
[ "Calculates", "the", "ordinal", "time", "from", "given", "year", "month", "day", "values", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L75-L79
40,876
ArminTamzarian/node-calendar
node-calendar.js
leapdays
function leapdays(y1, y2) { y1--; y2--; return (Math.floor(y2/4) - Math.floor(y1/4)) - (Math.floor(y2/100) - Math.floor(y1/100)) + (Math.floor(y2/400) - Math.floor(y1/400)); }
javascript
function leapdays(y1, y2) { y1--; y2--; return (Math.floor(y2/4) - Math.floor(y1/4)) - (Math.floor(y2/100) - Math.floor(y1/100)) + (Math.floor(y2/400) - Math.floor(y1/400)); }
[ "function", "leapdays", "(", "y1", ",", "y2", ")", "{", "y1", "--", ";", "y2", "--", ";", "return", "(", "Math", ".", "floor", "(", "y2", "/", "4", ")", "-", "Math", ".", "floor", "(", "y1", "/", "4", ")", ")", "-", "(", "Math", ".", "floor", "(", "y2", "/", "100", ")", "-", "Math", ".", "floor", "(", "y1", "/", "100", ")", ")", "+", "(", "Math", ".", "floor", "(", "y2", "/", "400", ")", "-", "Math", ".", "floor", "(", "y1", "/", "400", ")", ")", ";", "}" ]
Return number of leap years in range [y1, y2). Assumes y1 <= y2. @param {Number} y1 @param {Number} y2 @api public
[ "Return", "number", "of", "leap", "years", "in", "range", "[", "y1", "y2", ")", ".", "Assumes", "y1", "<", "=", "y2", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L99-L103
40,877
ArminTamzarian/node-calendar
node-calendar.js
setlocale
function setlocale(locale) { locale = typeof(locale) === "undefined" ? "en_US" : locale; if((cldr && (cldr.localeIds.indexOf(locale.replace(/-/g, '_').toLowerCase()) === -1)) || (!cldr && ((locale.replace(/-/g, '_').toLowerCase() !== "en_us")))) { throw new IllegalLocaleError(); } this.day_name = _extractLocaleDays(false, locale); this.day_abbr = _extractLocaleDays(true, locale); this.month_name = _extractLocaleMonths(false, locale); this.month_abbr = _extractLocaleMonths(true, locale); }
javascript
function setlocale(locale) { locale = typeof(locale) === "undefined" ? "en_US" : locale; if((cldr && (cldr.localeIds.indexOf(locale.replace(/-/g, '_').toLowerCase()) === -1)) || (!cldr && ((locale.replace(/-/g, '_').toLowerCase() !== "en_us")))) { throw new IllegalLocaleError(); } this.day_name = _extractLocaleDays(false, locale); this.day_abbr = _extractLocaleDays(true, locale); this.month_name = _extractLocaleMonths(false, locale); this.month_abbr = _extractLocaleMonths(true, locale); }
[ "function", "setlocale", "(", "locale", ")", "{", "locale", "=", "typeof", "(", "locale", ")", "===", "\"undefined\"", "?", "\"en_US\"", ":", "locale", ";", "if", "(", "(", "cldr", "&&", "(", "cldr", ".", "localeIds", ".", "indexOf", "(", "locale", ".", "replace", "(", "/", "-", "/", "g", ",", "'_'", ")", ".", "toLowerCase", "(", ")", ")", "===", "-", "1", ")", ")", "||", "(", "!", "cldr", "&&", "(", "(", "locale", ".", "replace", "(", "/", "-", "/", "g", ",", "'_'", ")", ".", "toLowerCase", "(", ")", "!==", "\"en_us\"", ")", ")", ")", ")", "{", "throw", "new", "IllegalLocaleError", "(", ")", ";", "}", "this", ".", "day_name", "=", "_extractLocaleDays", "(", "false", ",", "locale", ")", ";", "this", ".", "day_abbr", "=", "_extractLocaleDays", "(", "true", ",", "locale", ")", ";", "this", ".", "month_name", "=", "_extractLocaleMonths", "(", "false", ",", "locale", ")", ";", "this", ".", "month_abbr", "=", "_extractLocaleMonths", "(", "true", ",", "locale", ")", ";", "}" ]
Sets the locale for use in extracting month and weekday names. @param {String} locale @throws {IllegalLocaleError} If the provided locale is invalid. @api public
[ "Sets", "the", "locale", "for", "use", "in", "extracting", "month", "and", "weekday", "names", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L132-L143
40,878
ArminTamzarian/node-calendar
node-calendar.js
timegm
function timegm(timegmt) { var year = timegmt[0]; var month = timegmt[1]; var day = timegmt[2]; var hour = timegmt[3]; var minute = timegmt[4]; var second = timegmt[5]; if(month < 1 || month > 12) { throw new IllegalMonthError(); } if(day < 1 || day > (_DAYS_IN_MONTH[month] + (month === 2 && isleap(year)))) { throw new IllegalDayError(); } if(hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) { throw new IllegalTimeError(); } var days = _toordinal(year, month, 1) - 719163 + day - 1; var hours = (days * 24) + hour; var minutes = (hours * 60) + minute; var seconds = (minutes * 60) + second; return seconds; }
javascript
function timegm(timegmt) { var year = timegmt[0]; var month = timegmt[1]; var day = timegmt[2]; var hour = timegmt[3]; var minute = timegmt[4]; var second = timegmt[5]; if(month < 1 || month > 12) { throw new IllegalMonthError(); } if(day < 1 || day > (_DAYS_IN_MONTH[month] + (month === 2 && isleap(year)))) { throw new IllegalDayError(); } if(hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) { throw new IllegalTimeError(); } var days = _toordinal(year, month, 1) - 719163 + day - 1; var hours = (days * 24) + hour; var minutes = (hours * 60) + minute; var seconds = (minutes * 60) + second; return seconds; }
[ "function", "timegm", "(", "timegmt", ")", "{", "var", "year", "=", "timegmt", "[", "0", "]", ";", "var", "month", "=", "timegmt", "[", "1", "]", ";", "var", "day", "=", "timegmt", "[", "2", "]", ";", "var", "hour", "=", "timegmt", "[", "3", "]", ";", "var", "minute", "=", "timegmt", "[", "4", "]", ";", "var", "second", "=", "timegmt", "[", "5", "]", ";", "if", "(", "month", "<", "1", "||", "month", ">", "12", ")", "{", "throw", "new", "IllegalMonthError", "(", ")", ";", "}", "if", "(", "day", "<", "1", "||", "day", ">", "(", "_DAYS_IN_MONTH", "[", "month", "]", "+", "(", "month", "===", "2", "&&", "isleap", "(", "year", ")", ")", ")", ")", "{", "throw", "new", "IllegalDayError", "(", ")", ";", "}", "if", "(", "hour", "<", "0", "||", "hour", ">", "23", "||", "minute", "<", "0", "||", "minute", ">", "59", "||", "second", "<", "0", "||", "second", ">", "59", ")", "{", "throw", "new", "IllegalTimeError", "(", ")", ";", "}", "var", "days", "=", "_toordinal", "(", "year", ",", "month", ",", "1", ")", "-", "719163", "+", "day", "-", "1", ";", "var", "hours", "=", "(", "days", "*", "24", ")", "+", "hour", ";", "var", "minutes", "=", "(", "hours", "*", "60", ")", "+", "minute", ";", "var", "seconds", "=", "(", "minutes", "*", "60", ")", "+", "second", ";", "return", "seconds", ";", "}" ]
Unrelated but handy function to calculate Unix timestamp from GMT. @param {Array} tuple @throws {IllegalMonthError} If the provided month element is invalid. @throws {IllegalDayError} If the provided day element is invalid. @api public
[ "Unrelated", "but", "handy", "function", "to", "calculate", "Unix", "timestamp", "from", "GMT", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L153-L179
40,879
ArminTamzarian/node-calendar
node-calendar.js
Calendar
function Calendar(firstweekday) { this._firstweekday = typeof(firstweekday) === "undefined" ? 0 : firstweekday; if(firstweekday < 0 || firstweekday > 6) { throw new IllegalWeekdayError(); } this._oneday = 1000 * 60 * 60 * 24; this._onehour = 1000 * 60 * 60; }
javascript
function Calendar(firstweekday) { this._firstweekday = typeof(firstweekday) === "undefined" ? 0 : firstweekday; if(firstweekday < 0 || firstweekday > 6) { throw new IllegalWeekdayError(); } this._oneday = 1000 * 60 * 60 * 24; this._onehour = 1000 * 60 * 60; }
[ "function", "Calendar", "(", "firstweekday", ")", "{", "this", ".", "_firstweekday", "=", "typeof", "(", "firstweekday", ")", "===", "\"undefined\"", "?", "0", ":", "firstweekday", ";", "if", "(", "firstweekday", "<", "0", "||", "firstweekday", ">", "6", ")", "{", "throw", "new", "IllegalWeekdayError", "(", ")", ";", "}", "this", ".", "_oneday", "=", "1000", "*", "60", "*", "60", "*", "24", ";", "this", ".", "_onehour", "=", "1000", "*", "60", "*", "60", ";", "}" ]
Base calendar class. This class doesn't do any formatting. It simply provides data to subclasses. @param {Number} firstweekday @throws {IllegalWeekdayError} If the provided firstweekday is invalid. @api public
[ "Base", "calendar", "class", ".", "This", "class", "doesn", "t", "do", "any", "formatting", ".", "It", "simply", "provides", "data", "to", "subclasses", "." ]
aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0
https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L214-L223
40,880
graphql-factory/graphql-factory
archive/refactoring/subscription/resolver.js
defaultClientIDHandler
function defaultClientIDHandler(args, context, info) { return get(args, [ 'clientID' ]) || get(context, [ 'clientID' ]) || get(info, [ 'rootValue', 'clientID' ]); }
javascript
function defaultClientIDHandler(args, context, info) { return get(args, [ 'clientID' ]) || get(context, [ 'clientID' ]) || get(info, [ 'rootValue', 'clientID' ]); }
[ "function", "defaultClientIDHandler", "(", "args", ",", "context", ",", "info", ")", "{", "return", "get", "(", "args", ",", "[", "'clientID'", "]", ")", "||", "get", "(", "context", ",", "[", "'clientID'", "]", ")", "||", "get", "(", "info", ",", "[", "'rootValue'", ",", "'clientID'", "]", ")", ";", "}" ]
Default client id handler checks args then context then rootValue for a clientID field to use @param {*} args @param {*} context @param {*} info
[ "Default", "client", "id", "handler", "checks", "args", "then", "context", "then", "rootValue", "for", "a", "clientID", "field", "to", "use" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/refactoring/subscription/resolver.js#L11-L15
40,881
jrmerz/leaflet-canvas-geojson
src/lib/toCanvasXY.js
trimCanvasXY
function trimCanvasXY(xy) { if( xy.length === 0 ) return; var last = xy[xy.length-1], i, point; var c = 0; for( i = xy.length-2; i >= 0; i-- ) { point = xy[i]; if( Math.abs(last.x - point.x) === 0 && Math.abs(last.y - point.y) === 0 ) { xy.splice(i, 1); c++; } else { last = point; } } if( xy.length <= 1 ) { xy.push(last); c--; } }
javascript
function trimCanvasXY(xy) { if( xy.length === 0 ) return; var last = xy[xy.length-1], i, point; var c = 0; for( i = xy.length-2; i >= 0; i-- ) { point = xy[i]; if( Math.abs(last.x - point.x) === 0 && Math.abs(last.y - point.y) === 0 ) { xy.splice(i, 1); c++; } else { last = point; } } if( xy.length <= 1 ) { xy.push(last); c--; } }
[ "function", "trimCanvasXY", "(", "xy", ")", "{", "if", "(", "xy", ".", "length", "===", "0", ")", "return", ";", "var", "last", "=", "xy", "[", "xy", ".", "length", "-", "1", "]", ",", "i", ",", "point", ";", "var", "c", "=", "0", ";", "for", "(", "i", "=", "xy", ".", "length", "-", "2", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "point", "=", "xy", "[", "i", "]", ";", "if", "(", "Math", ".", "abs", "(", "last", ".", "x", "-", "point", ".", "x", ")", "===", "0", "&&", "Math", ".", "abs", "(", "last", ".", "y", "-", "point", ".", "y", ")", "===", "0", ")", "{", "xy", ".", "splice", "(", "i", ",", "1", ")", ";", "c", "++", ";", "}", "else", "{", "last", "=", "point", ";", "}", "}", "if", "(", "xy", ".", "length", "<=", "1", ")", "{", "xy", ".", "push", "(", "last", ")", ";", "c", "--", ";", "}", "}" ]
given an array of geo xy coordinates, make sure each point is at least more than 1px apart
[ "given", "an", "array", "of", "geo", "xy", "coordinates", "make", "sure", "each", "point", "is", "at", "least", "more", "than", "1px", "apart" ]
39ccf82d6ee89684b3f5c826c013210dad954d8f
https://github.com/jrmerz/leaflet-canvas-geojson/blob/39ccf82d6ee89684b3f5c826c013210dad954d8f/src/lib/toCanvasXY.js#L45-L64
40,882
dundalek/warehouse
backend/base.js
function(backend, name, options) { options = _.extend({keyPath: 'id'}, options || {}); this.options = options; this.backend = backend; this.name = name; this.keyPath = this.options.keyPath; }
javascript
function(backend, name, options) { options = _.extend({keyPath: 'id'}, options || {}); this.options = options; this.backend = backend; this.name = name; this.keyPath = this.options.keyPath; }
[ "function", "(", "backend", ",", "name", ",", "options", ")", "{", "options", "=", "_", ".", "extend", "(", "{", "keyPath", ":", "'id'", "}", ",", "options", "||", "{", "}", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "backend", "=", "backend", ";", "this", ".", "name", "=", "name", ";", "this", ".", "keyPath", "=", "this", ".", "options", ".", "keyPath", ";", "}" ]
Initialize the backend instance @constructs
[ "Initialize", "the", "backend", "instance" ]
d5a964a5997c28170dc907ad91b80ea3cb049faa
https://github.com/dundalek/warehouse/blob/d5a964a5997c28170dc907ad91b80ea3cb049faa/backend/base.js#L65-L72
40,883
graphql-factory/graphql-factory
archive/src-concept/generate/middleware.js
resolverMiddleware
function resolverMiddleware (resolver) { return function (req, res, next) { try { const { source, args, context, info } = req const ctx = { req, res, next } const value = resolver.call(ctx, source, args, context, info) return Promise.resolve(value) .then(result => { req.result = result return next() }) .catch(next) } catch (err) { return next(err) } } }
javascript
function resolverMiddleware (resolver) { return function (req, res, next) { try { const { source, args, context, info } = req const ctx = { req, res, next } const value = resolver.call(ctx, source, args, context, info) return Promise.resolve(value) .then(result => { req.result = result return next() }) .catch(next) } catch (err) { return next(err) } } }
[ "function", "resolverMiddleware", "(", "resolver", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "try", "{", "const", "{", "source", ",", "args", ",", "context", ",", "info", "}", "=", "req", "const", "ctx", "=", "{", "req", ",", "res", ",", "next", "}", "const", "value", "=", "resolver", ".", "call", "(", "ctx", ",", "source", ",", "args", ",", "context", ",", "info", ")", "return", "Promise", ".", "resolve", "(", "value", ")", ".", "then", "(", "result", "=>", "{", "req", ".", "result", "=", "result", "return", "next", "(", ")", "}", ")", ".", "catch", "(", "next", ")", "}", "catch", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "}", "}" ]
Wraps the resolver function in middleware so that it can be added to a middleware queue and processed the same way as other middleware @param resolver @returns {Function}
[ "Wraps", "the", "resolver", "function", "in", "middleware", "so", "that", "it", "can", "be", "added", "to", "a", "middleware", "queue", "and", "processed", "the", "same", "way", "as", "other", "middleware" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src-concept/generate/middleware.js#L18-L35
40,884
graphql-factory/graphql-factory
archive/src-concept/generate/middleware.js
nextMiddleware
function nextMiddleware (factory, mw, info) { const { resolved, index, routes, middlewares, errorMiddleware, req, res, metrics } = info const local = { finished: false, timeout: null } // check if the request has already been resolved if (resolved) return // get the current middleware const current = mw[index] const exec = { name: current.functionName, started: Date.now(), ended: null, data: null } metrics.executions.push(exec) // create a next method const next = data => { clearTimeout(local.timeout) if (local.finished || info.resolved) return local.finished = true // add the result exec.ended = Date.now() exec.data = data // allow reroutes to valid named route paths if (_.isString(data)) { const route = routes[data] if (!route) { if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 req.error = new Error(`No route found for "${data}"`) return nextMiddleware(factory, errorMiddleware, info) } res.end(data) } // get the correct route set const mwSet = route.type === ERROR_MIDDLEWARE ? errorMiddleware : middlewares // increment the re-route counter, set the index and go req.reroutes += 1 info.index = route.index return nextMiddleware(factory, mwSet, info) } // check for an error passed to the next method and not // already in the error middleware chain. if condition met // start processing error middleware if (data instanceof Error) { if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 req.error = data return nextMiddleware(factory, errorMiddleware, info) } res.end(data) } // check if there is any more middleware in the chain // if not, call end to complete the request return info.index === mw.length ? res.end() : nextMiddleware(factory, mw, info) } // create a timeout for the middleware if timeout > 0 if (current.timeout > 0) { local.timeout = setTimeout(() => { local.finished = true req.error = new Error(current.functionName + ' middleware timed out') // add the result exec.ended = Date.now() exec.data = req.error // if already in error middleware and timed out // end the entire request, othewise move to error mw if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 return nextMiddleware(factory, errorMiddleware, info) } return res.end() }, current.timeout) } // try to execute the resolver and if unable // move to error middleware. if already in error // middleware end the request try { info.index += 1 current.resolver(req, res, next) } catch (err) { clearTimeout(local.timeout) local.finished = true factory.emit(EVENT_ERROR, err) req.error = err // add the result exec.ended = Date.now() exec.data = req.error if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 return nextMiddleware(factory, errorMiddleware, info) } return res.end() } }
javascript
function nextMiddleware (factory, mw, info) { const { resolved, index, routes, middlewares, errorMiddleware, req, res, metrics } = info const local = { finished: false, timeout: null } // check if the request has already been resolved if (resolved) return // get the current middleware const current = mw[index] const exec = { name: current.functionName, started: Date.now(), ended: null, data: null } metrics.executions.push(exec) // create a next method const next = data => { clearTimeout(local.timeout) if (local.finished || info.resolved) return local.finished = true // add the result exec.ended = Date.now() exec.data = data // allow reroutes to valid named route paths if (_.isString(data)) { const route = routes[data] if (!route) { if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 req.error = new Error(`No route found for "${data}"`) return nextMiddleware(factory, errorMiddleware, info) } res.end(data) } // get the correct route set const mwSet = route.type === ERROR_MIDDLEWARE ? errorMiddleware : middlewares // increment the re-route counter, set the index and go req.reroutes += 1 info.index = route.index return nextMiddleware(factory, mwSet, info) } // check for an error passed to the next method and not // already in the error middleware chain. if condition met // start processing error middleware if (data instanceof Error) { if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 req.error = data return nextMiddleware(factory, errorMiddleware, info) } res.end(data) } // check if there is any more middleware in the chain // if not, call end to complete the request return info.index === mw.length ? res.end() : nextMiddleware(factory, mw, info) } // create a timeout for the middleware if timeout > 0 if (current.timeout > 0) { local.timeout = setTimeout(() => { local.finished = true req.error = new Error(current.functionName + ' middleware timed out') // add the result exec.ended = Date.now() exec.data = req.error // if already in error middleware and timed out // end the entire request, othewise move to error mw if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 return nextMiddleware(factory, errorMiddleware, info) } return res.end() }, current.timeout) } // try to execute the resolver and if unable // move to error middleware. if already in error // middleware end the request try { info.index += 1 current.resolver(req, res, next) } catch (err) { clearTimeout(local.timeout) local.finished = true factory.emit(EVENT_ERROR, err) req.error = err // add the result exec.ended = Date.now() exec.data = req.error if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) { info.index = 0 return nextMiddleware(factory, errorMiddleware, info) } return res.end() } }
[ "function", "nextMiddleware", "(", "factory", ",", "mw", ",", "info", ")", "{", "const", "{", "resolved", ",", "index", ",", "routes", ",", "middlewares", ",", "errorMiddleware", ",", "req", ",", "res", ",", "metrics", "}", "=", "info", "const", "local", "=", "{", "finished", ":", "false", ",", "timeout", ":", "null", "}", "// check if the request has already been resolved", "if", "(", "resolved", ")", "return", "// get the current middleware", "const", "current", "=", "mw", "[", "index", "]", "const", "exec", "=", "{", "name", ":", "current", ".", "functionName", ",", "started", ":", "Date", ".", "now", "(", ")", ",", "ended", ":", "null", ",", "data", ":", "null", "}", "metrics", ".", "executions", ".", "push", "(", "exec", ")", "// create a next method", "const", "next", "=", "data", "=>", "{", "clearTimeout", "(", "local", ".", "timeout", ")", "if", "(", "local", ".", "finished", "||", "info", ".", "resolved", ")", "return", "local", ".", "finished", "=", "true", "// add the result", "exec", ".", "ended", "=", "Date", ".", "now", "(", ")", "exec", ".", "data", "=", "data", "// allow reroutes to valid named route paths", "if", "(", "_", ".", "isString", "(", "data", ")", ")", "{", "const", "route", "=", "routes", "[", "data", "]", "if", "(", "!", "route", ")", "{", "if", "(", "current", ".", "type", "!==", "ERROR_MIDDLEWARE", "&&", "errorMiddleware", ".", "length", ")", "{", "info", ".", "index", "=", "0", "req", ".", "error", "=", "new", "Error", "(", "`", "${", "data", "}", "`", ")", "return", "nextMiddleware", "(", "factory", ",", "errorMiddleware", ",", "info", ")", "}", "res", ".", "end", "(", "data", ")", "}", "// get the correct route set", "const", "mwSet", "=", "route", ".", "type", "===", "ERROR_MIDDLEWARE", "?", "errorMiddleware", ":", "middlewares", "// increment the re-route counter, set the index and go", "req", ".", "reroutes", "+=", "1", "info", ".", "index", "=", "route", ".", "index", "return", "nextMiddleware", "(", "factory", ",", "mwSet", ",", "info", ")", "}", "// check for an error passed to the next method and not", "// already in the error middleware chain. if condition met", "// start processing error middleware", "if", "(", "data", "instanceof", "Error", ")", "{", "if", "(", "current", ".", "type", "!==", "ERROR_MIDDLEWARE", "&&", "errorMiddleware", ".", "length", ")", "{", "info", ".", "index", "=", "0", "req", ".", "error", "=", "data", "return", "nextMiddleware", "(", "factory", ",", "errorMiddleware", ",", "info", ")", "}", "res", ".", "end", "(", "data", ")", "}", "// check if there is any more middleware in the chain", "// if not, call end to complete the request", "return", "info", ".", "index", "===", "mw", ".", "length", "?", "res", ".", "end", "(", ")", ":", "nextMiddleware", "(", "factory", ",", "mw", ",", "info", ")", "}", "// create a timeout for the middleware if timeout > 0", "if", "(", "current", ".", "timeout", ">", "0", ")", "{", "local", ".", "timeout", "=", "setTimeout", "(", "(", ")", "=>", "{", "local", ".", "finished", "=", "true", "req", ".", "error", "=", "new", "Error", "(", "current", ".", "functionName", "+", "' middleware timed out'", ")", "// add the result", "exec", ".", "ended", "=", "Date", ".", "now", "(", ")", "exec", ".", "data", "=", "req", ".", "error", "// if already in error middleware and timed out", "// end the entire request, othewise move to error mw", "if", "(", "current", ".", "type", "!==", "ERROR_MIDDLEWARE", "&&", "errorMiddleware", ".", "length", ")", "{", "info", ".", "index", "=", "0", "return", "nextMiddleware", "(", "factory", ",", "errorMiddleware", ",", "info", ")", "}", "return", "res", ".", "end", "(", ")", "}", ",", "current", ".", "timeout", ")", "}", "// try to execute the resolver and if unable", "// move to error middleware. if already in error", "// middleware end the request", "try", "{", "info", ".", "index", "+=", "1", "current", ".", "resolver", "(", "req", ",", "res", ",", "next", ")", "}", "catch", "(", "err", ")", "{", "clearTimeout", "(", "local", ".", "timeout", ")", "local", ".", "finished", "=", "true", "factory", ".", "emit", "(", "EVENT_ERROR", ",", "err", ")", "req", ".", "error", "=", "err", "// add the result", "exec", ".", "ended", "=", "Date", ".", "now", "(", ")", "exec", ".", "data", "=", "req", ".", "error", "if", "(", "current", ".", "type", "!==", "ERROR_MIDDLEWARE", "&&", "errorMiddleware", ".", "length", ")", "{", "info", ".", "index", "=", "0", "return", "nextMiddleware", "(", "factory", ",", "errorMiddleware", ",", "info", ")", "}", "return", "res", ".", "end", "(", ")", "}", "}" ]
Processes the next middleware in the queue @param mw @param info @returns {*}
[ "Processes", "the", "next", "middleware", "in", "the", "queue" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src-concept/generate/middleware.js#L43-L169
40,885
graphql-factory/graphql-factory
archive/v2/example/example.js
function (source, args, context, info) { // console.log(this.utils.getRootFieldDef(info, '_tableName')) let typeName = this.utils.getReturnTypeName(info) let db = this.globals.db.main let config = db.tables[typeName] let cursor = db.cursor return cursor.db(config.db).table(config.table).run() }
javascript
function (source, args, context, info) { // console.log(this.utils.getRootFieldDef(info, '_tableName')) let typeName = this.utils.getReturnTypeName(info) let db = this.globals.db.main let config = db.tables[typeName] let cursor = db.cursor return cursor.db(config.db).table(config.table).run() }
[ "function", "(", "source", ",", "args", ",", "context", ",", "info", ")", "{", "// console.log(this.utils.getRootFieldDef(info, '_tableName'))", "let", "typeName", "=", "this", ".", "utils", ".", "getReturnTypeName", "(", "info", ")", "let", "db", "=", "this", ".", "globals", ".", "db", ".", "main", "let", "config", "=", "db", ".", "tables", "[", "typeName", "]", "let", "cursor", "=", "db", ".", "cursor", "return", "cursor", ".", "db", "(", "config", ".", "db", ")", ".", "table", "(", "config", ".", "table", ")", ".", "run", "(", ")", "}" ]
get user list
[ "get", "user", "list" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/v2/example/example.js#L42-L51
40,886
dundalek/warehouse
backend/fs.js
function() { var self = this; return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name)) .then(function(files) { return Q.all(files.map(function(f) { return self.delete(f); })); }) .then(function() { return true; }); }
javascript
function() { var self = this; return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name)) .then(function(files) { return Q.all(files.map(function(f) { return self.delete(f); })); }) .then(function() { return true; }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "return", "Q", ".", "ninvoke", "(", "fs", ",", "'readdir'", ",", "path", ".", "join", "(", "this", ".", "backend", ".", "options", ".", "path", ",", "this", ".", "name", ")", ")", ".", "then", "(", "function", "(", "files", ")", "{", "return", "Q", ".", "all", "(", "files", ".", "map", "(", "function", "(", "f", ")", "{", "return", "self", ".", "delete", "(", "f", ")", ";", "}", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "true", ";", "}", ")", ";", "}" ]
Delete all items
[ "Delete", "all", "items" ]
d5a964a5997c28170dc907ad91b80ea3cb049faa
https://github.com/dundalek/warehouse/blob/d5a964a5997c28170dc907ad91b80ea3cb049faa/backend/fs.js#L131-L142
40,887
dundalek/warehouse
backend/fs.js
function(file) { return path.join(this.backend.options.path, this.name, ''+path.basename(file)); }
javascript
function(file) { return path.join(this.backend.options.path, this.name, ''+path.basename(file)); }
[ "function", "(", "file", ")", "{", "return", "path", ".", "join", "(", "this", ".", "backend", ".", "options", ".", "path", ",", "this", ".", "name", ",", "''", "+", "path", ".", "basename", "(", "file", ")", ")", ";", "}" ]
Get absolute filename for given key
[ "Get", "absolute", "filename", "for", "given", "key" ]
d5a964a5997c28170dc907ad91b80ea3cb049faa
https://github.com/dundalek/warehouse/blob/d5a964a5997c28170dc907ad91b80ea3cb049faa/backend/fs.js#L145-L147
40,888
graphql-factory/graphql-factory
src-old/definition/definition.js
filterStore
function filterStore(operation, store, args) { const filter = obj => { switch (operation) { case 'omit': return _.isFunction(args[0]) ? _.omitBy(obj, args[0]) : _.omit(obj, args); case 'pick': return _.isFunction(args[0]) ? _.pickBy(obj, args[0]) : _.pick(obj, args); default: break; } }; switch (store) { case 'context': case 'functions': case 'directives': case 'plugins': case 'types': _.set(this, `_${store}`, filter(_.get(this, `_${store}`))); break; default: assert(false, `invalid store for ${operation} operation`); break; } return this; }
javascript
function filterStore(operation, store, args) { const filter = obj => { switch (operation) { case 'omit': return _.isFunction(args[0]) ? _.omitBy(obj, args[0]) : _.omit(obj, args); case 'pick': return _.isFunction(args[0]) ? _.pickBy(obj, args[0]) : _.pick(obj, args); default: break; } }; switch (store) { case 'context': case 'functions': case 'directives': case 'plugins': case 'types': _.set(this, `_${store}`, filter(_.get(this, `_${store}`))); break; default: assert(false, `invalid store for ${operation} operation`); break; } return this; }
[ "function", "filterStore", "(", "operation", ",", "store", ",", "args", ")", "{", "const", "filter", "=", "obj", "=>", "{", "switch", "(", "operation", ")", "{", "case", "'omit'", ":", "return", "_", ".", "isFunction", "(", "args", "[", "0", "]", ")", "?", "_", ".", "omitBy", "(", "obj", ",", "args", "[", "0", "]", ")", ":", "_", ".", "omit", "(", "obj", ",", "args", ")", ";", "case", "'pick'", ":", "return", "_", ".", "isFunction", "(", "args", "[", "0", "]", ")", "?", "_", ".", "pickBy", "(", "obj", ",", "args", "[", "0", "]", ")", ":", "_", ".", "pick", "(", "obj", ",", "args", ")", ";", "default", ":", "break", ";", "}", "}", ";", "switch", "(", "store", ")", "{", "case", "'context'", ":", "case", "'functions'", ":", "case", "'directives'", ":", "case", "'plugins'", ":", "case", "'types'", ":", "_", ".", "set", "(", "this", ",", "`", "${", "store", "}", "`", ",", "filter", "(", "_", ".", "get", "(", "this", ",", "`", "${", "store", "}", "`", ")", ")", ")", ";", "break", ";", "default", ":", "assert", "(", "false", ",", "`", "${", "operation", "}", "`", ")", ";", "break", ";", "}", "return", "this", ";", "}" ]
performs a filter operation on a specified store @param {*} operation @param {*} store @param {*} args
[ "performs", "a", "filter", "operation", "on", "a", "specified", "store" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/definition/definition.js#L91-L119
40,889
graphql-factory/graphql-factory
archive/refactoring/definition/merge.js
defaultConflictResolution
function defaultConflictResolution(definition, name, type, tgt, src) { // TODO: Add support for type/field level conflict settings // TODO: Add support for extending types via extend key switch(type) { case 'type': const { query, mutation, subscription } = get(definition, [ 'schema' ]) || {}; // always merge a rootTypes definition if ([ query, mutation, subscription].indexOf(name) !== -1) { return { name, config: merge(tgt, src) }; } break; case 'function': return { name, config: Object.assign(tgt, src) }; case 'context': return { name, config: merge(tgt, src) }; default: break; } // emit a warning definition.emit(FactoryEvent.WARN, 'MergeConflict: Duplicate ' + type + ' with name "' + name + '" found. Using newer value'); return { name, config: tgt }; }
javascript
function defaultConflictResolution(definition, name, type, tgt, src) { // TODO: Add support for type/field level conflict settings // TODO: Add support for extending types via extend key switch(type) { case 'type': const { query, mutation, subscription } = get(definition, [ 'schema' ]) || {}; // always merge a rootTypes definition if ([ query, mutation, subscription].indexOf(name) !== -1) { return { name, config: merge(tgt, src) }; } break; case 'function': return { name, config: Object.assign(tgt, src) }; case 'context': return { name, config: merge(tgt, src) }; default: break; } // emit a warning definition.emit(FactoryEvent.WARN, 'MergeConflict: Duplicate ' + type + ' with name "' + name + '" found. Using newer value'); return { name, config: tgt }; }
[ "function", "defaultConflictResolution", "(", "definition", ",", "name", ",", "type", ",", "tgt", ",", "src", ")", "{", "// TODO: Add support for type/field level conflict settings", "// TODO: Add support for extending types via extend key", "switch", "(", "type", ")", "{", "case", "'type'", ":", "const", "{", "query", ",", "mutation", ",", "subscription", "}", "=", "get", "(", "definition", ",", "[", "'schema'", "]", ")", "||", "{", "}", ";", "// always merge a rootTypes definition", "if", "(", "[", "query", ",", "mutation", ",", "subscription", "]", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "return", "{", "name", ",", "config", ":", "merge", "(", "tgt", ",", "src", ")", "}", ";", "}", "break", ";", "case", "'function'", ":", "return", "{", "name", ",", "config", ":", "Object", ".", "assign", "(", "tgt", ",", "src", ")", "}", ";", "case", "'context'", ":", "return", "{", "name", ",", "config", ":", "merge", "(", "tgt", ",", "src", ")", "}", ";", "default", ":", "break", ";", "}", "// emit a warning", "definition", ".", "emit", "(", "FactoryEvent", ".", "WARN", ",", "'MergeConflict: Duplicate '", "+", "type", "+", "' with name \"'", "+", "name", "+", "'\" found. Using newer value'", ")", ";", "return", "{", "name", ",", "config", ":", "tgt", "}", ";", "}" ]
Default conflict resolver for merging root types, context, and overwriting parts of type definitions @param {*} definition @param {*} name @param {*} type @param {*} tgt @param {*} src
[ "Default", "conflict", "resolver", "for", "merging", "root", "types", "context", "and", "overwriting", "parts", "of", "type", "definitions" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/refactoring/definition/merge.js#L32-L58
40,890
graphql-factory/graphql-factory
archive/refactoring/definition/merge.js
handleConflict
function handleConflict(definition, method, name, type, tgt, src) { const _method = method ? method : defaultConflictResolution; // allow the method to be a function that returns the new name // and type configuration if (typeof _method === 'function') { return _method(definition, name, type, tgt, src); } switch (_method) { // merges the target and source configurations case NameConflictResolution.MERGE: return { name, config: merge(tgt, src) }; // throws an error case NameConflictResolution.ERROR: throw new Error('Duplicate ' + type + ' name "' + name + '" is not allowed ' + 'when conflict is set to ' + NameConflictResolution.ERROR); // prints a warning and then overwrites the existing type definition case NameConflictResolution.WARN: definition.emit(FactoryEvent.WARN, 'GraphQLFactoryWarning: duplicate ' + 'type name "' + name + '" found. Merging ' + type + ' configuration') return { name, config: merge(tgt, src) }; // ignores the definition case NameConflictResolution.SKIP: return { name, config: tgt }; // silently overwrites the value case NameConflictResolution.OVERWRITE: return { name, config: src }; default: throw new Error('Invalid name conflict resolution'); } }
javascript
function handleConflict(definition, method, name, type, tgt, src) { const _method = method ? method : defaultConflictResolution; // allow the method to be a function that returns the new name // and type configuration if (typeof _method === 'function') { return _method(definition, name, type, tgt, src); } switch (_method) { // merges the target and source configurations case NameConflictResolution.MERGE: return { name, config: merge(tgt, src) }; // throws an error case NameConflictResolution.ERROR: throw new Error('Duplicate ' + type + ' name "' + name + '" is not allowed ' + 'when conflict is set to ' + NameConflictResolution.ERROR); // prints a warning and then overwrites the existing type definition case NameConflictResolution.WARN: definition.emit(FactoryEvent.WARN, 'GraphQLFactoryWarning: duplicate ' + 'type name "' + name + '" found. Merging ' + type + ' configuration') return { name, config: merge(tgt, src) }; // ignores the definition case NameConflictResolution.SKIP: return { name, config: tgt }; // silently overwrites the value case NameConflictResolution.OVERWRITE: return { name, config: src }; default: throw new Error('Invalid name conflict resolution'); } }
[ "function", "handleConflict", "(", "definition", ",", "method", ",", "name", ",", "type", ",", "tgt", ",", "src", ")", "{", "const", "_method", "=", "method", "?", "method", ":", "defaultConflictResolution", ";", "// allow the method to be a function that returns the new name", "// and type configuration", "if", "(", "typeof", "_method", "===", "'function'", ")", "{", "return", "_method", "(", "definition", ",", "name", ",", "type", ",", "tgt", ",", "src", ")", ";", "}", "switch", "(", "_method", ")", "{", "// merges the target and source configurations", "case", "NameConflictResolution", ".", "MERGE", ":", "return", "{", "name", ",", "config", ":", "merge", "(", "tgt", ",", "src", ")", "}", ";", "// throws an error", "case", "NameConflictResolution", ".", "ERROR", ":", "throw", "new", "Error", "(", "'Duplicate '", "+", "type", "+", "' name \"'", "+", "name", "+", "'\" is not allowed '", "+", "'when conflict is set to '", "+", "NameConflictResolution", ".", "ERROR", ")", ";", "// prints a warning and then overwrites the existing type definition", "case", "NameConflictResolution", ".", "WARN", ":", "definition", ".", "emit", "(", "FactoryEvent", ".", "WARN", ",", "'GraphQLFactoryWarning: duplicate '", "+", "'type name \"'", "+", "name", "+", "'\" found. Merging '", "+", "type", "+", "' configuration'", ")", "return", "{", "name", ",", "config", ":", "merge", "(", "tgt", ",", "src", ")", "}", ";", "// ignores the definition", "case", "NameConflictResolution", ".", "SKIP", ":", "return", "{", "name", ",", "config", ":", "tgt", "}", ";", "// silently overwrites the value", "case", "NameConflictResolution", ".", "OVERWRITE", ":", "return", "{", "name", ",", "config", ":", "src", "}", ";", "default", ":", "throw", "new", "Error", "(", "'Invalid name conflict resolution'", ")", ";", "}", "}" ]
Handles a type name conflict returns an object containing the type name to use and the type configuration to use. @param {*} method @param {*} name @param {*} prefix
[ "Handles", "a", "type", "name", "conflict", "returns", "an", "object", "containing", "the", "type", "name", "to", "use", "and", "the", "type", "configuration", "to", "use", "." ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/refactoring/definition/merge.js#L68-L107
40,891
jrmerz/leaflet-canvas-geojson
src/defaultRenderer/index.js
render
function render(context, xyPoints, map, canvasFeature) { ctx = context; if( canvasFeature.type === 'Point' ) { renderPoint(xyPoints, this.size); } else if( canvasFeature.type === 'LineString' ) { renderLine(xyPoints); } else if( canvasFeature.type === 'Polygon' ) { renderPolygon(xyPoints); } else if( canvasFeature.type === 'MultiPolygon' ) { xyPoints.forEach(renderPolygon); } }
javascript
function render(context, xyPoints, map, canvasFeature) { ctx = context; if( canvasFeature.type === 'Point' ) { renderPoint(xyPoints, this.size); } else if( canvasFeature.type === 'LineString' ) { renderLine(xyPoints); } else if( canvasFeature.type === 'Polygon' ) { renderPolygon(xyPoints); } else if( canvasFeature.type === 'MultiPolygon' ) { xyPoints.forEach(renderPolygon); } }
[ "function", "render", "(", "context", ",", "xyPoints", ",", "map", ",", "canvasFeature", ")", "{", "ctx", "=", "context", ";", "if", "(", "canvasFeature", ".", "type", "===", "'Point'", ")", "{", "renderPoint", "(", "xyPoints", ",", "this", ".", "size", ")", ";", "}", "else", "if", "(", "canvasFeature", ".", "type", "===", "'LineString'", ")", "{", "renderLine", "(", "xyPoints", ")", ";", "}", "else", "if", "(", "canvasFeature", ".", "type", "===", "'Polygon'", ")", "{", "renderPolygon", "(", "xyPoints", ")", ";", "}", "else", "if", "(", "canvasFeature", ".", "type", "===", "'MultiPolygon'", ")", "{", "xyPoints", ".", "forEach", "(", "renderPolygon", ")", ";", "}", "}" ]
Fuction called in scope of CanvasFeature
[ "Fuction", "called", "in", "scope", "of", "CanvasFeature" ]
39ccf82d6ee89684b3f5c826c013210dad954d8f
https://github.com/jrmerz/leaflet-canvas-geojson/blob/39ccf82d6ee89684b3f5c826c013210dad954d8f/src/defaultRenderer/index.js#L6-L18
40,892
jrmerz/leaflet-canvas-geojson
src/lib/intersects.js
intersects
function intersects(e) { if( !this.showing ) return; var dpp = this.getDegreesPerPx(e.latlng); var mpp = this.getMetersPerPx(e.latlng); var r = mpp * 5; // 5 px radius buffer; var center = { type : 'Point', coordinates : [e.latlng.lng, e.latlng.lat] }; var containerPoint = e.containerPoint; var x1 = e.latlng.lng - dpp; var x2 = e.latlng.lng + dpp; var y1 = e.latlng.lat - dpp; var y2 = e.latlng.lat + dpp; var intersects = this.intersectsBbox([[x1, y1], [x2, y2]], r, center, containerPoint); onIntersectsListCreated.call(this, e, intersects); }
javascript
function intersects(e) { if( !this.showing ) return; var dpp = this.getDegreesPerPx(e.latlng); var mpp = this.getMetersPerPx(e.latlng); var r = mpp * 5; // 5 px radius buffer; var center = { type : 'Point', coordinates : [e.latlng.lng, e.latlng.lat] }; var containerPoint = e.containerPoint; var x1 = e.latlng.lng - dpp; var x2 = e.latlng.lng + dpp; var y1 = e.latlng.lat - dpp; var y2 = e.latlng.lat + dpp; var intersects = this.intersectsBbox([[x1, y1], [x2, y2]], r, center, containerPoint); onIntersectsListCreated.call(this, e, intersects); }
[ "function", "intersects", "(", "e", ")", "{", "if", "(", "!", "this", ".", "showing", ")", "return", ";", "var", "dpp", "=", "this", ".", "getDegreesPerPx", "(", "e", ".", "latlng", ")", ";", "var", "mpp", "=", "this", ".", "getMetersPerPx", "(", "e", ".", "latlng", ")", ";", "var", "r", "=", "mpp", "*", "5", ";", "// 5 px radius buffer;", "var", "center", "=", "{", "type", ":", "'Point'", ",", "coordinates", ":", "[", "e", ".", "latlng", ".", "lng", ",", "e", ".", "latlng", ".", "lat", "]", "}", ";", "var", "containerPoint", "=", "e", ".", "containerPoint", ";", "var", "x1", "=", "e", ".", "latlng", ".", "lng", "-", "dpp", ";", "var", "x2", "=", "e", ".", "latlng", ".", "lng", "+", "dpp", ";", "var", "y1", "=", "e", ".", "latlng", ".", "lat", "-", "dpp", ";", "var", "y2", "=", "e", ".", "latlng", ".", "lat", "+", "dpp", ";", "var", "intersects", "=", "this", ".", "intersectsBbox", "(", "[", "[", "x1", ",", "y1", "]", ",", "[", "x2", ",", "y2", "]", "]", ",", "r", ",", "center", ",", "containerPoint", ")", ";", "onIntersectsListCreated", ".", "call", "(", "this", ",", "e", ",", "intersects", ")", ";", "}" ]
Handle mouse intersection events e - leaflet event
[ "Handle", "mouse", "intersection", "events", "e", "-", "leaflet", "event" ]
39ccf82d6ee89684b3f5c826c013210dad954d8f
https://github.com/jrmerz/leaflet-canvas-geojson/blob/39ccf82d6ee89684b3f5c826c013210dad954d8f/src/lib/intersects.js#L8-L31
40,893
graphql-factory/graphql-factory
src-old/utilities/http.js
processBody
function processBody(opts, body) { if (body === undefined) { return ''; } const handlers = Object.assign({}, serializers, opts.serializers); const headers = typeof opts.headers === 'object' ? opts.headers : {}; const contentType = Object.keys(headers).reduce((type, header) => { if (typeof type === 'string') { return type; } if ( header.match(/^content-type$/i) && typeof headers[header] === 'string' ) { return headers[header].toLowerCase(); } return type; }, undefined); const handler = handlers[contentType]; if (typeof handler === 'function') { return String(handler(body)); } if (typeof body === 'object') { return JSON.stringify(body); } return String(body); }
javascript
function processBody(opts, body) { if (body === undefined) { return ''; } const handlers = Object.assign({}, serializers, opts.serializers); const headers = typeof opts.headers === 'object' ? opts.headers : {}; const contentType = Object.keys(headers).reduce((type, header) => { if (typeof type === 'string') { return type; } if ( header.match(/^content-type$/i) && typeof headers[header] === 'string' ) { return headers[header].toLowerCase(); } return type; }, undefined); const handler = handlers[contentType]; if (typeof handler === 'function') { return String(handler(body)); } if (typeof body === 'object') { return JSON.stringify(body); } return String(body); }
[ "function", "processBody", "(", "opts", ",", "body", ")", "{", "if", "(", "body", "===", "undefined", ")", "{", "return", "''", ";", "}", "const", "handlers", "=", "Object", ".", "assign", "(", "{", "}", ",", "serializers", ",", "opts", ".", "serializers", ")", ";", "const", "headers", "=", "typeof", "opts", ".", "headers", "===", "'object'", "?", "opts", ".", "headers", ":", "{", "}", ";", "const", "contentType", "=", "Object", ".", "keys", "(", "headers", ")", ".", "reduce", "(", "(", "type", ",", "header", ")", "=>", "{", "if", "(", "typeof", "type", "===", "'string'", ")", "{", "return", "type", ";", "}", "if", "(", "header", ".", "match", "(", "/", "^content-type$", "/", "i", ")", "&&", "typeof", "headers", "[", "header", "]", "===", "'string'", ")", "{", "return", "headers", "[", "header", "]", ".", "toLowerCase", "(", ")", ";", "}", "return", "type", ";", "}", ",", "undefined", ")", ";", "const", "handler", "=", "handlers", "[", "contentType", "]", ";", "if", "(", "typeof", "handler", "===", "'function'", ")", "{", "return", "String", "(", "handler", "(", "body", ")", ")", ";", "}", "if", "(", "typeof", "body", "===", "'object'", ")", "{", "return", "JSON", ".", "stringify", "(", "body", ")", ";", "}", "return", "String", "(", "body", ")", ";", "}" ]
Converts the body value to a string using optional serializers @param {*} opts @param {*} body
[ "Converts", "the", "body", "value", "to", "a", "string", "using", "optional", "serializers" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/utilities/http.js#L35-L63
40,894
graphql-factory/graphql-factory
src-old/utilities/http.js
processData
function processData(res, data, options) { const handlers = Object.assign({}, deserializers, options.deserializers); const contentType = res.headers['content-type']; const types = typeof contentType === 'string' ? contentType.split(';') : []; // if there are no content types, return the data unmodified if (!types.length) { return data; } return types.reduce((d, type) => { try { const t = type.toLocaleLowerCase().trim(); const handler = handlers[t]; if (d instanceof Error || typeof handler !== 'function') { return d; } return handler(d); } catch (error) { return error; } }, data); }
javascript
function processData(res, data, options) { const handlers = Object.assign({}, deserializers, options.deserializers); const contentType = res.headers['content-type']; const types = typeof contentType === 'string' ? contentType.split(';') : []; // if there are no content types, return the data unmodified if (!types.length) { return data; } return types.reduce((d, type) => { try { const t = type.toLocaleLowerCase().trim(); const handler = handlers[t]; if (d instanceof Error || typeof handler !== 'function') { return d; } return handler(d); } catch (error) { return error; } }, data); }
[ "function", "processData", "(", "res", ",", "data", ",", "options", ")", "{", "const", "handlers", "=", "Object", ".", "assign", "(", "{", "}", ",", "deserializers", ",", "options", ".", "deserializers", ")", ";", "const", "contentType", "=", "res", ".", "headers", "[", "'content-type'", "]", ";", "const", "types", "=", "typeof", "contentType", "===", "'string'", "?", "contentType", ".", "split", "(", "';'", ")", ":", "[", "]", ";", "// if there are no content types, return the data unmodified", "if", "(", "!", "types", ".", "length", ")", "{", "return", "data", ";", "}", "return", "types", ".", "reduce", "(", "(", "d", ",", "type", ")", "=>", "{", "try", "{", "const", "t", "=", "type", ".", "toLocaleLowerCase", "(", ")", ".", "trim", "(", ")", ";", "const", "handler", "=", "handlers", "[", "t", "]", ";", "if", "(", "d", "instanceof", "Error", "||", "typeof", "handler", "!==", "'function'", ")", "{", "return", "d", ";", "}", "return", "handler", "(", "d", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "}", ",", "data", ")", ";", "}" ]
Processes the response data based on content type using optional deserializers @param {*} res @param {*} data @param {*} options
[ "Processes", "the", "response", "data", "based", "on", "content", "type", "using", "optional", "deserializers" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/utilities/http.js#L72-L95
40,895
graphql-factory/graphql-factory
scratch/mongo-plugin.js
mongoType
function mongoType( typeStr, options ) { const required = typeStr.match(/^(\S+)!$/); const list = typeStr.match(/^\[(\S+)]$/); if (required) { const innerType = required[1]; if (_.includes(SCALARS, innerType)) { options.required = true; } return mongoType(innerType); } else if (list) { return [ mongoType(list[1]) ]; } switch (typeStr) { case 'String': return String; case 'Int': case 'Float': return Number; case 'Boolean': return Boolean; case 'DateTime': return Date; case 'ID': return mongoose.Schema.Types.ObjectId; case 'JSON': return mongoose.Schema.Types.Mixed; default: throw new Error(typeStr); } }
javascript
function mongoType( typeStr, options ) { const required = typeStr.match(/^(\S+)!$/); const list = typeStr.match(/^\[(\S+)]$/); if (required) { const innerType = required[1]; if (_.includes(SCALARS, innerType)) { options.required = true; } return mongoType(innerType); } else if (list) { return [ mongoType(list[1]) ]; } switch (typeStr) { case 'String': return String; case 'Int': case 'Float': return Number; case 'Boolean': return Boolean; case 'DateTime': return Date; case 'ID': return mongoose.Schema.Types.ObjectId; case 'JSON': return mongoose.Schema.Types.Mixed; default: throw new Error(typeStr); } }
[ "function", "mongoType", "(", "typeStr", ",", "options", ")", "{", "const", "required", "=", "typeStr", ".", "match", "(", "/", "^(\\S+)!$", "/", ")", ";", "const", "list", "=", "typeStr", ".", "match", "(", "/", "^\\[(\\S+)]$", "/", ")", ";", "if", "(", "required", ")", "{", "const", "innerType", "=", "required", "[", "1", "]", ";", "if", "(", "_", ".", "includes", "(", "SCALARS", ",", "innerType", ")", ")", "{", "options", ".", "required", "=", "true", ";", "}", "return", "mongoType", "(", "innerType", ")", ";", "}", "else", "if", "(", "list", ")", "{", "return", "[", "mongoType", "(", "list", "[", "1", "]", ")", "]", ";", "}", "switch", "(", "typeStr", ")", "{", "case", "'String'", ":", "return", "String", ";", "case", "'Int'", ":", "case", "'Float'", ":", "return", "Number", ";", "case", "'Boolean'", ":", "return", "Boolean", ";", "case", "'DateTime'", ":", "return", "Date", ";", "case", "'ID'", ":", "return", "mongoose", ".", "Schema", ".", "Types", ".", "ObjectId", ";", "case", "'JSON'", ":", "return", "mongoose", ".", "Schema", ".", "Types", ".", "Mixed", ";", "default", ":", "throw", "new", "Error", "(", "typeStr", ")", ";", "}", "}" ]
Translates a graphql scalar type to a valid mongoose type @param {*} typeStr @param {*} options
[ "Translates", "a", "graphql", "scalar", "type", "to", "a", "valid", "mongoose", "type" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/scratch/mongo-plugin.js#L31-L64
40,896
graphql-factory/graphql-factory
archive/v2/src/GraphQLFactoryDecomposer.js
getTypeInfo
function getTypeInfo (obj, info) { const constructorName = _.constructorName(obj) const _info = info || { type: null, name: null, isList: false, isNonNull: false } switch (constructorName) { case 'GraphQLNonNull': _info.isNonNull = true return getTypeInfo(obj.ofType, _info) case 'GraphQLList': _info.isList = true return getTypeInfo(obj.ofType, _info) default: _info.type = obj _info.name = obj.name } return _info }
javascript
function getTypeInfo (obj, info) { const constructorName = _.constructorName(obj) const _info = info || { type: null, name: null, isList: false, isNonNull: false } switch (constructorName) { case 'GraphQLNonNull': _info.isNonNull = true return getTypeInfo(obj.ofType, _info) case 'GraphQLList': _info.isList = true return getTypeInfo(obj.ofType, _info) default: _info.type = obj _info.name = obj.name } return _info }
[ "function", "getTypeInfo", "(", "obj", ",", "info", ")", "{", "const", "constructorName", "=", "_", ".", "constructorName", "(", "obj", ")", "const", "_info", "=", "info", "||", "{", "type", ":", "null", ",", "name", ":", "null", ",", "isList", ":", "false", ",", "isNonNull", ":", "false", "}", "switch", "(", "constructorName", ")", "{", "case", "'GraphQLNonNull'", ":", "_info", ".", "isNonNull", "=", "true", "return", "getTypeInfo", "(", "obj", ".", "ofType", ",", "_info", ")", "case", "'GraphQLList'", ":", "_info", ".", "isList", "=", "true", "return", "getTypeInfo", "(", "obj", ".", "ofType", ",", "_info", ")", "default", ":", "_info", ".", "type", "=", "obj", "_info", ".", "name", "=", "obj", ".", "name", "}", "return", "_info", "}" ]
Strips away nonnull and list objects to build an info object containing the type @param obj @param info @returns {*}
[ "Strips", "away", "nonnull", "and", "list", "objects", "to", "build", "an", "info", "object", "containing", "the", "type" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/v2/src/GraphQLFactoryDecomposer.js#L11-L32
40,897
graphql-factory/graphql-factory
archive/v2/src/GraphQLFactoryDecomposer.js
baseDef
function baseDef (info) { const { name, isList, isNonNull } = info const def = { type: isList ? [ name ] : name } if (isNonNull) def.nullable = false return def }
javascript
function baseDef (info) { const { name, isList, isNonNull } = info const def = { type: isList ? [ name ] : name } if (isNonNull) def.nullable = false return def }
[ "function", "baseDef", "(", "info", ")", "{", "const", "{", "name", ",", "isList", ",", "isNonNull", "}", "=", "info", "const", "def", "=", "{", "type", ":", "isList", "?", "[", "name", "]", ":", "name", "}", "if", "(", "isNonNull", ")", "def", ".", "nullable", "=", "false", "return", "def", "}" ]
creates a base def object @param info @returns {{type: [null]}}
[ "creates", "a", "base", "def", "object" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/v2/src/GraphQLFactoryDecomposer.js#L39-L46
40,898
graphql-factory/graphql-factory
src-old/utilities/request.js
resolveBuild
function resolveBuild(schema) { const build = _.get(schema, 'definition._build'); return isPromise(build) ? build : Promise.resolve(); }
javascript
function resolveBuild(schema) { const build = _.get(schema, 'definition._build'); return isPromise(build) ? build : Promise.resolve(); }
[ "function", "resolveBuild", "(", "schema", ")", "{", "const", "build", "=", "_", ".", "get", "(", "schema", ",", "'definition._build'", ")", ";", "return", "isPromise", "(", "build", ")", "?", "build", ":", "Promise", ".", "resolve", "(", ")", ";", "}" ]
Resolves the schema definition build before performing the request @param {*} schema
[ "Resolves", "the", "schema", "definition", "build", "before", "performing", "the", "request" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/utilities/request.js#L14-L17
40,899
graphql-factory/graphql-factory
src-old/execution/middleware.js
middleware
function middleware(definition, resolver, options) { const customExecution = options.factoryExecution !== false; const resolve = function(source, args, context, info) { // ensure that context is an object and extend it const ctx = _.isObjectLike(context) ? context : {}; Object.assign(ctx, definition.context); info.definition = definition; return customExecution ? factoryExecute(source, args, ctx, info) : graphqlExecute(source, args, ctx, info); }; // add the resolver as a property on the resolve middleware // function so that when deconstructing the schema the original // resolver is preserved. Also add a flag that identifies this // resolver as factory middleware resolve.__resolver = resolver; resolve.__factoryMiddleware = true; return resolve; }
javascript
function middleware(definition, resolver, options) { const customExecution = options.factoryExecution !== false; const resolve = function(source, args, context, info) { // ensure that context is an object and extend it const ctx = _.isObjectLike(context) ? context : {}; Object.assign(ctx, definition.context); info.definition = definition; return customExecution ? factoryExecute(source, args, ctx, info) : graphqlExecute(source, args, ctx, info); }; // add the resolver as a property on the resolve middleware // function so that when deconstructing the schema the original // resolver is preserved. Also add a flag that identifies this // resolver as factory middleware resolve.__resolver = resolver; resolve.__factoryMiddleware = true; return resolve; }
[ "function", "middleware", "(", "definition", ",", "resolver", ",", "options", ")", "{", "const", "customExecution", "=", "options", ".", "factoryExecution", "!==", "false", ";", "const", "resolve", "=", "function", "(", "source", ",", "args", ",", "context", ",", "info", ")", "{", "// ensure that context is an object and extend it", "const", "ctx", "=", "_", ".", "isObjectLike", "(", "context", ")", "?", "context", ":", "{", "}", ";", "Object", ".", "assign", "(", "ctx", ",", "definition", ".", "context", ")", ";", "info", ".", "definition", "=", "definition", ";", "return", "customExecution", "?", "factoryExecute", "(", "source", ",", "args", ",", "ctx", ",", "info", ")", ":", "graphqlExecute", "(", "source", ",", "args", ",", "ctx", ",", "info", ")", ";", "}", ";", "// add the resolver as a property on the resolve middleware", "// function so that when deconstructing the schema the original", "// resolver is preserved. Also add a flag that identifies this", "// resolver as factory middleware", "resolve", ".", "__resolver", "=", "resolver", ";", "resolve", ".", "__factoryMiddleware", "=", "true", ";", "return", "resolve", ";", "}" ]
Main middleware function that is wrapped around all resolvers in the graphql schema @param {*} source @param {*} args @param {*} context @param {*} info
[ "Main", "middleware", "function", "that", "is", "wrapped", "around", "all", "resolvers", "in", "the", "graphql", "schema" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/execution/middleware.js#L13-L33