id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
41,200
basic-web-components/basic-web-components
packages/demos/bower_components/shadydom/shadydom.min.js
removeChild
function removeChild(node) { if (tree.Logical.getParentNode(node) !== this) { throw Error('The node to be removed is not a child of this node: ' + node); } if (!mixinImpl.removeNode(node)) { // if removing from a shadyRoot, remove form host instead var container = isShadyRoot(this) ? this.host : this; // not guaranteed to physically be in container; e.g. // undistributed nodes. var parent = tree.Composed.getParentNode(node); if (container === parent) { tree.Composed.removeChild(container, node); } } mixinImpl._scheduleObserver(this, null, node); return node; }
javascript
function removeChild(node) { if (tree.Logical.getParentNode(node) !== this) { throw Error('The node to be removed is not a child of this node: ' + node); } if (!mixinImpl.removeNode(node)) { // if removing from a shadyRoot, remove form host instead var container = isShadyRoot(this) ? this.host : this; // not guaranteed to physically be in container; e.g. // undistributed nodes. var parent = tree.Composed.getParentNode(node); if (container === parent) { tree.Composed.removeChild(container, node); } } mixinImpl._scheduleObserver(this, null, node); return node; }
[ "function", "removeChild", "(", "node", ")", "{", "if", "(", "tree", ".", "Logical", ".", "getParentNode", "(", "node", ")", "!==", "this", ")", "{", "throw", "Error", "(", "'The node to be removed is not a child of this node: '", "+", "node", ")", ";", "}", "if", "(", "!", "mixinImpl", ".", "removeNode", "(", "node", ")", ")", "{", "// if removing from a shadyRoot, remove form host instead", "var", "container", "=", "isShadyRoot", "(", "this", ")", "?", "this", ".", "host", ":", "this", ";", "// not guaranteed to physically be in container; e.g.", "// undistributed nodes.", "var", "parent", "=", "tree", ".", "Composed", ".", "getParentNode", "(", "node", ")", ";", "if", "(", "container", "===", "parent", ")", "{", "tree", ".", "Composed", ".", "removeChild", "(", "container", ",", "node", ")", ";", "}", "}", "mixinImpl", ".", "_scheduleObserver", "(", "this", ",", "null", ",", "node", ")", ";", "return", "node", ";", "}" ]
Removes the given `node` from the element's `lightChildren`. This method also performs dom composition.
[ "Removes", "the", "given", "node", "from", "the", "element", "s", "lightChildren", ".", "This", "method", "also", "performs", "dom", "composition", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L2059-L2078
41,201
catamphetamine/web-service
source/middleware/authentication.js
get_jwt_token
function get_jwt_token(ctx) { // Parses "Authorization: Bearer ${token}" if (ctx.header.authorization) { const match = ctx.header.authorization.match(/^Bearer (.+)$/i) if (match) { return match[1] } } // (doesn't read cookies anymore to protect users from CSRF attacks) // // Tries the "authentication" cookie // if (ctx.cookies.get('authentication')) // { // return ctx.cookies.get('authentication') // } }
javascript
function get_jwt_token(ctx) { // Parses "Authorization: Bearer ${token}" if (ctx.header.authorization) { const match = ctx.header.authorization.match(/^Bearer (.+)$/i) if (match) { return match[1] } } // (doesn't read cookies anymore to protect users from CSRF attacks) // // Tries the "authentication" cookie // if (ctx.cookies.get('authentication')) // { // return ctx.cookies.get('authentication') // } }
[ "function", "get_jwt_token", "(", "ctx", ")", "{", "// Parses \"Authorization: Bearer ${token}\"", "if", "(", "ctx", ".", "header", ".", "authorization", ")", "{", "const", "match", "=", "ctx", ".", "header", ".", "authorization", ".", "match", "(", "/", "^Bearer (.+)$", "/", "i", ")", "if", "(", "match", ")", "{", "return", "match", "[", "1", "]", "}", "}", "// (doesn't read cookies anymore to protect users from CSRF attacks)", "// // Tries the \"authentication\" cookie", "// if (ctx.cookies.get('authentication'))", "// {", "// \treturn ctx.cookies.get('authentication')", "// }", "}" ]
Looks for JWT token inside HTTP Authorization header
[ "Looks", "for", "JWT", "token", "inside", "HTTP", "Authorization", "header" ]
e1eabaaf76bd109a2b2c48ad617ebdd9111409a1
https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/authentication.js#L6-L25
41,202
catamphetamine/web-service
source/middleware/authentication.js
authenticate
async function authenticate({ options, keys, log }) { // A little helper which can be called from routes // as `ctx.role('administrator')` // which will throw if the user isn't administrator. // The `roles` are taken from JWT payload. this.role = (...roles) => { if (!this.user) { throw new errors.Unauthenticated() } for (const role of roles) { for (const user_role of this.user.roles) { if (user_role === role) { return true } } } throw new errors.Unauthorized(`One of the following roles is required: ${roles}`) } // Get JWT token from incoming HTTP request let token = get_jwt_token(this) // If no JWT token was found, then done if (!token) { return } // JWT token (is now accessible from Koa's `ctx`) this.accessToken = token // Verify JWT token integrity // by checking its signature using the supplied `keys` let payload for (const secret of keys) { try { payload = jwt.verify(token, secret) break } catch (error) { // If authentication token expired if (error.name === 'TokenExpiredError') { if (options.refreshAccessToken) { // If refreshing an access token fails // then don't prevent the user from at least seeing a page // therefore catching an error here. try { token = await options.refreshAccessToken(this) } catch (error) { log.error(error) } if (token) { for (const secret of keys) { try { payload = jwt.verify(token, secret) break } catch (error) { // Try another `secret` if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature') { continue } // Some other non-JWT-related error log.error(error) break } } } } if (payload) { break } throw new errors.Access_token_expired() } // Try another `secret` if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature') { continue } // Some other non-JWT-related error. // Shouldn't prevent the user from at least seeing a page // therefore not rethrowing this error. log.error(error) break } } // If JWT token signature was unable to be verified, then exit if (!payload) { return } // If the access token isn't valid for access to this server // (e.g. it's a "refresh token") then exit. if (options.validateAccessToken) { if (!options.validateAccessToken(payload, this)) { return } } // Token payload can be accessed through `ctx` this.accessTokenPayload = payload // Fire "on user request" hook if (options.onUserRequest) { options.onUserRequest(token, this) } // JWT token ID const jwt_id = payload.jti // `subject` // (which is a user id) const user_id = payload.sub // // Optional JWT token validation (by id) // // (for example, that it has not been revoked) // if (validateToken) // { // // Can validate the token via a request to a database, for example. // // Checks for `valid` property value inside the result object. // // (There can possibly be other properties such as `reason`) // const is_valid = (await validateToken(token, this)).valid // // // If the JWT token happens to be invalid // // (expired or revoked, for example), then exit. // if (!is_valid) // { // // this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked') // return // } // } // JWT token ID is now accessible via Koa's `ctx` this.accessTokenId = jwt_id // Extracts user data (description) from JWT token payload // (`user` is now accessible via Koa's `ctx`) this.user = options.userInfo ? options.userInfo(payload) : {} // Sets user id this.user.id = user_id // Extra payload fields: // // 'iss' // Issuer // 'sub' // Subject // 'aud' // Audience // 'exp' // Expiration time // 'nbf' // Not before // 'iat' // Issued at // 'jti' // JWT ID // JWT token payload is accessible via Koa's `ctx` this.accessTokenPayload = payload }
javascript
async function authenticate({ options, keys, log }) { // A little helper which can be called from routes // as `ctx.role('administrator')` // which will throw if the user isn't administrator. // The `roles` are taken from JWT payload. this.role = (...roles) => { if (!this.user) { throw new errors.Unauthenticated() } for (const role of roles) { for (const user_role of this.user.roles) { if (user_role === role) { return true } } } throw new errors.Unauthorized(`One of the following roles is required: ${roles}`) } // Get JWT token from incoming HTTP request let token = get_jwt_token(this) // If no JWT token was found, then done if (!token) { return } // JWT token (is now accessible from Koa's `ctx`) this.accessToken = token // Verify JWT token integrity // by checking its signature using the supplied `keys` let payload for (const secret of keys) { try { payload = jwt.verify(token, secret) break } catch (error) { // If authentication token expired if (error.name === 'TokenExpiredError') { if (options.refreshAccessToken) { // If refreshing an access token fails // then don't prevent the user from at least seeing a page // therefore catching an error here. try { token = await options.refreshAccessToken(this) } catch (error) { log.error(error) } if (token) { for (const secret of keys) { try { payload = jwt.verify(token, secret) break } catch (error) { // Try another `secret` if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature') { continue } // Some other non-JWT-related error log.error(error) break } } } } if (payload) { break } throw new errors.Access_token_expired() } // Try another `secret` if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature') { continue } // Some other non-JWT-related error. // Shouldn't prevent the user from at least seeing a page // therefore not rethrowing this error. log.error(error) break } } // If JWT token signature was unable to be verified, then exit if (!payload) { return } // If the access token isn't valid for access to this server // (e.g. it's a "refresh token") then exit. if (options.validateAccessToken) { if (!options.validateAccessToken(payload, this)) { return } } // Token payload can be accessed through `ctx` this.accessTokenPayload = payload // Fire "on user request" hook if (options.onUserRequest) { options.onUserRequest(token, this) } // JWT token ID const jwt_id = payload.jti // `subject` // (which is a user id) const user_id = payload.sub // // Optional JWT token validation (by id) // // (for example, that it has not been revoked) // if (validateToken) // { // // Can validate the token via a request to a database, for example. // // Checks for `valid` property value inside the result object. // // (There can possibly be other properties such as `reason`) // const is_valid = (await validateToken(token, this)).valid // // // If the JWT token happens to be invalid // // (expired or revoked, for example), then exit. // if (!is_valid) // { // // this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked') // return // } // } // JWT token ID is now accessible via Koa's `ctx` this.accessTokenId = jwt_id // Extracts user data (description) from JWT token payload // (`user` is now accessible via Koa's `ctx`) this.user = options.userInfo ? options.userInfo(payload) : {} // Sets user id this.user.id = user_id // Extra payload fields: // // 'iss' // Issuer // 'sub' // Subject // 'aud' // Audience // 'exp' // Expiration time // 'nbf' // Not before // 'iat' // Issued at // 'jti' // JWT ID // JWT token payload is accessible via Koa's `ctx` this.accessTokenPayload = payload }
[ "async", "function", "authenticate", "(", "{", "options", ",", "keys", ",", "log", "}", ")", "{", "// A little helper which can be called from routes", "// as `ctx.role('administrator')`", "// which will throw if the user isn't administrator.", "// The `roles` are taken from JWT payload.", "this", ".", "role", "=", "(", "...", "roles", ")", "=>", "{", "if", "(", "!", "this", ".", "user", ")", "{", "throw", "new", "errors", ".", "Unauthenticated", "(", ")", "}", "for", "(", "const", "role", "of", "roles", ")", "{", "for", "(", "const", "user_role", "of", "this", ".", "user", ".", "roles", ")", "{", "if", "(", "user_role", "===", "role", ")", "{", "return", "true", "}", "}", "}", "throw", "new", "errors", ".", "Unauthorized", "(", "`", "${", "roles", "}", "`", ")", "}", "// Get JWT token from incoming HTTP request", "let", "token", "=", "get_jwt_token", "(", "this", ")", "// If no JWT token was found, then done", "if", "(", "!", "token", ")", "{", "return", "}", "// JWT token (is now accessible from Koa's `ctx`)", "this", ".", "accessToken", "=", "token", "// Verify JWT token integrity", "// by checking its signature using the supplied `keys`", "let", "payload", "for", "(", "const", "secret", "of", "keys", ")", "{", "try", "{", "payload", "=", "jwt", ".", "verify", "(", "token", ",", "secret", ")", "break", "}", "catch", "(", "error", ")", "{", "// If authentication token expired", "if", "(", "error", ".", "name", "===", "'TokenExpiredError'", ")", "{", "if", "(", "options", ".", "refreshAccessToken", ")", "{", "// If refreshing an access token fails", "// then don't prevent the user from at least seeing a page", "// therefore catching an error here.", "try", "{", "token", "=", "await", "options", ".", "refreshAccessToken", "(", "this", ")", "}", "catch", "(", "error", ")", "{", "log", ".", "error", "(", "error", ")", "}", "if", "(", "token", ")", "{", "for", "(", "const", "secret", "of", "keys", ")", "{", "try", "{", "payload", "=", "jwt", ".", "verify", "(", "token", ",", "secret", ")", "break", "}", "catch", "(", "error", ")", "{", "// Try another `secret`", "if", "(", "error", ".", "name", "===", "'JsonWebTokenError'", "&&", "error", ".", "message", "===", "'invalid signature'", ")", "{", "continue", "}", "// Some other non-JWT-related error", "log", ".", "error", "(", "error", ")", "break", "}", "}", "}", "}", "if", "(", "payload", ")", "{", "break", "}", "throw", "new", "errors", ".", "Access_token_expired", "(", ")", "}", "// Try another `secret`", "if", "(", "error", ".", "name", "===", "'JsonWebTokenError'", "&&", "error", ".", "message", "===", "'invalid signature'", ")", "{", "continue", "}", "// Some other non-JWT-related error.", "// Shouldn't prevent the user from at least seeing a page", "// therefore not rethrowing this error.", "log", ".", "error", "(", "error", ")", "break", "}", "}", "// If JWT token signature was unable to be verified, then exit", "if", "(", "!", "payload", ")", "{", "return", "}", "// If the access token isn't valid for access to this server", "// (e.g. it's a \"refresh token\") then exit.", "if", "(", "options", ".", "validateAccessToken", ")", "{", "if", "(", "!", "options", ".", "validateAccessToken", "(", "payload", ",", "this", ")", ")", "{", "return", "}", "}", "// Token payload can be accessed through `ctx`", "this", ".", "accessTokenPayload", "=", "payload", "// Fire \"on user request\" hook", "if", "(", "options", ".", "onUserRequest", ")", "{", "options", ".", "onUserRequest", "(", "token", ",", "this", ")", "}", "// JWT token ID", "const", "jwt_id", "=", "payload", ".", "jti", "// `subject`", "// (which is a user id)", "const", "user_id", "=", "payload", ".", "sub", "// // Optional JWT token validation (by id)", "// // (for example, that it has not been revoked)", "// if (validateToken)", "// {", "// \t// Can validate the token via a request to a database, for example.", "// \t// Checks for `valid` property value inside the result object.", "// \t// (There can possibly be other properties such as `reason`)", "// \tconst is_valid = (await validateToken(token, this)).valid", "//", "// \t// If the JWT token happens to be invalid", "// \t// (expired or revoked, for example), then exit.", "// \tif (!is_valid)", "// \t{", "// \t\t// this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked')", "// \t\treturn", "// \t}", "// }", "// JWT token ID is now accessible via Koa's `ctx`", "this", ".", "accessTokenId", "=", "jwt_id", "// Extracts user data (description) from JWT token payload", "// (`user` is now accessible via Koa's `ctx`)", "this", ".", "user", "=", "options", ".", "userInfo", "?", "options", ".", "userInfo", "(", "payload", ")", ":", "{", "}", "// Sets user id", "this", ".", "user", ".", "id", "=", "user_id", "// Extra payload fields:", "//", "// 'iss' // Issuer", "// 'sub' // Subject", "// 'aud' // Audience", "// 'exp' // Expiration time", "// 'nbf' // Not before", "// 'iat' // Issued at ", "// 'jti' // JWT ID", "// JWT token payload is accessible via Koa's `ctx`", "this", ".", "accessTokenPayload", "=", "payload", "}" ]
Looks for JWT token, and if it is found, sets some variables.
[ "Looks", "for", "JWT", "token", "and", "if", "it", "is", "found", "sets", "some", "variables", "." ]
e1eabaaf76bd109a2b2c48ad617ebdd9111409a1
https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/authentication.js#L28-L217
41,203
basic-web-components/basic-web-components
packages/basic-autosize-textarea/src/AutosizeTextarea.js
setMinimumHeight
function setMinimumHeight(element) { const copyContainer = element.$.copyContainer; const outerHeight = copyContainer.getBoundingClientRect().height; const style = getComputedStyle(copyContainer); const paddingTop = parseFloat(style.paddingTop); const paddingBottom = parseFloat(style.paddingBottom); const innerHeight = copyContainer.clientHeight - paddingTop - paddingBottom; const bordersPlusPadding = outerHeight - innerHeight; let minHeight = (element.minimumRows * element[lineHeightSymbol]) + bordersPlusPadding; minHeight = Math.ceil(minHeight); copyContainer.style.minHeight = minHeight + 'px'; }
javascript
function setMinimumHeight(element) { const copyContainer = element.$.copyContainer; const outerHeight = copyContainer.getBoundingClientRect().height; const style = getComputedStyle(copyContainer); const paddingTop = parseFloat(style.paddingTop); const paddingBottom = parseFloat(style.paddingBottom); const innerHeight = copyContainer.clientHeight - paddingTop - paddingBottom; const bordersPlusPadding = outerHeight - innerHeight; let minHeight = (element.minimumRows * element[lineHeightSymbol]) + bordersPlusPadding; minHeight = Math.ceil(minHeight); copyContainer.style.minHeight = minHeight + 'px'; }
[ "function", "setMinimumHeight", "(", "element", ")", "{", "const", "copyContainer", "=", "element", ".", "$", ".", "copyContainer", ";", "const", "outerHeight", "=", "copyContainer", ".", "getBoundingClientRect", "(", ")", ".", "height", ";", "const", "style", "=", "getComputedStyle", "(", "copyContainer", ")", ";", "const", "paddingTop", "=", "parseFloat", "(", "style", ".", "paddingTop", ")", ";", "const", "paddingBottom", "=", "parseFloat", "(", "style", ".", "paddingBottom", ")", ";", "const", "innerHeight", "=", "copyContainer", ".", "clientHeight", "-", "paddingTop", "-", "paddingBottom", ";", "const", "bordersPlusPadding", "=", "outerHeight", "-", "innerHeight", ";", "let", "minHeight", "=", "(", "element", ".", "minimumRows", "*", "element", "[", "lineHeightSymbol", "]", ")", "+", "bordersPlusPadding", ";", "minHeight", "=", "Math", ".", "ceil", "(", "minHeight", ")", ";", "copyContainer", ".", "style", ".", "minHeight", "=", "minHeight", "+", "'px'", ";", "}" ]
Setting the minimumRows attribute translates into setting the minimum height on the text copy container.
[ "Setting", "the", "minimumRows", "attribute", "translates", "into", "setting", "the", "minimum", "height", "on", "the", "text", "copy", "container", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-autosize-textarea/src/AutosizeTextarea.js#L332-L343
41,204
basic-web-components/basic-web-components
packages/basic-fade-overflow/src/FadeOverflow.js
extractRgbValues
function extractRgbValues(rgbString) { const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/; const match = rgbRegex.exec(rgbString); if (match) { return { r: parseInt(match[1]), g: parseInt(match[2]), b: parseInt(match[3]) }; } else { return null; } }
javascript
function extractRgbValues(rgbString) { const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/; const match = rgbRegex.exec(rgbString); if (match) { return { r: parseInt(match[1]), g: parseInt(match[2]), b: parseInt(match[3]) }; } else { return null; } }
[ "function", "extractRgbValues", "(", "rgbString", ")", "{", "const", "rgbRegex", "=", "/", "rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*[\\d\\.]+\\s*)?\\)", "/", ";", "const", "match", "=", "rgbRegex", ".", "exec", "(", "rgbString", ")", ";", "if", "(", "match", ")", "{", "return", "{", "r", ":", "parseInt", "(", "match", "[", "1", "]", ")", ",", "g", ":", "parseInt", "(", "match", "[", "2", "]", ")", ",", "b", ":", "parseInt", "(", "match", "[", "3", "]", ")", "}", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Return the individual RGB values from a CSS color string.
[ "Return", "the", "individual", "RGB", "values", "from", "a", "CSS", "color", "string", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-fade-overflow/src/FadeOverflow.js#L128-L140
41,205
basic-web-components/basic-web-components
packages/basic-component-mixins/src/ContentItemsMixin.js
filterAuxiliaryElements
function filterAuxiliaryElements(items) { const auxiliaryTags = [ 'link', 'script', 'style', 'template' ]; return [].filter.call(items, function(item) { return !item.localName || auxiliaryTags.indexOf(item.localName) < 0; }); }
javascript
function filterAuxiliaryElements(items) { const auxiliaryTags = [ 'link', 'script', 'style', 'template' ]; return [].filter.call(items, function(item) { return !item.localName || auxiliaryTags.indexOf(item.localName) < 0; }); }
[ "function", "filterAuxiliaryElements", "(", "items", ")", "{", "const", "auxiliaryTags", "=", "[", "'link'", ",", "'script'", ",", "'style'", ",", "'template'", "]", ";", "return", "[", "]", ".", "filter", ".", "call", "(", "items", ",", "function", "(", "item", ")", "{", "return", "!", "item", ".", "localName", "||", "auxiliaryTags", ".", "indexOf", "(", "item", ".", "localName", ")", "<", "0", ";", "}", ")", ";", "}" ]
Return the given elements, filtering out auxiliary elements that aren't typically visible. Items which are not elements are returned as is.
[ "Return", "the", "given", "elements", "filtering", "out", "auxiliary", "elements", "that", "aren", "t", "typically", "visible", ".", "Items", "which", "are", "not", "elements", "are", "returned", "as", "is", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/ContentItemsMixin.js#L140-L150
41,206
basic-web-components/basic-web-components
packages/basic-component-mixins/src/safeAttributes.js
setAttributeToElement
function setAttributeToElement(element, attributeName, value) { if (value === null || typeof value === 'undefined') { element.removeAttribute(attributeName); } else { const text = String(value); // Avoid recursive attributeChangedCallback calls. if (element.getAttribute(attributeName) !== text) { element.setAttribute(attributeName, value); } } }
javascript
function setAttributeToElement(element, attributeName, value) { if (value === null || typeof value === 'undefined') { element.removeAttribute(attributeName); } else { const text = String(value); // Avoid recursive attributeChangedCallback calls. if (element.getAttribute(attributeName) !== text) { element.setAttribute(attributeName, value); } } }
[ "function", "setAttributeToElement", "(", "element", ",", "attributeName", ",", "value", ")", "{", "if", "(", "value", "===", "null", "||", "typeof", "value", "===", "'undefined'", ")", "{", "element", ".", "removeAttribute", "(", "attributeName", ")", ";", "}", "else", "{", "const", "text", "=", "String", "(", "value", ")", ";", "// Avoid recursive attributeChangedCallback calls.", "if", "(", "element", ".", "getAttribute", "(", "attributeName", ")", "!==", "text", ")", "{", "element", ".", "setAttribute", "(", "attributeName", ",", "value", ")", ";", "}", "}", "}" ]
Reflect the attribute to the given element. If the value is null, remove the attribute.
[ "Reflect", "the", "attribute", "to", "the", "given", "element", ".", "If", "the", "value", "is", "null", "remove", "the", "attribute", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/safeAttributes.js#L107-L117
41,207
basic-web-components/basic-web-components
packages/basic-component-mixins/src/renderArrayAsElements.js
renderArrayAsElements
function renderArrayAsElements(items, container, renderItem) { // Create a new set of elements for the current items. items.forEach((item, index) => { const oldElement = container.childNodes[index]; const newElement = renderItem(item, oldElement); if (newElement) { if (!oldElement) { container.appendChild(newElement); } else if (newElement !== oldElement) { container.replaceChild(newElement, oldElement); } } }); // If the array shrank, remove the extra elements which are no longer needed. while (container.childNodes.length > items.length) { container.removeChild(container.childNodes[items.length]); } }
javascript
function renderArrayAsElements(items, container, renderItem) { // Create a new set of elements for the current items. items.forEach((item, index) => { const oldElement = container.childNodes[index]; const newElement = renderItem(item, oldElement); if (newElement) { if (!oldElement) { container.appendChild(newElement); } else if (newElement !== oldElement) { container.replaceChild(newElement, oldElement); } } }); // If the array shrank, remove the extra elements which are no longer needed. while (container.childNodes.length > items.length) { container.removeChild(container.childNodes[items.length]); } }
[ "function", "renderArrayAsElements", "(", "items", ",", "container", ",", "renderItem", ")", "{", "// Create a new set of elements for the current items.", "items", ".", "forEach", "(", "(", "item", ",", "index", ")", "=>", "{", "const", "oldElement", "=", "container", ".", "childNodes", "[", "index", "]", ";", "const", "newElement", "=", "renderItem", "(", "item", ",", "oldElement", ")", ";", "if", "(", "newElement", ")", "{", "if", "(", "!", "oldElement", ")", "{", "container", ".", "appendChild", "(", "newElement", ")", ";", "}", "else", "if", "(", "newElement", "!==", "oldElement", ")", "{", "container", ".", "replaceChild", "(", "newElement", ",", "oldElement", ")", ";", "}", "}", "}", ")", ";", "// If the array shrank, remove the extra elements which are no longer needed.", "while", "(", "container", ".", "childNodes", ".", "length", ">", "items", ".", "length", ")", "{", "container", ".", "removeChild", "(", "container", ".", "childNodes", "[", "items", ".", "length", "]", ")", ";", "}", "}" ]
Helper function for rendering an array of items as elements. This is not a mixin, but a function components can use if they need to generate a set of elements for the items in an array. This function will reuse existing elements if possible. E.g., if it is called to render an array of 4 items, and later called to render an array of 5 items, it can reuse the existing 4 items, creating just one new element. Note, however, that this re-rendering is not automatic. If, after calling this function, you manipulate the array you used, you must still call this function again to re-render the array. The `renderItem` parameter takes a function of two arguments: an item to to render, and an existing element (if one exists) which can be repurposed to render that item. If the latter argument is null, the `renderItem()` function should create a new element and return it. The function should do the same if the supplied existing element is not suitable for rendering the given item; the returned element will be used to replace the existing one. If the existing element *is* suitable, the function can simply update it and return it as is. Example: The following will render an array of strings in divs as children of the `container` element: let strings = ['a', 'b', 'c', ...]; let container = this.querySelector(...); renderArrayAsElements(strings, container, (string, element) => { if (!element) { // No element exists yet, so create a new one. element = document.createElement('div'); } // Set/update the text content of the element. element.textContent = string; return element; }); @param {Array} items - the items to render @param {HTMLElement} container - the parent that will hold the elements @param {function} renderItem - returns a new element for an item, or repurposes an existing element for an item
[ "Helper", "function", "for", "rendering", "an", "array", "of", "items", "as", "elements", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/renderArrayAsElements.js#L43-L61
41,208
catamphetamine/web-service
source/middleware/file upload.js
upload_file
async function upload_file(file, { upload_folder, log }) { if (log) { log.debug(`Uploading: ${file.filename}`) } // Generate random unique filename const file_name = await generate_unique_filename(upload_folder, { on_collision: (file_name) => { log.info(`Generate unique file name: collision for "${file_name}". Taking another try.`) } }) // dot_extension: path.extname(file.filename) const output_file = path.join(upload_folder, file_name) // Write the file to disk return await new Promise((resolve, reject) => { // Ensure the `upload_folder` exists // (just an extra precaution) fs.ensureDir(upload_folder, (error) => { if (error) { return reject(error) } // Open output file stream const stream = fs.createWriteStream(output_file) // Pipe file contents to disk file.pipe(stream) .on('finish', () => resolve(path.relative(upload_folder, output_file))) .on('error', error => reject(error)) }) }) }
javascript
async function upload_file(file, { upload_folder, log }) { if (log) { log.debug(`Uploading: ${file.filename}`) } // Generate random unique filename const file_name = await generate_unique_filename(upload_folder, { on_collision: (file_name) => { log.info(`Generate unique file name: collision for "${file_name}". Taking another try.`) } }) // dot_extension: path.extname(file.filename) const output_file = path.join(upload_folder, file_name) // Write the file to disk return await new Promise((resolve, reject) => { // Ensure the `upload_folder` exists // (just an extra precaution) fs.ensureDir(upload_folder, (error) => { if (error) { return reject(error) } // Open output file stream const stream = fs.createWriteStream(output_file) // Pipe file contents to disk file.pipe(stream) .on('finish', () => resolve(path.relative(upload_folder, output_file))) .on('error', error => reject(error)) }) }) }
[ "async", "function", "upload_file", "(", "file", ",", "{", "upload_folder", ",", "log", "}", ")", "{", "if", "(", "log", ")", "{", "log", ".", "debug", "(", "`", "${", "file", ".", "filename", "}", "`", ")", "}", "// Generate random unique filename", "const", "file_name", "=", "await", "generate_unique_filename", "(", "upload_folder", ",", "{", "on_collision", ":", "(", "file_name", ")", "=>", "{", "log", ".", "info", "(", "`", "${", "file_name", "}", "`", ")", "}", "}", ")", "// dot_extension: path.extname(file.filename)", "const", "output_file", "=", "path", ".", "join", "(", "upload_folder", ",", "file_name", ")", "// Write the file to disk", "return", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// Ensure the `upload_folder` exists", "// (just an extra precaution)", "fs", ".", "ensureDir", "(", "upload_folder", ",", "(", "error", ")", "=>", "{", "if", "(", "error", ")", "{", "return", "reject", "(", "error", ")", "}", "// Open output file stream", "const", "stream", "=", "fs", ".", "createWriteStream", "(", "output_file", ")", "// Pipe file contents to disk", "file", ".", "pipe", "(", "stream", ")", ".", "on", "(", "'finish'", ",", "(", ")", "=>", "resolve", "(", "path", ".", "relative", "(", "upload_folder", ",", "output_file", ")", ")", ")", ".", "on", "(", "'error'", ",", "error", "=>", "reject", "(", "error", ")", ")", "}", ")", "}", ")", "}" ]
Handles file upload. Takes a `file` busboy file object along with `upload_folder` option. Writes the `file` stream to `upload_folder` naming it with a randomly generated filename. Returns a Promise resolving to the randomly generated filename.
[ "Handles", "file", "upload", ".", "Takes", "a", "file", "busboy", "file", "object", "along", "with", "upload_folder", "option", ".", "Writes", "the", "file", "stream", "to", "upload_folder", "naming", "it", "with", "a", "randomly", "generated", "filename", ".", "Returns", "a", "Promise", "resolving", "to", "the", "randomly", "generated", "filename", "." ]
e1eabaaf76bd109a2b2c48ad617ebdd9111409a1
https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/file upload.js#L284-L325
41,209
basic-web-components/basic-web-components
packages/demos/bower_components/shadydom/src/tree.js
assertNative
function assertNative(element, property, tracked) { let native = getNativeProperty(element, property); if (native != tracked && element.__patched) { window.console.warn('tracked', tracked, 'native', native); } return tracked; }
javascript
function assertNative(element, property, tracked) { let native = getNativeProperty(element, property); if (native != tracked && element.__patched) { window.console.warn('tracked', tracked, 'native', native); } return tracked; }
[ "function", "assertNative", "(", "element", ",", "property", ",", "tracked", ")", "{", "let", "native", "=", "getNativeProperty", "(", "element", ",", "property", ")", ";", "if", "(", "native", "!=", "tracked", "&&", "element", ".", "__patched", ")", "{", "window", ".", "console", ".", "warn", "(", "'tracked'", ",", "tracked", ",", "'native'", ",", "native", ")", ";", "}", "return", "tracked", ";", "}" ]
for testing...
[ "for", "testing", "..." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/src/tree.js#L569-L575
41,210
pazams/vivalid
lib/validator-repo.js
build
function build(validatorName, validatorOptions) { if (typeof validatorBuildersRepository[validatorName] !== 'function') { throw validatorName + ' does not exists. use addValidatorBuilder to add a new validation rule'; } return validatorBuildersRepository[validatorName](ValidationState, stateEnum, validatorOptions); }
javascript
function build(validatorName, validatorOptions) { if (typeof validatorBuildersRepository[validatorName] !== 'function') { throw validatorName + ' does not exists. use addValidatorBuilder to add a new validation rule'; } return validatorBuildersRepository[validatorName](ValidationState, stateEnum, validatorOptions); }
[ "function", "build", "(", "validatorName", ",", "validatorOptions", ")", "{", "if", "(", "typeof", "validatorBuildersRepository", "[", "validatorName", "]", "!==", "'function'", ")", "{", "throw", "validatorName", "+", "' does not exists. use addValidatorBuilder to add a new validation rule'", ";", "}", "return", "validatorBuildersRepository", "[", "validatorName", "]", "(", "ValidationState", ",", "stateEnum", ",", "validatorOptions", ")", ";", "}" ]
Adds validator builder. Use to create custom validation rules. @memberof! vivalid.validatorRepo @function @private @param {validatorName} name validator name. @param {object} validatorOptions.
[ "Adds", "validator", "builder", ".", "Use", "to", "create", "custom", "validation", "rules", "." ]
dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f
https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/validator-repo.js#L27-L34
41,211
pazams/vivalid
lib/html-interface.js
addCallback
function addCallback(name, fn) { if (typeof fn !== 'function') throw 'error while trying to add a custom callback: argument must be a function'; if (callbacks[name]) throw 'error while trying to add a custom callback: ' + name + ' already exists'; callbacks[name] = fn; }
javascript
function addCallback(name, fn) { if (typeof fn !== 'function') throw 'error while trying to add a custom callback: argument must be a function'; if (callbacks[name]) throw 'error while trying to add a custom callback: ' + name + ' already exists'; callbacks[name] = fn; }
[ "function", "addCallback", "(", "name", ",", "fn", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "throw", "'error while trying to add a custom callback: argument must be a function'", ";", "if", "(", "callbacks", "[", "name", "]", ")", "throw", "'error while trying to add a custom callback: '", "+", "name", "+", "' already exists'", ";", "callbacks", "[", "name", "]", "=", "fn", ";", "}" ]
Adds functional parameters, to be referenced at html data attributes. @memberof! vivalid.htmlInterface @function @example vivalid.htmlInterface.addCallback('onValidationFailure', function(invalid,pending,valid){ alert('input group is invalid!: '+invalid+ ' invalid, ' +pending+' pending, and ' +valid+' valid ' ); }); @param {string} name @param {function} fn
[ "Adds", "functional", "parameters", "to", "be", "referenced", "at", "html", "data", "attributes", "." ]
dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f
https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L19-L23
41,212
pazams/vivalid
lib/html-interface.js
initGroup
function initGroup(groupElem) { $$.ready(registerGroupFromDataAttribtues); function registerGroupFromDataAttribtues() { inputElems = $$.getElementsByTagNames(validInputTagNames, groupElem) .filter(function(el) { return $$.hasDataSet(el, 'vivalidTuples'); }); var vivalidGroup = createGroupFromDataAttribtues(groupElem, inputElems); addToGroupNameDictionairy(groupElem, vivalidGroup); } }
javascript
function initGroup(groupElem) { $$.ready(registerGroupFromDataAttribtues); function registerGroupFromDataAttribtues() { inputElems = $$.getElementsByTagNames(validInputTagNames, groupElem) .filter(function(el) { return $$.hasDataSet(el, 'vivalidTuples'); }); var vivalidGroup = createGroupFromDataAttribtues(groupElem, inputElems); addToGroupNameDictionairy(groupElem, vivalidGroup); } }
[ "function", "initGroup", "(", "groupElem", ")", "{", "$$", ".", "ready", "(", "registerGroupFromDataAttribtues", ")", ";", "function", "registerGroupFromDataAttribtues", "(", ")", "{", "inputElems", "=", "$$", ".", "getElementsByTagNames", "(", "validInputTagNames", ",", "groupElem", ")", ".", "filter", "(", "function", "(", "el", ")", "{", "return", "$$", ".", "hasDataSet", "(", "el", ",", "'vivalidTuples'", ")", ";", "}", ")", ";", "var", "vivalidGroup", "=", "createGroupFromDataAttribtues", "(", "groupElem", ",", "inputElems", ")", ";", "addToGroupNameDictionairy", "(", "groupElem", ",", "vivalidGroup", ")", ";", "}", "}" ]
Bootstraps a group by the group's DOM HTMLElement when using the html data attributes interface. Provides more control over vivalid.htmlInterface.init. Usefull when some of the elements are not present when DOMContentLoaded fires, but rather are appended at some later stage in the application flow. @memberof! vivalid.htmlInterface @function @example vivalid.htmlInterface.initGroup(document.getElementById('FormId')); @param {HTMLElement} groupElem
[ "Bootstraps", "a", "group", "by", "the", "group", "s", "DOM", "HTMLElement", "when", "using", "the", "html", "data", "attributes", "interface", ".", "Provides", "more", "control", "over", "vivalid", ".", "htmlInterface", ".", "init", ".", "Usefull", "when", "some", "of", "the", "elements", "are", "not", "present", "when", "DOMContentLoaded", "fires", "but", "rather", "are", "appended", "at", "some", "later", "stage", "in", "the", "application", "flow", "." ]
dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f
https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L32-L46
41,213
pazams/vivalid
lib/html-interface.js
initAll
function initAll() { $$.ready(registerAllFromDataAttribtues); function registerAllFromDataAttribtues() { var _nextGroupId = 1; // es6 map would have been nice here, but this lib is intended to run on es5 browsers. integrating Babel might work. var groupIdToInputs = {}; var groupIdToGroup = {}; $$.getElementsByTagNames(validInputTagNames) .filter(function(el) { return $$.hasDataSet(el, 'vivalidTuples'); }) .forEach(function(el) { addGroupInputs($$.getClosestParentByAttribute(el, 'vivalidGroup'), el); }); for (var groupId in groupIdToInputs) { var vivalidGroup = createGroupFromDataAttribtues(groupIdToGroup[groupId], groupIdToInputs[groupId]); addToGroupNameDictionairy(groupIdToGroup[groupId], vivalidGroup); } function addGroupInputs(group, input) { if (!group) { throw 'an input validation is missing a group, input id: ' + input.id; } if (!group._groupId) group._groupId = _nextGroupId++; if (!groupIdToInputs[group._groupId]) { groupIdToInputs[group._groupId] = []; groupIdToGroup[group._groupId] = group; } groupIdToInputs[group._groupId].push(input); } } }
javascript
function initAll() { $$.ready(registerAllFromDataAttribtues); function registerAllFromDataAttribtues() { var _nextGroupId = 1; // es6 map would have been nice here, but this lib is intended to run on es5 browsers. integrating Babel might work. var groupIdToInputs = {}; var groupIdToGroup = {}; $$.getElementsByTagNames(validInputTagNames) .filter(function(el) { return $$.hasDataSet(el, 'vivalidTuples'); }) .forEach(function(el) { addGroupInputs($$.getClosestParentByAttribute(el, 'vivalidGroup'), el); }); for (var groupId in groupIdToInputs) { var vivalidGroup = createGroupFromDataAttribtues(groupIdToGroup[groupId], groupIdToInputs[groupId]); addToGroupNameDictionairy(groupIdToGroup[groupId], vivalidGroup); } function addGroupInputs(group, input) { if (!group) { throw 'an input validation is missing a group, input id: ' + input.id; } if (!group._groupId) group._groupId = _nextGroupId++; if (!groupIdToInputs[group._groupId]) { groupIdToInputs[group._groupId] = []; groupIdToGroup[group._groupId] = group; } groupIdToInputs[group._groupId].push(input); } } }
[ "function", "initAll", "(", ")", "{", "$$", ".", "ready", "(", "registerAllFromDataAttribtues", ")", ";", "function", "registerAllFromDataAttribtues", "(", ")", "{", "var", "_nextGroupId", "=", "1", ";", "// es6 map would have been nice here, but this lib is intended to run on es5 browsers. integrating Babel might work.", "var", "groupIdToInputs", "=", "{", "}", ";", "var", "groupIdToGroup", "=", "{", "}", ";", "$$", ".", "getElementsByTagNames", "(", "validInputTagNames", ")", ".", "filter", "(", "function", "(", "el", ")", "{", "return", "$$", ".", "hasDataSet", "(", "el", ",", "'vivalidTuples'", ")", ";", "}", ")", ".", "forEach", "(", "function", "(", "el", ")", "{", "addGroupInputs", "(", "$$", ".", "getClosestParentByAttribute", "(", "el", ",", "'vivalidGroup'", ")", ",", "el", ")", ";", "}", ")", ";", "for", "(", "var", "groupId", "in", "groupIdToInputs", ")", "{", "var", "vivalidGroup", "=", "createGroupFromDataAttribtues", "(", "groupIdToGroup", "[", "groupId", "]", ",", "groupIdToInputs", "[", "groupId", "]", ")", ";", "addToGroupNameDictionairy", "(", "groupIdToGroup", "[", "groupId", "]", ",", "vivalidGroup", ")", ";", "}", "function", "addGroupInputs", "(", "group", ",", "input", ")", "{", "if", "(", "!", "group", ")", "{", "throw", "'an input validation is missing a group, input id: '", "+", "input", ".", "id", ";", "}", "if", "(", "!", "group", ".", "_groupId", ")", "group", ".", "_groupId", "=", "_nextGroupId", "++", ";", "if", "(", "!", "groupIdToInputs", "[", "group", ".", "_groupId", "]", ")", "{", "groupIdToInputs", "[", "group", ".", "_groupId", "]", "=", "[", "]", ";", "groupIdToGroup", "[", "group", ".", "_groupId", "]", "=", "group", ";", "}", "groupIdToInputs", "[", "group", ".", "_groupId", "]", ".", "push", "(", "input", ")", ";", "}", "}", "}" ]
Bootstraps all groups when using the html data attributes interface. Will work on all groups present at initial page load. @memberof! vivalid.htmlInterface @function @example vivalid.htmlInterface.initAll();
[ "Bootstraps", "all", "groups", "when", "using", "the", "html", "data", "attributes", "interface", ".", "Will", "work", "on", "all", "groups", "present", "at", "initial", "page", "load", "." ]
dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f
https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L54-L97
41,214
pazams/vivalid
lib/html-interface.js
resetGroup
function resetGroup(groupName) { var vivalidGroup = groupNameToVivalidGroup[groupName]; if (vivalidGroup) { vivalidGroup.reset(); } else { console.log('could not find group named ' + groupName); } }
javascript
function resetGroup(groupName) { var vivalidGroup = groupNameToVivalidGroup[groupName]; if (vivalidGroup) { vivalidGroup.reset(); } else { console.log('could not find group named ' + groupName); } }
[ "function", "resetGroup", "(", "groupName", ")", "{", "var", "vivalidGroup", "=", "groupNameToVivalidGroup", "[", "groupName", "]", ";", "if", "(", "vivalidGroup", ")", "{", "vivalidGroup", ".", "reset", "(", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'could not find group named '", "+", "groupName", ")", ";", "}", "}" ]
Allow's an application to reset the validations state and event listeners of a group @memberof! vivalid.htmlInterface @function @example vivalid.htmlInterface.resetGroup('contactGroup'); @param {string} groupName
[ "Allow", "s", "an", "application", "to", "reset", "the", "validations", "state", "and", "event", "listeners", "of", "a", "group" ]
dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f
https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L106-L116
41,215
basic-web-components/basic-web-components
packages/basic-component-mixins/src/KeyboardPrefixSelectionMixin.js
getIndexOfItemWithTextPrefix
function getIndexOfItemWithTextPrefix(element, prefix) { const itemTextContents = getItemTextContents(element); const prefixLength = prefix.length; for (let i = 0; i < itemTextContents.length; i++) { const itemTextContent = itemTextContents[i]; if (itemTextContent.substr(0, prefixLength) === prefix) { return i; } } return -1; }
javascript
function getIndexOfItemWithTextPrefix(element, prefix) { const itemTextContents = getItemTextContents(element); const prefixLength = prefix.length; for (let i = 0; i < itemTextContents.length; i++) { const itemTextContent = itemTextContents[i]; if (itemTextContent.substr(0, prefixLength) === prefix) { return i; } } return -1; }
[ "function", "getIndexOfItemWithTextPrefix", "(", "element", ",", "prefix", ")", "{", "const", "itemTextContents", "=", "getItemTextContents", "(", "element", ")", ";", "const", "prefixLength", "=", "prefix", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "itemTextContents", ".", "length", ";", "i", "++", ")", "{", "const", "itemTextContent", "=", "itemTextContents", "[", "i", "]", ";", "if", "(", "itemTextContent", ".", "substr", "(", "0", ",", "prefixLength", ")", "===", "prefix", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Return the index of the first item with the given prefix, else -1.
[ "Return", "the", "index", "of", "the", "first", "item", "with", "the", "given", "prefix", "else", "-", "1", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/KeyboardPrefixSelectionMixin.js#L118-L128
41,216
basic-web-components/basic-web-components
packages/basic-component-mixins/src/ShadowTemplateMixin.js
createTemplateWithInnerHTML
function createTemplateWithInnerHTML(innerHTML) { const template = document.createElement('template'); // REVIEW: Is there an easier way to do this? // We'd like to just set innerHTML on the template content, but since it's // a DocumentFragment, that doesn't work. const div = document.createElement('div'); div.innerHTML = innerHTML; while (div.childNodes.length > 0) { template.content.appendChild(div.childNodes[0]); } return template; }
javascript
function createTemplateWithInnerHTML(innerHTML) { const template = document.createElement('template'); // REVIEW: Is there an easier way to do this? // We'd like to just set innerHTML on the template content, but since it's // a DocumentFragment, that doesn't work. const div = document.createElement('div'); div.innerHTML = innerHTML; while (div.childNodes.length > 0) { template.content.appendChild(div.childNodes[0]); } return template; }
[ "function", "createTemplateWithInnerHTML", "(", "innerHTML", ")", "{", "const", "template", "=", "document", ".", "createElement", "(", "'template'", ")", ";", "// REVIEW: Is there an easier way to do this?", "// We'd like to just set innerHTML on the template content, but since it's", "// a DocumentFragment, that doesn't work.", "const", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "innerHTML", "=", "innerHTML", ";", "while", "(", "div", ".", "childNodes", ".", "length", ">", "0", ")", "{", "template", ".", "content", ".", "appendChild", "(", "div", ".", "childNodes", "[", "0", "]", ")", ";", "}", "return", "template", ";", "}" ]
Convert a plain string of HTML into a real template element.
[ "Convert", "a", "plain", "string", "of", "HTML", "into", "a", "real", "template", "element", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/ShadowTemplateMixin.js#L64-L75
41,217
basic-web-components/basic-web-components
packages/basic-component-mixins/src/ShadowTemplateMixin.js
shimTemplateStyles
function shimTemplateStyles(template, tag) { window.WebComponents.ShadowCSS.shimStyling(template.content, tag); }
javascript
function shimTemplateStyles(template, tag) { window.WebComponents.ShadowCSS.shimStyling(template.content, tag); }
[ "function", "shimTemplateStyles", "(", "template", ",", "tag", ")", "{", "window", ".", "WebComponents", ".", "ShadowCSS", ".", "shimStyling", "(", "template", ".", "content", ",", "tag", ")", ";", "}" ]
Invoke basic style shimming with ShadowCSS.
[ "Invoke", "basic", "style", "shimming", "with", "ShadowCSS", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/ShadowTemplateMixin.js#L78-L80
41,218
catamphetamine/web-service
source/deprecated/koa-generic-session/lib/session.js
compatMaxage
function compatMaxage(opts) { if (opts) { opts.maxage = opts.maxage === undefined ? opts.maxAge : opts.maxage; delete opts.maxAge; } }
javascript
function compatMaxage(opts) { if (opts) { opts.maxage = opts.maxage === undefined ? opts.maxAge : opts.maxage; delete opts.maxAge; } }
[ "function", "compatMaxage", "(", "opts", ")", "{", "if", "(", "opts", ")", "{", "opts", ".", "maxage", "=", "opts", ".", "maxage", "===", "undefined", "?", "opts", ".", "maxAge", ":", "opts", ".", "maxage", ";", "delete", "opts", ".", "maxAge", ";", "}", "}" ]
cookie use maxage, hack to compat connect type `maxAge`
[ "cookie", "use", "maxage", "hack", "to", "compat", "connect", "type", "maxAge" ]
e1eabaaf76bd109a2b2c48ad617ebdd9111409a1
https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/deprecated/koa-generic-session/lib/session.js#L414-L421
41,219
catamphetamine/web-service
source/middleware/error handler.js
render_stack_trace
function render_stack_trace(error, { markup_settings, log }) { // Supports custom `html` for an error if (error.html) { return { response_status: error.status, response_body: error.html } } // Handle `superagent` errors // https://github.com/visionmedia/superagent/blob/29ca1fc938b974c6623d9040a044e39dfb272fed/lib/node/response.js#L106 if (error.response && typeof error.status === 'number') { // If the `superagent` http request returned an HTML response // (possibly an error stack trace), // then just output that stack trace. if (error.response.headers['content-type'] && error.response.headers['content-type'].split(';')[0].trim() === 'text/html') { return { response_status: error.status, response_body: error.message } } } // If this error has a stack trace then it can be shown let stack_trace if (error.stack) { stack_trace = error.stack } // `superagent` errors have the `original` property // for storing the initial error else if (error.original && error.original.stack) { stack_trace = error.original.stack } // If this error doesn't have a stack trace - do nothing if (!stack_trace) { return {} } // Render the error's stack trace as HTML markup try { return { response_body: html_stack_trace({ stack: stack_trace }, markup_settings) } } catch (error) { log.error(error) // If error stack trace couldn't be rendered as HTML markup, // then just output it as plain text. return { response_body: error.stack } } }
javascript
function render_stack_trace(error, { markup_settings, log }) { // Supports custom `html` for an error if (error.html) { return { response_status: error.status, response_body: error.html } } // Handle `superagent` errors // https://github.com/visionmedia/superagent/blob/29ca1fc938b974c6623d9040a044e39dfb272fed/lib/node/response.js#L106 if (error.response && typeof error.status === 'number') { // If the `superagent` http request returned an HTML response // (possibly an error stack trace), // then just output that stack trace. if (error.response.headers['content-type'] && error.response.headers['content-type'].split(';')[0].trim() === 'text/html') { return { response_status: error.status, response_body: error.message } } } // If this error has a stack trace then it can be shown let stack_trace if (error.stack) { stack_trace = error.stack } // `superagent` errors have the `original` property // for storing the initial error else if (error.original && error.original.stack) { stack_trace = error.original.stack } // If this error doesn't have a stack trace - do nothing if (!stack_trace) { return {} } // Render the error's stack trace as HTML markup try { return { response_body: html_stack_trace({ stack: stack_trace }, markup_settings) } } catch (error) { log.error(error) // If error stack trace couldn't be rendered as HTML markup, // then just output it as plain text. return { response_body: error.stack } } }
[ "function", "render_stack_trace", "(", "error", ",", "{", "markup_settings", ",", "log", "}", ")", "{", "// Supports custom `html` for an error", "if", "(", "error", ".", "html", ")", "{", "return", "{", "response_status", ":", "error", ".", "status", ",", "response_body", ":", "error", ".", "html", "}", "}", "// Handle `superagent` errors", "// https://github.com/visionmedia/superagent/blob/29ca1fc938b974c6623d9040a044e39dfb272fed/lib/node/response.js#L106", "if", "(", "error", ".", "response", "&&", "typeof", "error", ".", "status", "===", "'number'", ")", "{", "// If the `superagent` http request returned an HTML response ", "// (possibly an error stack trace),", "// then just output that stack trace.", "if", "(", "error", ".", "response", ".", "headers", "[", "'content-type'", "]", "&&", "error", ".", "response", ".", "headers", "[", "'content-type'", "]", ".", "split", "(", "';'", ")", "[", "0", "]", ".", "trim", "(", ")", "===", "'text/html'", ")", "{", "return", "{", "response_status", ":", "error", ".", "status", ",", "response_body", ":", "error", ".", "message", "}", "}", "}", "// If this error has a stack trace then it can be shown", "let", "stack_trace", "if", "(", "error", ".", "stack", ")", "{", "stack_trace", "=", "error", ".", "stack", "}", "// `superagent` errors have the `original` property ", "// for storing the initial error", "else", "if", "(", "error", ".", "original", "&&", "error", ".", "original", ".", "stack", ")", "{", "stack_trace", "=", "error", ".", "original", ".", "stack", "}", "// If this error doesn't have a stack trace - do nothing", "if", "(", "!", "stack_trace", ")", "{", "return", "{", "}", "}", "// Render the error's stack trace as HTML markup", "try", "{", "return", "{", "response_body", ":", "html_stack_trace", "(", "{", "stack", ":", "stack_trace", "}", ",", "markup_settings", ")", "}", "}", "catch", "(", "error", ")", "{", "log", ".", "error", "(", "error", ")", "// If error stack trace couldn't be rendered as HTML markup,", "// then just output it as plain text.", "return", "{", "response_body", ":", "error", ".", "stack", "}", "}", "}" ]
Renders the stack trace of an error as HTML markup
[ "Renders", "the", "stack", "trace", "of", "an", "error", "as", "HTML", "markup" ]
e1eabaaf76bd109a2b2c48ad617ebdd9111409a1
https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/error handler.js#L118-L174
41,220
clux/duel
duel.js
Id
function Id(bracket, round, match) { if (!(this instanceof Id)) { return new Id(bracket, round, match); } this.s = bracket; this.r = round; this.m = match; }
javascript
function Id(bracket, round, match) { if (!(this instanceof Id)) { return new Id(bracket, round, match); } this.s = bracket; this.r = round; this.m = match; }
[ "function", "Id", "(", "bracket", ",", "round", ",", "match", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Id", ")", ")", "{", "return", "new", "Id", "(", "bracket", ",", "round", ",", "match", ")", ";", "}", "this", ".", "s", "=", "bracket", ";", "this", ".", "r", "=", "round", ";", "this", ".", "m", "=", "match", ";", "}" ]
Id class - so each Id has an automatic string representation
[ "Id", "class", "-", "so", "each", "Id", "has", "an", "automatic", "string", "representation" ]
0482733bb19bd6dfe8ae807306da8641020ca6b2
https://github.com/clux/duel/blob/0482733bb19bd6dfe8ae807306da8641020ca6b2/duel.js#L9-L16
41,221
clux/duel
duel.js
function (size, p, last, isLong) { var matches = []; // first WB round to initialize players for (var i = 1; i <= Math.pow(2, p - 1); i += 1) { matches.push({ id: gId(WB, 1, i), p: woMark(seeds(i, p), size) }); } // blank WB rounds var r, g; for (r = 2; r <= p; r += 1) { for (g = 1; g <= Math.pow(2, p - r); g += 1) { matches.push({id: gId(WB, r, g), p: blank() }); } } // blank LB rounds if (last >= LB) { for (r = 1; r <= 2*p - 2; r += 1) { // number of matches halves every odd round in losers bracket for (g = 1; g <= Math.pow(2, p - 1 - Math.floor((r + 1) / 2)); g += 1) { matches.push({ id: gId(LB, r, g), p: blank() }); } } matches.push({ id: gId(LB, 2*p - 1, 1), p: blank() }); // grand final match 1 } if (isLong) { // bronze final if last === WB, else grand final match 2 matches.push({ id: gId(LB, last === LB ? 2*p : 1, 1), p: blank() }); } return matches.sort(Base.compareMatches); // sort so they can be scored in order }
javascript
function (size, p, last, isLong) { var matches = []; // first WB round to initialize players for (var i = 1; i <= Math.pow(2, p - 1); i += 1) { matches.push({ id: gId(WB, 1, i), p: woMark(seeds(i, p), size) }); } // blank WB rounds var r, g; for (r = 2; r <= p; r += 1) { for (g = 1; g <= Math.pow(2, p - r); g += 1) { matches.push({id: gId(WB, r, g), p: blank() }); } } // blank LB rounds if (last >= LB) { for (r = 1; r <= 2*p - 2; r += 1) { // number of matches halves every odd round in losers bracket for (g = 1; g <= Math.pow(2, p - 1 - Math.floor((r + 1) / 2)); g += 1) { matches.push({ id: gId(LB, r, g), p: blank() }); } } matches.push({ id: gId(LB, 2*p - 1, 1), p: blank() }); // grand final match 1 } if (isLong) { // bronze final if last === WB, else grand final match 2 matches.push({ id: gId(LB, last === LB ? 2*p : 1, 1), p: blank() }); } return matches.sort(Base.compareMatches); // sort so they can be scored in order }
[ "function", "(", "size", ",", "p", ",", "last", ",", "isLong", ")", "{", "var", "matches", "=", "[", "]", ";", "// first WB round to initialize players", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "Math", ".", "pow", "(", "2", ",", "p", "-", "1", ")", ";", "i", "+=", "1", ")", "{", "matches", ".", "push", "(", "{", "id", ":", "gId", "(", "WB", ",", "1", ",", "i", ")", ",", "p", ":", "woMark", "(", "seeds", "(", "i", ",", "p", ")", ",", "size", ")", "}", ")", ";", "}", "// blank WB rounds", "var", "r", ",", "g", ";", "for", "(", "r", "=", "2", ";", "r", "<=", "p", ";", "r", "+=", "1", ")", "{", "for", "(", "g", "=", "1", ";", "g", "<=", "Math", ".", "pow", "(", "2", ",", "p", "-", "r", ")", ";", "g", "+=", "1", ")", "{", "matches", ".", "push", "(", "{", "id", ":", "gId", "(", "WB", ",", "r", ",", "g", ")", ",", "p", ":", "blank", "(", ")", "}", ")", ";", "}", "}", "// blank LB rounds", "if", "(", "last", ">=", "LB", ")", "{", "for", "(", "r", "=", "1", ";", "r", "<=", "2", "*", "p", "-", "2", ";", "r", "+=", "1", ")", "{", "// number of matches halves every odd round in losers bracket", "for", "(", "g", "=", "1", ";", "g", "<=", "Math", ".", "pow", "(", "2", ",", "p", "-", "1", "-", "Math", ".", "floor", "(", "(", "r", "+", "1", ")", "/", "2", ")", ")", ";", "g", "+=", "1", ")", "{", "matches", ".", "push", "(", "{", "id", ":", "gId", "(", "LB", ",", "r", ",", "g", ")", ",", "p", ":", "blank", "(", ")", "}", ")", ";", "}", "}", "matches", ".", "push", "(", "{", "id", ":", "gId", "(", "LB", ",", "2", "*", "p", "-", "1", ",", "1", ")", ",", "p", ":", "blank", "(", ")", "}", ")", ";", "// grand final match 1", "}", "if", "(", "isLong", ")", "{", "// bronze final if last === WB, else grand final match 2", "matches", ".", "push", "(", "{", "id", ":", "gId", "(", "LB", ",", "last", "===", "LB", "?", "2", "*", "p", ":", "1", ",", "1", ")", ",", "p", ":", "blank", "(", ")", "}", ")", ";", "}", "return", "matches", ".", "sort", "(", "Base", ".", "compareMatches", ")", ";", "// sort so they can be scored in order", "}" ]
make ALL matches for a Duel elimination tournament
[ "make", "ALL", "matches", "for", "a", "Duel", "elimination", "tournament" ]
0482733bb19bd6dfe8ae807306da8641020ca6b2
https://github.com/clux/duel/blob/0482733bb19bd6dfe8ae807306da8641020ca6b2/duel.js#L61-L91
41,222
clux/duel
duel.js
function (p, round, game) { // we know round <= p var numGames = Math.pow(2, p - round); var midPoint = Math.floor(Math.pow(2, p - round - 1)); // midPoint 0 in finals // reverse the match list map var reversed = $.odd(Math.floor(round/2)); // split the match list map in two change order and rejoin the lists var partitioned = $.even(Math.floor((round + 1)/2)); if (partitioned) { if (reversed) { return (game > midPoint) ? numGames - game + midPoint + 1 : midPoint - game + 1; } return (game > midPoint) ? game - midPoint : game + midPoint; } return reversed ? numGames - game + 1 : game; }
javascript
function (p, round, game) { // we know round <= p var numGames = Math.pow(2, p - round); var midPoint = Math.floor(Math.pow(2, p - round - 1)); // midPoint 0 in finals // reverse the match list map var reversed = $.odd(Math.floor(round/2)); // split the match list map in two change order and rejoin the lists var partitioned = $.even(Math.floor((round + 1)/2)); if (partitioned) { if (reversed) { return (game > midPoint) ? numGames - game + midPoint + 1 : midPoint - game + 1; } return (game > midPoint) ? game - midPoint : game + midPoint; } return reversed ? numGames - game + 1 : game; }
[ "function", "(", "p", ",", "round", ",", "game", ")", "{", "// we know round <= p", "var", "numGames", "=", "Math", ".", "pow", "(", "2", ",", "p", "-", "round", ")", ";", "var", "midPoint", "=", "Math", ".", "floor", "(", "Math", ".", "pow", "(", "2", ",", "p", "-", "round", "-", "1", ")", ")", ";", "// midPoint 0 in finals", "// reverse the match list map", "var", "reversed", "=", "$", ".", "odd", "(", "Math", ".", "floor", "(", "round", "/", "2", ")", ")", ";", "// split the match list map in two change order and rejoin the lists", "var", "partitioned", "=", "$", ".", "even", "(", "Math", ".", "floor", "(", "(", "round", "+", "1", ")", "/", "2", ")", ")", ";", "if", "(", "partitioned", ")", "{", "if", "(", "reversed", ")", "{", "return", "(", "game", ">", "midPoint", ")", "?", "numGames", "-", "game", "+", "midPoint", "+", "1", ":", "midPoint", "-", "game", "+", "1", ";", "}", "return", "(", "game", ">", "midPoint", ")", "?", "game", "-", "midPoint", ":", "game", "+", "midPoint", ";", "}", "return", "reversed", "?", "numGames", "-", "game", "+", "1", ":", "game", ";", "}" ]
helper to mix down progression to reduce chances of replayed matches
[ "helper", "to", "mix", "down", "progression", "to", "reduce", "chances", "of", "replayed", "matches" ]
0482733bb19bd6dfe8ae807306da8641020ca6b2
https://github.com/clux/duel/blob/0482733bb19bd6dfe8ae807306da8641020ca6b2/duel.js#L144-L161
41,223
clux/duel
duel.js
function (id) { var b = id.s , r = id.r , g = id.m , p = this.p; // knockouts / special finals if (b >= this.last) { // greater than case is for BF in long single elimination if (b === WB && this.isLong && r === p - 1) { // if bronze final, move loser to "LBR1" at mirror pos of WBGF return [gId(LB, 1, 1), (g + 1) % 2]; } if (b === LB && r === 2*p - 1 && this.isLong) { // if double final, then loser moves to the bottom return [gId(LB, 2 * p, 1), 1]; } // otherwise always KO'd if loosing in >= last bracket return null; } // WBR1 always feeds into LBR1 as if it were WBR2 if (r === 1) { return [gId(LB, 1, Math.floor((g+1)/2)), g % 2]; } if (this.downMix) { // always drop on top when downmixing return [gId(LB, (r-1)*2, mixLbGames(p, r, g)), 0]; } // normal LB drops: on top for (r>2) and (r<=2 if odd g) to match bracket movement var pos = (r > 2 || $.odd(g)) ? 0 : 1; return [gId(LB, (r-1)*2, g), pos]; }
javascript
function (id) { var b = id.s , r = id.r , g = id.m , p = this.p; // knockouts / special finals if (b >= this.last) { // greater than case is for BF in long single elimination if (b === WB && this.isLong && r === p - 1) { // if bronze final, move loser to "LBR1" at mirror pos of WBGF return [gId(LB, 1, 1), (g + 1) % 2]; } if (b === LB && r === 2*p - 1 && this.isLong) { // if double final, then loser moves to the bottom return [gId(LB, 2 * p, 1), 1]; } // otherwise always KO'd if loosing in >= last bracket return null; } // WBR1 always feeds into LBR1 as if it were WBR2 if (r === 1) { return [gId(LB, 1, Math.floor((g+1)/2)), g % 2]; } if (this.downMix) { // always drop on top when downmixing return [gId(LB, (r-1)*2, mixLbGames(p, r, g)), 0]; } // normal LB drops: on top for (r>2) and (r<=2 if odd g) to match bracket movement var pos = (r > 2 || $.odd(g)) ? 0 : 1; return [gId(LB, (r-1)*2, g), pos]; }
[ "function", "(", "id", ")", "{", "var", "b", "=", "id", ".", "s", ",", "r", "=", "id", ".", "r", ",", "g", "=", "id", ".", "m", ",", "p", "=", "this", ".", "p", ";", "// knockouts / special finals", "if", "(", "b", ">=", "this", ".", "last", ")", "{", "// greater than case is for BF in long single elimination", "if", "(", "b", "===", "WB", "&&", "this", ".", "isLong", "&&", "r", "===", "p", "-", "1", ")", "{", "// if bronze final, move loser to \"LBR1\" at mirror pos of WBGF", "return", "[", "gId", "(", "LB", ",", "1", ",", "1", ")", ",", "(", "g", "+", "1", ")", "%", "2", "]", ";", "}", "if", "(", "b", "===", "LB", "&&", "r", "===", "2", "*", "p", "-", "1", "&&", "this", ".", "isLong", ")", "{", "// if double final, then loser moves to the bottom", "return", "[", "gId", "(", "LB", ",", "2", "*", "p", ",", "1", ")", ",", "1", "]", ";", "}", "// otherwise always KO'd if loosing in >= last bracket", "return", "null", ";", "}", "// WBR1 always feeds into LBR1 as if it were WBR2", "if", "(", "r", "===", "1", ")", "{", "return", "[", "gId", "(", "LB", ",", "1", ",", "Math", ".", "floor", "(", "(", "g", "+", "1", ")", "/", "2", ")", ")", ",", "g", "%", "2", "]", ";", "}", "if", "(", "this", ".", "downMix", ")", "{", "// always drop on top when downmixing", "return", "[", "gId", "(", "LB", ",", "(", "r", "-", "1", ")", "*", "2", ",", "mixLbGames", "(", "p", ",", "r", ",", "g", ")", ")", ",", "0", "]", ";", "}", "// normal LB drops: on top for (r>2) and (r<=2 if odd g) to match bracket movement", "var", "pos", "=", "(", "r", ">", "2", "||", "$", ".", "odd", "(", "g", ")", ")", "?", "0", ":", "1", ";", "return", "[", "gId", "(", "LB", ",", "(", "r", "-", "1", ")", "*", "2", ",", "g", ")", ",", "pos", "]", ";", "}" ]
find the match and position a loser should move "down" to in the current bracket
[ "find", "the", "match", "and", "position", "a", "loser", "should", "move", "down", "to", "in", "the", "current", "bracket" ]
0482733bb19bd6dfe8ae807306da8641020ca6b2
https://github.com/clux/duel/blob/0482733bb19bd6dfe8ae807306da8641020ca6b2/duel.js#L164-L197
41,224
clux/duel
duel.js
function (progressFn, m) { var idx = m.p.indexOf(WO); if (idx >= 0) { // set scores manually to avoid the `_verify` walkover scoring restriction m.m = (idx === 0) ? [0, 1] : [1, 0]; progressFn(m); } }
javascript
function (progressFn, m) { var idx = m.p.indexOf(WO); if (idx >= 0) { // set scores manually to avoid the `_verify` walkover scoring restriction m.m = (idx === 0) ? [0, 1] : [1, 0]; progressFn(m); } }
[ "function", "(", "progressFn", ",", "m", ")", "{", "var", "idx", "=", "m", ".", "p", ".", "indexOf", "(", "WO", ")", ";", "if", "(", "idx", ">=", "0", ")", "{", "// set scores manually to avoid the `_verify` walkover scoring restriction", "m", ".", "m", "=", "(", "idx", "===", "0", ")", "?", "[", "0", ",", "1", "]", ":", "[", "1", ",", "0", "]", ";", "progressFn", "(", "m", ")", ";", "}", "}" ]
helper to initially score matches with walkovers correctly
[ "helper", "to", "initially", "score", "matches", "with", "walkovers", "correctly" ]
0482733bb19bd6dfe8ae807306da8641020ca6b2
https://github.com/clux/duel/blob/0482733bb19bd6dfe8ae807306da8641020ca6b2/duel.js#L219-L226
41,225
basic-web-components/basic-web-components
packages/basic-current-anchor/src/CurrentAnchor.js
refresh
function refresh(element) { const url = window.location.href; let match; if (element.areaLink) { // Match prefix let prefix = element.href; // If prefix doesn't end in slash, add a slash. // We want to avoid matching in the middle of a folder name. if (prefix.length < url.length && prefix.substr(-1) !== '/') { prefix += '/'; } match = (url.substr(0, prefix.length) === prefix); } else { // Match whole path match = (url === element.href); } element.current = match; }
javascript
function refresh(element) { const url = window.location.href; let match; if (element.areaLink) { // Match prefix let prefix = element.href; // If prefix doesn't end in slash, add a slash. // We want to avoid matching in the middle of a folder name. if (prefix.length < url.length && prefix.substr(-1) !== '/') { prefix += '/'; } match = (url.substr(0, prefix.length) === prefix); } else { // Match whole path match = (url === element.href); } element.current = match; }
[ "function", "refresh", "(", "element", ")", "{", "const", "url", "=", "window", ".", "location", ".", "href", ";", "let", "match", ";", "if", "(", "element", ".", "areaLink", ")", "{", "// Match prefix", "let", "prefix", "=", "element", ".", "href", ";", "// If prefix doesn't end in slash, add a slash.", "// We want to avoid matching in the middle of a folder name.", "if", "(", "prefix", ".", "length", "<", "url", ".", "length", "&&", "prefix", ".", "substr", "(", "-", "1", ")", "!==", "'/'", ")", "{", "prefix", "+=", "'/'", ";", "}", "match", "=", "(", "url", ".", "substr", "(", "0", ",", "prefix", ".", "length", ")", "===", "prefix", ")", ";", "}", "else", "{", "// Match whole path", "match", "=", "(", "url", "===", "element", ".", "href", ")", ";", "}", "element", ".", "current", "=", "match", ";", "}" ]
Update the current status of the element based on the current location.
[ "Update", "the", "current", "status", "of", "the", "element", "based", "on", "the", "current", "location", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-current-anchor/src/CurrentAnchor.js#L131-L148
41,226
basic-web-components/basic-web-components
packages/basic-component-mixins/src/SingleSelectionMixin.js
selectIndex
function selectIndex(element, index) { const count = element.items.length; const boundedIndex = (element.selectionWraps) ? // JavaScript mod doesn't handle negative numbers the way we want to wrap. // See http://stackoverflow.com/a/18618250/76472 ((index % count) + count) % count : // Keep index within bounds of array. Math.max(Math.min(index, count - 1), 0); const previousIndex = element.selectedIndex; if (previousIndex !== boundedIndex) { element.selectedIndex = boundedIndex; return true; } else { return false; } }
javascript
function selectIndex(element, index) { const count = element.items.length; const boundedIndex = (element.selectionWraps) ? // JavaScript mod doesn't handle negative numbers the way we want to wrap. // See http://stackoverflow.com/a/18618250/76472 ((index % count) + count) % count : // Keep index within bounds of array. Math.max(Math.min(index, count - 1), 0); const previousIndex = element.selectedIndex; if (previousIndex !== boundedIndex) { element.selectedIndex = boundedIndex; return true; } else { return false; } }
[ "function", "selectIndex", "(", "element", ",", "index", ")", "{", "const", "count", "=", "element", ".", "items", ".", "length", ";", "const", "boundedIndex", "=", "(", "element", ".", "selectionWraps", ")", "?", "// JavaScript mod doesn't handle negative numbers the way we want to wrap.", "// See http://stackoverflow.com/a/18618250/76472", "(", "(", "index", "%", "count", ")", "+", "count", ")", "%", "count", ":", "// Keep index within bounds of array.", "Math", ".", "max", "(", "Math", ".", "min", "(", "index", ",", "count", "-", "1", ")", ",", "0", ")", ";", "const", "previousIndex", "=", "element", ".", "selectedIndex", ";", "if", "(", "previousIndex", "!==", "boundedIndex", ")", "{", "element", ".", "selectedIndex", "=", "boundedIndex", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Ensure the given index is within bounds, and select it if it's not already selected.
[ "Ensure", "the", "given", "index", "is", "within", "bounds", "and", "select", "it", "if", "it", "s", "not", "already", "selected", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/SingleSelectionMixin.js#L361-L379
41,227
basic-web-components/basic-web-components
packages/basic-component-mixins/src/SingleSelectionMixin.js
trackSelectedItem
function trackSelectedItem(element) { const items = element.items; const itemCount = items ? items.length : 0; const previousSelectedItem = element.selectedItem; if (!previousSelectedItem) { // No item was previously selected. if (element.selectionRequired) { // Select the first item by default. element.selectedIndex = 0; } } else if (itemCount === 0) { // We've lost the selection, and there's nothing left to select. element.selectedItem = null; } else { // Try to find the previously-selected item in the current set of items. const indexInCurrentItems = Array.prototype.indexOf.call(items, previousSelectedItem); const previousSelectedIndex = element.selectedIndex; if (indexInCurrentItems < 0) { // Previously-selected item was removed from the items. // Select the item at the same index (if it exists) or as close as possible. const newSelectedIndex = Math.min(previousSelectedIndex, itemCount - 1); // Select by item, since index may be the same, and we want to raise the // selected-item-changed event. element.selectedItem = items[newSelectedIndex]; } else if (indexInCurrentItems !== previousSelectedIndex) { // Previously-selected item still there, but changed position. element.selectedIndex = indexInCurrentItems; } } }
javascript
function trackSelectedItem(element) { const items = element.items; const itemCount = items ? items.length : 0; const previousSelectedItem = element.selectedItem; if (!previousSelectedItem) { // No item was previously selected. if (element.selectionRequired) { // Select the first item by default. element.selectedIndex = 0; } } else if (itemCount === 0) { // We've lost the selection, and there's nothing left to select. element.selectedItem = null; } else { // Try to find the previously-selected item in the current set of items. const indexInCurrentItems = Array.prototype.indexOf.call(items, previousSelectedItem); const previousSelectedIndex = element.selectedIndex; if (indexInCurrentItems < 0) { // Previously-selected item was removed from the items. // Select the item at the same index (if it exists) or as close as possible. const newSelectedIndex = Math.min(previousSelectedIndex, itemCount - 1); // Select by item, since index may be the same, and we want to raise the // selected-item-changed event. element.selectedItem = items[newSelectedIndex]; } else if (indexInCurrentItems !== previousSelectedIndex) { // Previously-selected item still there, but changed position. element.selectedIndex = indexInCurrentItems; } } }
[ "function", "trackSelectedItem", "(", "element", ")", "{", "const", "items", "=", "element", ".", "items", ";", "const", "itemCount", "=", "items", "?", "items", ".", "length", ":", "0", ";", "const", "previousSelectedItem", "=", "element", ".", "selectedItem", ";", "if", "(", "!", "previousSelectedItem", ")", "{", "// No item was previously selected.", "if", "(", "element", ".", "selectionRequired", ")", "{", "// Select the first item by default.", "element", ".", "selectedIndex", "=", "0", ";", "}", "}", "else", "if", "(", "itemCount", "===", "0", ")", "{", "// We've lost the selection, and there's nothing left to select.", "element", ".", "selectedItem", "=", "null", ";", "}", "else", "{", "// Try to find the previously-selected item in the current set of items.", "const", "indexInCurrentItems", "=", "Array", ".", "prototype", ".", "indexOf", ".", "call", "(", "items", ",", "previousSelectedItem", ")", ";", "const", "previousSelectedIndex", "=", "element", ".", "selectedIndex", ";", "if", "(", "indexInCurrentItems", "<", "0", ")", "{", "// Previously-selected item was removed from the items.", "// Select the item at the same index (if it exists) or as close as possible.", "const", "newSelectedIndex", "=", "Math", ".", "min", "(", "previousSelectedIndex", ",", "itemCount", "-", "1", ")", ";", "// Select by item, since index may be the same, and we want to raise the", "// selected-item-changed event.", "element", ".", "selectedItem", "=", "items", "[", "newSelectedIndex", "]", ";", "}", "else", "if", "(", "indexInCurrentItems", "!==", "previousSelectedIndex", ")", "{", "// Previously-selected item still there, but changed position.", "element", ".", "selectedIndex", "=", "indexInCurrentItems", ";", "}", "}", "}" ]
Following a change in the set of items, or in the value of the `selectionRequired` property, reacquire the selected item. If it's moved, update `selectedIndex`. If it's been removed, and a selection is required, try to select another item.
[ "Following", "a", "change", "in", "the", "set", "of", "items", "or", "in", "the", "value", "of", "the", "selectionRequired", "property", "reacquire", "the", "selected", "item", ".", "If", "it", "s", "moved", "update", "selectedIndex", ".", "If", "it", "s", "been", "removed", "and", "a", "selection", "is", "required", "try", "to", "select", "another", "item", "." ]
1dd0e353da13e208777c022380c2d8056c041c0c
https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/SingleSelectionMixin.js#L385-L416
41,228
devpaul/grunt-devserver
lib/commands/loadCompleteOptionsCmd.js
loadCompleteOptionsCmd
function loadCompleteOptionsCmd(options) { if(!options || typeof options !== 'object') throw new Error('expected options object') if(!options.getOptions) options = new BasicOptions(options) return options.file ? new CompositeOptions([new MultiOptions(options.file), options]) : options }
javascript
function loadCompleteOptionsCmd(options) { if(!options || typeof options !== 'object') throw new Error('expected options object') if(!options.getOptions) options = new BasicOptions(options) return options.file ? new CompositeOptions([new MultiOptions(options.file), options]) : options }
[ "function", "loadCompleteOptionsCmd", "(", "options", ")", "{", "if", "(", "!", "options", "||", "typeof", "options", "!==", "'object'", ")", "throw", "new", "Error", "(", "'expected options object'", ")", "if", "(", "!", "options", ".", "getOptions", ")", "options", "=", "new", "BasicOptions", "(", "options", ")", "return", "options", ".", "file", "?", "new", "CompositeOptions", "(", "[", "new", "MultiOptions", "(", "options", ".", "file", ")", ",", "options", "]", ")", ":", "options", "}" ]
Loads a complete set of configuration options. If the options passed to the command contains a reference to an options file then options will be loaded and merged with the original options and a new options object is returned representing the full and complete options of the system. NOTE that recursive loading of options files is not supported to maintain simplicity. A strong use case is not apparent for the recursive scenario. @param options an object literal containing user defined options @returns CompositeObject
[ "Loads", "a", "complete", "set", "of", "configuration", "options", ".", "If", "the", "options", "passed", "to", "the", "command", "contains", "a", "reference", "to", "an", "options", "file", "then", "options", "will", "be", "loaded", "and", "merged", "with", "the", "original", "options", "and", "a", "new", "options", "object", "is", "returned", "representing", "the", "full", "and", "complete", "options", "of", "the", "system", "." ]
934f1c5a51db8cc176fec9d6e58dd9f20d47b347
https://github.com/devpaul/grunt-devserver/blob/934f1c5a51db8cc176fec9d6e58dd9f20d47b347/lib/commands/loadCompleteOptionsCmd.js#L16-L24
41,229
devpaul/grunt-devserver
lib/model/config/HttpsConfig.js
HttpsConfig
function HttpsConfig(options) { var httpsOptions = options && options.httpsOptions underscore.extend(this, HttpsConfig._DEFAULT) CommonConfig.call(this, options) this.httpsOptions = applyHttpsOptions.call(this, httpsOptions) this.type = serverTypes.HTTPS }
javascript
function HttpsConfig(options) { var httpsOptions = options && options.httpsOptions underscore.extend(this, HttpsConfig._DEFAULT) CommonConfig.call(this, options) this.httpsOptions = applyHttpsOptions.call(this, httpsOptions) this.type = serverTypes.HTTPS }
[ "function", "HttpsConfig", "(", "options", ")", "{", "var", "httpsOptions", "=", "options", "&&", "options", ".", "httpsOptions", "underscore", ".", "extend", "(", "this", ",", "HttpsConfig", ".", "_DEFAULT", ")", "CommonConfig", ".", "call", "(", "this", ",", "options", ")", "this", ".", "httpsOptions", "=", "applyHttpsOptions", ".", "call", "(", "this", ",", "httpsOptions", ")", "this", ".", "type", "=", "serverTypes", ".", "HTTPS", "}" ]
Configuration for a HTTPS server @param options @constructor
[ "Configuration", "for", "a", "HTTPS", "server" ]
934f1c5a51db8cc176fec9d6e58dd9f20d47b347
https://github.com/devpaul/grunt-devserver/blob/934f1c5a51db8cc176fec9d6e58dd9f20d47b347/lib/model/config/HttpsConfig.js#L12-L19
41,230
patrick-steele-idem/async-config
src/async-config.js
getEnvironment
function getEnvironment (options) { var env; if (options.environment) { env = options.environment; } else { env = process.env.NODE_ENV; } if (env) { if (env === 'prod') { env = 'production'; } else if (env === 'dev') { env = 'development'; } } else { // Default to "development" env = 'development'; } return env; }
javascript
function getEnvironment (options) { var env; if (options.environment) { env = options.environment; } else { env = process.env.NODE_ENV; } if (env) { if (env === 'prod') { env = 'production'; } else if (env === 'dev') { env = 'development'; } } else { // Default to "development" env = 'development'; } return env; }
[ "function", "getEnvironment", "(", "options", ")", "{", "var", "env", ";", "if", "(", "options", ".", "environment", ")", "{", "env", "=", "options", ".", "environment", ";", "}", "else", "{", "env", "=", "process", ".", "env", ".", "NODE_ENV", ";", "}", "if", "(", "env", ")", "{", "if", "(", "env", "===", "'prod'", ")", "{", "env", "=", "'production'", ";", "}", "else", "if", "(", "env", "===", "'dev'", ")", "{", "env", "=", "'development'", ";", "}", "}", "else", "{", "// Default to \"development\"", "env", "=", "'development'", ";", "}", "return", "env", ";", "}" ]
Determine the environment from the provided options and the NODE_ENV environment variable. Also normalize the environment name such that "prod" becomes "production" and "dev" becomes "development".
[ "Determine", "the", "environment", "from", "the", "provided", "options", "and", "the", "NODE_ENV", "environment", "variable", ".", "Also", "normalize", "the", "environment", "name", "such", "that", "prod", "becomes", "production", "and", "dev", "becomes", "development", "." ]
3c3447aded373eb6aafd5894a0c3474d8b4302ba
https://github.com/patrick-steele-idem/async-config/blob/3c3447aded373eb6aafd5894a0c3474d8b4302ba/src/async-config.js#L91-L112
41,231
patrick-steele-idem/async-config
src/async-config.js
loadSources
async function loadSources (sources, options) { const mergedConfig = {}; function handleSourceLoad (sourceConfig) { if (sourceConfig) merge(sourceConfig, mergedConfig); } for (const source of sources) { let sourceConfig; if (source == null) { // No-op... skip this source continue; } else if (typeof source === 'string') { // Load a source from a JSON file sourceConfig = await loadFileSource(source, options); } else if (Array.isArray(source)) { sourceConfig = await loadSources(source, options); // Load and merge all of the sources } else if (typeof source === 'function') { sourceConfig = await source(); // Invoke the function to asynchronously load the config object for this source } else if (typeof source === 'object') { sourceConfig = source; // Just merge the object } else { throw new Error('Invalid configuration source: ' + source); } handleSourceLoad(sourceConfig); } return mergedConfig; }
javascript
async function loadSources (sources, options) { const mergedConfig = {}; function handleSourceLoad (sourceConfig) { if (sourceConfig) merge(sourceConfig, mergedConfig); } for (const source of sources) { let sourceConfig; if (source == null) { // No-op... skip this source continue; } else if (typeof source === 'string') { // Load a source from a JSON file sourceConfig = await loadFileSource(source, options); } else if (Array.isArray(source)) { sourceConfig = await loadSources(source, options); // Load and merge all of the sources } else if (typeof source === 'function') { sourceConfig = await source(); // Invoke the function to asynchronously load the config object for this source } else if (typeof source === 'object') { sourceConfig = source; // Just merge the object } else { throw new Error('Invalid configuration source: ' + source); } handleSourceLoad(sourceConfig); } return mergedConfig; }
[ "async", "function", "loadSources", "(", "sources", ",", "options", ")", "{", "const", "mergedConfig", "=", "{", "}", ";", "function", "handleSourceLoad", "(", "sourceConfig", ")", "{", "if", "(", "sourceConfig", ")", "merge", "(", "sourceConfig", ",", "mergedConfig", ")", ";", "}", "for", "(", "const", "source", "of", "sources", ")", "{", "let", "sourceConfig", ";", "if", "(", "source", "==", "null", ")", "{", "// No-op... skip this source", "continue", ";", "}", "else", "if", "(", "typeof", "source", "===", "'string'", ")", "{", "// Load a source from a JSON file", "sourceConfig", "=", "await", "loadFileSource", "(", "source", ",", "options", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "source", ")", ")", "{", "sourceConfig", "=", "await", "loadSources", "(", "source", ",", "options", ")", ";", "// Load and merge all of the sources", "}", "else", "if", "(", "typeof", "source", "===", "'function'", ")", "{", "sourceConfig", "=", "await", "source", "(", ")", ";", "// Invoke the function to asynchronously load the config object for this source", "}", "else", "if", "(", "typeof", "source", "===", "'object'", ")", "{", "sourceConfig", "=", "source", ";", "// Just merge the object", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid configuration source: '", "+", "source", ")", ";", "}", "handleSourceLoad", "(", "sourceConfig", ")", ";", "}", "return", "mergedConfig", ";", "}" ]
Asynchronously load all of the configuration objects from the various sources.
[ "Asynchronously", "load", "all", "of", "the", "configuration", "objects", "from", "the", "various", "sources", "." ]
3c3447aded373eb6aafd5894a0c3474d8b4302ba
https://github.com/patrick-steele-idem/async-config/blob/3c3447aded373eb6aafd5894a0c3474d8b4302ba/src/async-config.js#L186-L216
41,232
devpaul/grunt-devserver
lib/model/config/HttpConfig.js
HttpConfig
function HttpConfig(options) { underscore.extend(this, HttpConfig._DEFAULT) CommonConfig.call(this, options) this.type = serverTypes.HTTP }
javascript
function HttpConfig(options) { underscore.extend(this, HttpConfig._DEFAULT) CommonConfig.call(this, options) this.type = serverTypes.HTTP }
[ "function", "HttpConfig", "(", "options", ")", "{", "underscore", ".", "extend", "(", "this", ",", "HttpConfig", ".", "_DEFAULT", ")", "CommonConfig", ".", "call", "(", "this", ",", "options", ")", "this", ".", "type", "=", "serverTypes", ".", "HTTP", "}" ]
Configuration for a HTTP server @constructor
[ "Configuration", "for", "a", "HTTP", "server" ]
934f1c5a51db8cc176fec9d6e58dd9f20d47b347
https://github.com/devpaul/grunt-devserver/blob/934f1c5a51db8cc176fec9d6e58dd9f20d47b347/lib/model/config/HttpConfig.js#L9-L13
41,233
avajs/karma-ava
lib/babel-transform.js
Babelify
function Babelify(filename, babelConfig) { stream.Transform.call(this); this._data = ''; this._filename = filename; this._babelConfig = babelConfig; }
javascript
function Babelify(filename, babelConfig) { stream.Transform.call(this); this._data = ''; this._filename = filename; this._babelConfig = babelConfig; }
[ "function", "Babelify", "(", "filename", ",", "babelConfig", ")", "{", "stream", ".", "Transform", ".", "call", "(", "this", ")", ";", "this", ".", "_data", "=", "''", ";", "this", ".", "_filename", "=", "filename", ";", "this", ".", "_babelConfig", "=", "babelConfig", ";", "}" ]
copied from Babelify - modified so we can embed source maps
[ "copied", "from", "Babelify", "-", "modified", "so", "we", "can", "embed", "source", "maps" ]
8a584a9fdcb17b276806ebc4b7129cd8b9810fcf
https://github.com/avajs/karma-ava/blob/8a584a9fdcb17b276806ebc4b7129cd8b9810fcf/lib/babel-transform.js#L22-L27
41,234
devpaul/grunt-devserver
lib/commands/buildServerCmd.js
buildServerCmd
function buildServerCmd(config) { var deferred = Q.defer() , app try { assertConfig(config) app = createMiddleware(config) createServer(config, app).then(onServerCreated, deferred.reject) } catch(error) { deferred.reject(error) } return deferred.promise function onServerCreated(server) { deferred.resolve(new Server(config, server, app)) } }
javascript
function buildServerCmd(config) { var deferred = Q.defer() , app try { assertConfig(config) app = createMiddleware(config) createServer(config, app).then(onServerCreated, deferred.reject) } catch(error) { deferred.reject(error) } return deferred.promise function onServerCreated(server) { deferred.resolve(new Server(config, server, app)) } }
[ "function", "buildServerCmd", "(", "config", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ",", "app", "try", "{", "assertConfig", "(", "config", ")", "app", "=", "createMiddleware", "(", "config", ")", "createServer", "(", "config", ",", "app", ")", ".", "then", "(", "onServerCreated", ",", "deferred", ".", "reject", ")", "}", "catch", "(", "error", ")", "{", "deferred", ".", "reject", "(", "error", ")", "}", "return", "deferred", ".", "promise", "function", "onServerCreated", "(", "server", ")", "{", "deferred", ".", "resolve", "(", "new", "Server", "(", "config", ",", "server", ",", "app", ")", ")", "}", "}" ]
Builds a Server wrapper interface from a config to provide basic standard controls for varying server types @param config {HttpConfig|HttpsConfig} a supported configuration for building a server @returns {Q.promise}
[ "Builds", "a", "Server", "wrapper", "interface", "from", "a", "config", "to", "provide", "basic", "standard", "controls", "for", "varying", "server", "types" ]
934f1c5a51db8cc176fec9d6e58dd9f20d47b347
https://github.com/devpaul/grunt-devserver/blob/934f1c5a51db8cc176fec9d6e58dd9f20d47b347/lib/commands/buildServerCmd.js#L15-L32
41,235
devpaul/grunt-devserver
lib/commands/startServerCmd.js
startServerCmd
function startServerCmd(options) { var deferred = Q.defer() var config try { options = loadOptions(options) config = buildConfigFromOptions(options) buildServer(config).then(onServerBuilt, onServerBuildFailed) } catch(error) { deferred.reject(error) } return deferred.promise function onServerBuilt(server) { server.start().then(deferred.resolve, onServerStartFailed) } function onServerBuildFailed(error) { var msg = (error && error.message) || 'of no good reason' console.error('failed to build server because ' + msg) deferred.reject(error) } function onServerStartFailed(error) { var msg = (error && error.message) || 'of no good reason' console.error('failed to start server becaue ' + msg) deferred.reject(error) } }
javascript
function startServerCmd(options) { var deferred = Q.defer() var config try { options = loadOptions(options) config = buildConfigFromOptions(options) buildServer(config).then(onServerBuilt, onServerBuildFailed) } catch(error) { deferred.reject(error) } return deferred.promise function onServerBuilt(server) { server.start().then(deferred.resolve, onServerStartFailed) } function onServerBuildFailed(error) { var msg = (error && error.message) || 'of no good reason' console.error('failed to build server because ' + msg) deferred.reject(error) } function onServerStartFailed(error) { var msg = (error && error.message) || 'of no good reason' console.error('failed to start server becaue ' + msg) deferred.reject(error) } }
[ "function", "startServerCmd", "(", "options", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", "var", "config", "try", "{", "options", "=", "loadOptions", "(", "options", ")", "config", "=", "buildConfigFromOptions", "(", "options", ")", "buildServer", "(", "config", ")", ".", "then", "(", "onServerBuilt", ",", "onServerBuildFailed", ")", "}", "catch", "(", "error", ")", "{", "deferred", ".", "reject", "(", "error", ")", "}", "return", "deferred", ".", "promise", "function", "onServerBuilt", "(", "server", ")", "{", "server", ".", "start", "(", ")", ".", "then", "(", "deferred", ".", "resolve", ",", "onServerStartFailed", ")", "}", "function", "onServerBuildFailed", "(", "error", ")", "{", "var", "msg", "=", "(", "error", "&&", "error", ".", "message", ")", "||", "'of no good reason'", "console", ".", "error", "(", "'failed to build server because '", "+", "msg", ")", "deferred", ".", "reject", "(", "error", ")", "}", "function", "onServerStartFailed", "(", "error", ")", "{", "var", "msg", "=", "(", "error", "&&", "error", ".", "message", ")", "||", "'of no good reason'", "console", ".", "error", "(", "'failed to start server becaue '", "+", "msg", ")", "deferred", ".", "reject", "(", "error", ")", "}", "}" ]
Given a set of options starts a server @param options a set of options @returns {Q.promise} a promise notifying of server start
[ "Given", "a", "set", "of", "options", "starts", "a", "server" ]
934f1c5a51db8cc176fec9d6e58dd9f20d47b347
https://github.com/devpaul/grunt-devserver/blob/934f1c5a51db8cc176fec9d6e58dd9f20d47b347/lib/commands/startServerCmd.js#L11-L41
41,236
spanishdict/node-google-dfp-wrapper
lib/dfp.js
_makeQuery
function _makeQuery(conditions, fields) { // build up 'Where' string var query = fields.reduce(function(condition, field) { var addition = ''; var val = conditions[field]; var isNumber = typeof val === 'number'; if (val) { addition += field; if (isNumber) { addition += '='; } else { addition += ' like \''; } addition += val; if (!isNumber) { addition += '\''; } addition += ' and '; } return condition + addition; }, 'Where '); // remove final 'and' query = query.replace(/ and $/, ''); return new nodeGoogleDfp.Statement(query); }
javascript
function _makeQuery(conditions, fields) { // build up 'Where' string var query = fields.reduce(function(condition, field) { var addition = ''; var val = conditions[field]; var isNumber = typeof val === 'number'; if (val) { addition += field; if (isNumber) { addition += '='; } else { addition += ' like \''; } addition += val; if (!isNumber) { addition += '\''; } addition += ' and '; } return condition + addition; }, 'Where '); // remove final 'and' query = query.replace(/ and $/, ''); return new nodeGoogleDfp.Statement(query); }
[ "function", "_makeQuery", "(", "conditions", ",", "fields", ")", "{", "// build up 'Where' string", "var", "query", "=", "fields", ".", "reduce", "(", "function", "(", "condition", ",", "field", ")", "{", "var", "addition", "=", "''", ";", "var", "val", "=", "conditions", "[", "field", "]", ";", "var", "isNumber", "=", "typeof", "val", "===", "'number'", ";", "if", "(", "val", ")", "{", "addition", "+=", "field", ";", "if", "(", "isNumber", ")", "{", "addition", "+=", "'='", ";", "}", "else", "{", "addition", "+=", "' like \\''", ";", "}", "addition", "+=", "val", ";", "if", "(", "!", "isNumber", ")", "{", "addition", "+=", "'\\''", ";", "}", "addition", "+=", "' and '", ";", "}", "return", "condition", "+", "addition", ";", "}", ",", "'Where '", ")", ";", "// remove final 'and'", "query", "=", "query", ".", "replace", "(", "/", " and $", "/", ",", "''", ")", ";", "return", "new", "nodeGoogleDfp", ".", "Statement", "(", "query", ")", ";", "}" ]
Converts an object of conditions and possible query fields into a node-google-dfp statement to query DFP. @param {Object} conditions An object of the properties you'd like to query and the values you'd like them to contain. @param {Array} fields All the fields it is possible to query, as detailed in the DFP api. @return {Object} node-google-dfp statement.
[ "Converts", "an", "object", "of", "conditions", "and", "possible", "query", "fields", "into", "a", "node", "-", "google", "-", "dfp", "statement", "to", "query", "DFP", "." ]
3f46f73c1c0bc28968473043e759c8bb57f67eda
https://github.com/spanishdict/node-google-dfp-wrapper/blob/3f46f73c1c0bc28968473043e759c8bb57f67eda/lib/dfp.js#L165-L193
41,237
spanishdict/node-google-dfp-wrapper
lib/dfp.js
_lookupKeyInPair
function _lookupKeyInPair(pair) { var key = pair[0]; var value = pair[1]; return Bluebird.all([ this.lookupCriteriaKey(key), value ]); }
javascript
function _lookupKeyInPair(pair) { var key = pair[0]; var value = pair[1]; return Bluebird.all([ this.lookupCriteriaKey(key), value ]); }
[ "function", "_lookupKeyInPair", "(", "pair", ")", "{", "var", "key", "=", "pair", "[", "0", "]", ";", "var", "value", "=", "pair", "[", "1", "]", ";", "return", "Bluebird", ".", "all", "(", "[", "this", ".", "lookupCriteriaKey", "(", "key", ")", ",", "value", "]", ")", ";", "}" ]
Query DFP for the key id of a key value pair. @param {Array} pair [0] The name of a key. [1] The name of a value. @return {Promise} Resolves with an Array [0] The dfp id of the key passed in. [1] The name of value passed in (unchanged).
[ "Query", "DFP", "for", "the", "key", "id", "of", "a", "key", "value", "pair", "." ]
3f46f73c1c0bc28968473043e759c8bb57f67eda
https://github.com/spanishdict/node-google-dfp-wrapper/blob/3f46f73c1c0bc28968473043e759c8bb57f67eda/lib/dfp.js#L421-L428
41,238
spanishdict/node-google-dfp-wrapper
lib/dfp.js
_lookupValueInPair
function _lookupValueInPair(pair) { var keyId = pair[0]; var value = pair[1]; return Bluebird.all([ keyId, this.lookupCriteriaValues(value, keyId) ]); }
javascript
function _lookupValueInPair(pair) { var keyId = pair[0]; var value = pair[1]; return Bluebird.all([ keyId, this.lookupCriteriaValues(value, keyId) ]); }
[ "function", "_lookupValueInPair", "(", "pair", ")", "{", "var", "keyId", "=", "pair", "[", "0", "]", ";", "var", "value", "=", "pair", "[", "1", "]", ";", "return", "Bluebird", ".", "all", "(", "[", "keyId", ",", "this", ".", "lookupCriteriaValues", "(", "value", ",", "keyId", ")", "]", ")", ";", "}" ]
Query DFP for the value id of a key value pair. @param {Array} pair [0] The id of a key. [1] The name of a value. @return {Promise} Resolves with an Array [0] The dfp id of the key passed in (unchanged). [1] The dfp id of value passed in.
[ "Query", "DFP", "for", "the", "value", "id", "of", "a", "key", "value", "pair", "." ]
3f46f73c1c0bc28968473043e759c8bb57f67eda
https://github.com/spanishdict/node-google-dfp-wrapper/blob/3f46f73c1c0bc28968473043e759c8bb57f67eda/lib/dfp.js#L439-L446
41,239
spanishdict/node-google-dfp-wrapper
lib/dfp.js
_convertPairToObject
function _convertPairToObject(pair) { var keyId = pair[0]; var valueIds = pair[1]; return { keyId: keyId, valueIds: valueIds }; }
javascript
function _convertPairToObject(pair) { var keyId = pair[0]; var valueIds = pair[1]; return { keyId: keyId, valueIds: valueIds }; }
[ "function", "_convertPairToObject", "(", "pair", ")", "{", "var", "keyId", "=", "pair", "[", "0", "]", ";", "var", "valueIds", "=", "pair", "[", "1", "]", ";", "return", "{", "keyId", ":", "keyId", ",", "valueIds", ":", "valueIds", "}", ";", "}" ]
Convert an array of DFP key and value ids to an object. @param {Array} pair [0] The id of a key. [1] The id of a value. @return {Object} An object of the ids.
[ "Convert", "an", "array", "of", "DFP", "key", "and", "value", "ids", "to", "an", "object", "." ]
3f46f73c1c0bc28968473043e759c8bb57f67eda
https://github.com/spanishdict/node-google-dfp-wrapper/blob/3f46f73c1c0bc28968473043e759c8bb57f67eda/lib/dfp.js#L455-L462
41,240
mbroadst/thinkagain
old/lib/schema.js
validate
function validate(doc, schema, prefix, options) { schema.validate(doc, prefix, options); }
javascript
function validate(doc, schema, prefix, options) { schema.validate(doc, prefix, options); }
[ "function", "validate", "(", "doc", ",", "schema", ",", "prefix", ",", "options", ")", "{", "schema", ".", "validate", "(", "doc", ",", "prefix", ",", "options", ")", ";", "}" ]
The schema doesn't contain joined docs
[ "The", "schema", "doesn", "t", "contain", "joined", "docs" ]
0aa6d3e82019530ce847083cd64e811aed63b36c
https://github.com/mbroadst/thinkagain/blob/0aa6d3e82019530ce847083cd64e811aed63b36c/old/lib/schema.js#L269-L271
41,241
wilmoore/request-id.js
defaults.js
defaults
function defaults(options) { options = options || {}; return { reqHeader: options.reqHeader || 'X-Request-Id', resHeader: options.resHeader || 'X-Request-Id', paramName: options.paramName || 'requestId', generator: options.generator || uuid }; }
javascript
function defaults(options) { options = options || {}; return { reqHeader: options.reqHeader || 'X-Request-Id', resHeader: options.resHeader || 'X-Request-Id', paramName: options.paramName || 'requestId', generator: options.generator || uuid }; }
[ "function", "defaults", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "return", "{", "reqHeader", ":", "options", ".", "reqHeader", "||", "'X-Request-Id'", ",", "resHeader", ":", "options", ".", "resHeader", "||", "'X-Request-Id'", ",", "paramName", ":", "options", ".", "paramName", "||", "'requestId'", ",", "generator", ":", "options", ".", "generator", "||", "uuid", "}", ";", "}" ]
Initialize Default Options. @param {Object} options Optional configuraiton. @param {String} [options.reqHeader='X-Request-Id'] Request Header Name. @param {String} [options.resHeader='X-Request-Id'] Response Header Name. @param {String} [options.paramName='requestId'] Query Parameter. @param {Function} [options.generator=uuid] Generator Function. @return {Object} Optional configuration.
[ "Initialize", "Default", "Options", "." ]
65c940e78b607d474c1dd988703e7a1c310e96f6
https://github.com/wilmoore/request-id.js/blob/65c940e78b607d474c1dd988703e7a1c310e96f6/defaults.js#L37-L46
41,242
danigb/music-pitch
index.js
parseDecorator
function parseDecorator (fn) { return function (pitch) { var p = asArray(pitch) return p ? fn(p) : null } }
javascript
function parseDecorator (fn) { return function (pitch) { var p = asArray(pitch) return p ? fn(p) : null } }
[ "function", "parseDecorator", "(", "fn", ")", "{", "return", "function", "(", "pitch", ")", "{", "var", "p", "=", "asArray", "(", "pitch", ")", "return", "p", "?", "fn", "(", "p", ")", ":", "null", "}", "}" ]
decorate a function to force the param to be an array-pitch
[ "decorate", "a", "function", "to", "force", "the", "param", "to", "be", "an", "array", "-", "pitch" ]
2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b
https://github.com/danigb/music-pitch/blob/2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b/index.js#L11-L16
41,243
danigb/music-pitch
index.js
str
function str (pitch) { var p = Array.isArray(pitch) ? pitch : asPitch.parse(pitch) return p ? asPitch.stringify(p) : null }
javascript
function str (pitch) { var p = Array.isArray(pitch) ? pitch : asPitch.parse(pitch) return p ? asPitch.stringify(p) : null }
[ "function", "str", "(", "pitch", ")", "{", "var", "p", "=", "Array", ".", "isArray", "(", "pitch", ")", "?", "pitch", ":", "asPitch", ".", "parse", "(", "pitch", ")", "return", "p", "?", "asPitch", ".", "stringify", "(", "p", ")", ":", "null", "}" ]
Get pitch name in scientific notation @param {String|Array} pitch - the pitch string or array @return {String} the name of the pitch @example pitch.str('cb') // => 'Cb' pitch.str('fx2') // => 'F##2'
[ "Get", "pitch", "name", "in", "scientific", "notation" ]
2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b
https://github.com/danigb/music-pitch/blob/2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b/index.js#L36-L39
41,244
danigb/music-pitch
index.js
fromMidi
function fromMidi (midi) { var name = CHROMATIC[midi % 12] var oct = Math.floor(midi / 12) - 1 return name + oct }
javascript
function fromMidi (midi) { var name = CHROMATIC[midi % 12] var oct = Math.floor(midi / 12) - 1 return name + oct }
[ "function", "fromMidi", "(", "midi", ")", "{", "var", "name", "=", "CHROMATIC", "[", "midi", "%", "12", "]", "var", "oct", "=", "Math", ".", "floor", "(", "midi", "/", "12", ")", "-", "1", "return", "name", "+", "oct", "}" ]
Get the pitch of the given midi number This method doesn't take into account diatonic spelling. Always the same pitch class is given to the same midi number. @param {Integer} midi - the midi number @return {String} the pitch @example pitch.fromMidi(69) // => 'A4'
[ "Get", "the", "pitch", "of", "the", "given", "midi", "number" ]
2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b
https://github.com/danigb/music-pitch/blob/2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b/index.js#L119-L123
41,245
danigb/music-pitch
index.js
fromFreq
function fromFreq (freq, tuning) { tuning = tuning || 440 var lineal = 12 * ((Math.log(freq) - Math.log(tuning)) / Math.log(2)) var midi = Math.round(69 + lineal) return fromMidi(midi) }
javascript
function fromFreq (freq, tuning) { tuning = tuning || 440 var lineal = 12 * ((Math.log(freq) - Math.log(tuning)) / Math.log(2)) var midi = Math.round(69 + lineal) return fromMidi(midi) }
[ "function", "fromFreq", "(", "freq", ",", "tuning", ")", "{", "tuning", "=", "tuning", "||", "440", "var", "lineal", "=", "12", "*", "(", "(", "Math", ".", "log", "(", "freq", ")", "-", "Math", ".", "log", "(", "tuning", ")", ")", "/", "Math", ".", "log", "(", "2", ")", ")", "var", "midi", "=", "Math", ".", "round", "(", "69", "+", "lineal", ")", "return", "fromMidi", "(", "midi", ")", "}" ]
Get the pitch of a given frequency. It will round the frequency to the nearest pitch frequency. Use `cents` function if you need to know the difference between the the frequency and the pitch. @param {Float} freq - the frequency @return {String} the pitch @see cents @example pitch.fromFreq(440) // => 'A4' pitch.fromFreq(443) // => 'A4' pitch.cents(443, 'A4') // => ... to get the difference
[ "Get", "the", "pitch", "of", "a", "given", "frequency", "." ]
2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b
https://github.com/danigb/music-pitch/blob/2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b/index.js#L158-L163
41,246
danigb/music-pitch
index.js
toFreq
function toFreq (p, tuning) { if (NUM.test(p)) return +p var midi = toMidi(asPitch.parse(p)) if (!midi) return null tuning = tuning || 440 return Math.pow(2, (midi - 69) / 12) * tuning }
javascript
function toFreq (p, tuning) { if (NUM.test(p)) return +p var midi = toMidi(asPitch.parse(p)) if (!midi) return null tuning = tuning || 440 return Math.pow(2, (midi - 69) / 12) * tuning }
[ "function", "toFreq", "(", "p", ",", "tuning", ")", "{", "if", "(", "NUM", ".", "test", "(", "p", ")", ")", "return", "+", "p", "var", "midi", "=", "toMidi", "(", "asPitch", ".", "parse", "(", "p", ")", ")", "if", "(", "!", "midi", ")", "return", "null", "tuning", "=", "tuning", "||", "440", "return", "Math", ".", "pow", "(", "2", ",", "(", "midi", "-", "69", ")", "/", "12", ")", "*", "tuning", "}" ]
Get the pitch frequency in hertzs @param {String} pitch - the pitch @param {Integer} tuning - optional tuning, 440 by default @return {Float} - the pitch frequency @example pitch.toFreq('A4') // => 440 pitch.toFreq('A3', 444) // => 222
[ "Get", "the", "pitch", "frequency", "in", "hertzs" ]
2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b
https://github.com/danigb/music-pitch/blob/2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b/index.js#L179-L185
41,247
danigb/music-pitch
index.js
cents
function cents (from, to, decimals) { var dec = decimals ? Math.pow(10, decimals) : 100 var fromFq = toFreq(from) var toFq = toFreq(to) return Math.floor(1200 * (Math.log(toFq / fromFq) * dec / Math.log(2))) / dec }
javascript
function cents (from, to, decimals) { var dec = decimals ? Math.pow(10, decimals) : 100 var fromFq = toFreq(from) var toFq = toFreq(to) return Math.floor(1200 * (Math.log(toFq / fromFq) * dec / Math.log(2))) / dec }
[ "function", "cents", "(", "from", ",", "to", ",", "decimals", ")", "{", "var", "dec", "=", "decimals", "?", "Math", ".", "pow", "(", "10", ",", "decimals", ")", ":", "100", "var", "fromFq", "=", "toFreq", "(", "from", ")", "var", "toFq", "=", "toFreq", "(", "to", ")", "return", "Math", ".", "floor", "(", "1200", "*", "(", "Math", ".", "log", "(", "toFq", "/", "fromFq", ")", "*", "dec", "/", "Math", ".", "log", "(", "2", ")", ")", ")", "/", "dec", "}" ]
Get the distance in cents between pitches or frequencies @param {String|Integer} from - first pitch or frequency @param {String|Integer} to - other pitch or frequency @param {Integer} decimals - the decimal precision (2 by default) @return {Integer} the distance in cents @example cents(440, 444) // => 15.66 cents('A4', 444) // => 15.66 cents('A4', 'A#4') // => 100
[ "Get", "the", "distance", "in", "cents", "between", "pitches", "or", "frequencies" ]
2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b
https://github.com/danigb/music-pitch/blob/2f2eb6710a4aa46dce8edd07b8051bdbc73ce00b/index.js#L201-L206
41,248
chleck/locale-js
example/translate.js
demo
function demo() { // Translate phrase w(__('Hello!')); // Comment for translator w(__('Hello!# This is comment.')); // Phrase with id w(__('Hello!#another_hello')); // Phrase with id and comment w(__('Hello!#another_hello2 Please translate this another way.')); // Phrase with # but not comment w(__('There is ## in this phrase but it is not comment.')); // This phrase will not be translated - missing in translation. w(__('Hello?')); // Escapes for placeholders w(__('This is %% percent symbol.')); // Placeholders with additional arguments w(__('My %(0)s is faster then your %(1)s!', 'SSD', 'HDD')); // Placeholders with array w(__('My %(0)s is faster then your %(1)s!', [ 'Kawasaki', 'Segway' ])); // Placeholders with object w(__('My %(0)s is faster then your %(1)s!', { 0: 'Core i7', 1: '486DX' })); // Both names and order w(__('Let\'s count in English: %s, %s, %(3)s and %s.', 'one', 'two', 'four', 'three')); // Plural forms w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 1)); w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 12)); w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 22)); // All-in-one w(__([ '%n developer from our team uses %(0)s with %(1)s.# Comment 1', '%n developers from our team uses %(0)s with %(1)s.# Comment 2' ], 1, 'C', 'vim' )); w(__([ '%n developer from our team uses %(0)s with %(1)s.# Comment 3', '%n developers from our team uses %(0)s with %(1)s.# Comment 4' ], 3, [ 'Python', 'PyCharm' ] )); w(__([ '%n developer from our team uses %(0)s with %(1)s.# Multiline\ncomment', '%n developers from our team uses %(0)s with %(1)s.# Another\nmultiline\ncomment' ], 7, { 0: 'Node.js', 1: 'Sublime Text 2' } )); // No args - empty string w(__()); }
javascript
function demo() { // Translate phrase w(__('Hello!')); // Comment for translator w(__('Hello!# This is comment.')); // Phrase with id w(__('Hello!#another_hello')); // Phrase with id and comment w(__('Hello!#another_hello2 Please translate this another way.')); // Phrase with # but not comment w(__('There is ## in this phrase but it is not comment.')); // This phrase will not be translated - missing in translation. w(__('Hello?')); // Escapes for placeholders w(__('This is %% percent symbol.')); // Placeholders with additional arguments w(__('My %(0)s is faster then your %(1)s!', 'SSD', 'HDD')); // Placeholders with array w(__('My %(0)s is faster then your %(1)s!', [ 'Kawasaki', 'Segway' ])); // Placeholders with object w(__('My %(0)s is faster then your %(1)s!', { 0: 'Core i7', 1: '486DX' })); // Both names and order w(__('Let\'s count in English: %s, %s, %(3)s and %s.', 'one', 'two', 'four', 'three')); // Plural forms w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 1)); w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 12)); w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 22)); // All-in-one w(__([ '%n developer from our team uses %(0)s with %(1)s.# Comment 1', '%n developers from our team uses %(0)s with %(1)s.# Comment 2' ], 1, 'C', 'vim' )); w(__([ '%n developer from our team uses %(0)s with %(1)s.# Comment 3', '%n developers from our team uses %(0)s with %(1)s.# Comment 4' ], 3, [ 'Python', 'PyCharm' ] )); w(__([ '%n developer from our team uses %(0)s with %(1)s.# Multiline\ncomment', '%n developers from our team uses %(0)s with %(1)s.# Another\nmultiline\ncomment' ], 7, { 0: 'Node.js', 1: 'Sublime Text 2' } )); // No args - empty string w(__()); }
[ "function", "demo", "(", ")", "{", "// Translate phrase", "w", "(", "__", "(", "'Hello!'", ")", ")", ";", "// Comment for translator", "w", "(", "__", "(", "'Hello!# This is comment.'", ")", ")", ";", "// Phrase with id ", "w", "(", "__", "(", "'Hello!#another_hello'", ")", ")", ";", "// Phrase with id and comment", "w", "(", "__", "(", "'Hello!#another_hello2 Please translate this another way.'", ")", ")", ";", "// Phrase with # but not comment", "w", "(", "__", "(", "'There is ## in this phrase but it is not comment.'", ")", ")", ";", "// This phrase will not be translated - missing in translation.", "w", "(", "__", "(", "'Hello?'", ")", ")", ";", "// Escapes for placeholders", "w", "(", "__", "(", "'This is %% percent symbol.'", ")", ")", ";", "// Placeholders with additional arguments", "w", "(", "__", "(", "'My %(0)s is faster then your %(1)s!'", ",", "'SSD'", ",", "'HDD'", ")", ")", ";", "// Placeholders with array", "w", "(", "__", "(", "'My %(0)s is faster then your %(1)s!'", ",", "[", "'Kawasaki'", ",", "'Segway'", "]", ")", ")", ";", "// Placeholders with object", "w", "(", "__", "(", "'My %(0)s is faster then your %(1)s!'", ",", "{", "0", ":", "'Core i7'", ",", "1", ":", "'486DX'", "}", ")", ")", ";", "// Both names and order", "w", "(", "__", "(", "'Let\\'s count in English: %s, %s, %(3)s and %s.'", ",", "'one'", ",", "'two'", ",", "'four'", ",", "'three'", ")", ")", ";", "// Plural forms", "w", "(", "__", "(", "[", "'Inbox: %n unreaded message.'", ",", "'Inbox: %n unreaded messages.'", "]", ",", "1", ")", ")", ";", "w", "(", "__", "(", "[", "'Inbox: %n unreaded message.'", ",", "'Inbox: %n unreaded messages.'", "]", ",", "12", ")", ")", ";", "w", "(", "__", "(", "[", "'Inbox: %n unreaded message.'", ",", "'Inbox: %n unreaded messages.'", "]", ",", "22", ")", ")", ";", "// All-in-one", "w", "(", "__", "(", "[", "'%n developer from our team uses %(0)s with %(1)s.# Comment 1'", ",", "'%n developers from our team uses %(0)s with %(1)s.# Comment 2'", "]", ",", "1", ",", "'C'", ",", "'vim'", ")", ")", ";", "w", "(", "__", "(", "[", "'%n developer from our team uses %(0)s with %(1)s.# Comment 3'", ",", "'%n developers from our team uses %(0)s with %(1)s.# Comment 4'", "]", ",", "3", ",", "[", "'Python'", ",", "'PyCharm'", "]", ")", ")", ";", "w", "(", "__", "(", "[", "'%n developer from our team uses %(0)s with %(1)s.# Multiline\\ncomment'", ",", "'%n developers from our team uses %(0)s with %(1)s.# Another\\nmultiline\\ncomment'", "]", ",", "7", ",", "{", "0", ":", "'Node.js'", ",", "1", ":", "'Sublime Text 2'", "}", ")", ")", ";", "// No args - empty string", "w", "(", "__", "(", ")", ")", ";", "}" ]
THE END !!! Usage of translation functions
[ "THE", "END", "!!!", "Usage", "of", "translation", "functions" ]
50662485ff029e4cea6d180683646426f0ee81f5
https://github.com/chleck/locale-js/blob/50662485ff029e4cea6d180683646426f0ee81f5/example/translate.js#L34-L79
41,249
ghinda/gridlayout
src/gridlayout-ie.js
function() { var cellSelector = '' + '.gl-cell > .gl-vertical,' + '.gl-cell > .gl-fill,' + '.gl-cell > .gl-scrollview,' + '.gl-cell > .gl-scrollview > .gl-scrollview-content'; var $cells = document.querySelectorAll(cellSelector); var i; var $parent; var cell; var parent; for(i = 0; i < $cells.length; i++) { cell = getBoundingClientRect.call($cells[i]); $parent = $cells[i].parentNode; parent = getBoundingClientRect.call($parent); var parentDisplay; if($parent.currentStyle) { parentDisplay = $parent.currentStyle.display; } else { parentDisplay = window.getComputedStyle($parent).display; } // instead of checking for IE by user agent, check if // and the height is wrong. if(cell.height !== parent.height) { // we can't separate property read/write into separate loops, // for performance with reflows, because we need to have the // corrent dimensions set on a cell parent, once we reach a child. $cells[i].style.height = parent.height + 'px'; // some rows without dimensions set take up more space than needed. if(parentDisplay === 'table-row') { $parent.style.height = parent.height + 'px'; } } } }
javascript
function() { var cellSelector = '' + '.gl-cell > .gl-vertical,' + '.gl-cell > .gl-fill,' + '.gl-cell > .gl-scrollview,' + '.gl-cell > .gl-scrollview > .gl-scrollview-content'; var $cells = document.querySelectorAll(cellSelector); var i; var $parent; var cell; var parent; for(i = 0; i < $cells.length; i++) { cell = getBoundingClientRect.call($cells[i]); $parent = $cells[i].parentNode; parent = getBoundingClientRect.call($parent); var parentDisplay; if($parent.currentStyle) { parentDisplay = $parent.currentStyle.display; } else { parentDisplay = window.getComputedStyle($parent).display; } // instead of checking for IE by user agent, check if // and the height is wrong. if(cell.height !== parent.height) { // we can't separate property read/write into separate loops, // for performance with reflows, because we need to have the // corrent dimensions set on a cell parent, once we reach a child. $cells[i].style.height = parent.height + 'px'; // some rows without dimensions set take up more space than needed. if(parentDisplay === 'table-row') { $parent.style.height = parent.height + 'px'; } } } }
[ "function", "(", ")", "{", "var", "cellSelector", "=", "''", "+", "'.gl-cell > .gl-vertical,'", "+", "'.gl-cell > .gl-fill,'", "+", "'.gl-cell > .gl-scrollview,'", "+", "'.gl-cell > .gl-scrollview > .gl-scrollview-content'", ";", "var", "$cells", "=", "document", ".", "querySelectorAll", "(", "cellSelector", ")", ";", "var", "i", ";", "var", "$parent", ";", "var", "cell", ";", "var", "parent", ";", "for", "(", "i", "=", "0", ";", "i", "<", "$cells", ".", "length", ";", "i", "++", ")", "{", "cell", "=", "getBoundingClientRect", ".", "call", "(", "$cells", "[", "i", "]", ")", ";", "$parent", "=", "$cells", "[", "i", "]", ".", "parentNode", ";", "parent", "=", "getBoundingClientRect", ".", "call", "(", "$parent", ")", ";", "var", "parentDisplay", ";", "if", "(", "$parent", ".", "currentStyle", ")", "{", "parentDisplay", "=", "$parent", ".", "currentStyle", ".", "display", ";", "}", "else", "{", "parentDisplay", "=", "window", ".", "getComputedStyle", "(", "$parent", ")", ".", "display", ";", "}", "// instead of checking for IE by user agent, check if", "// and the height is wrong.", "if", "(", "cell", ".", "height", "!==", "parent", ".", "height", ")", "{", "// we can't separate property read/write into separate loops,", "// for performance with reflows, because we need to have the", "// corrent dimensions set on a cell parent, once we reach a child.", "$cells", "[", "i", "]", ".", "style", ".", "height", "=", "parent", ".", "height", "+", "'px'", ";", "// some rows without dimensions set take up more space than needed.", "if", "(", "parentDisplay", "===", "'table-row'", ")", "{", "$parent", ".", "style", ".", "height", "=", "parent", ".", "height", "+", "'px'", ";", "}", "}", "}", "}" ]
set the correct grid and scrollview sizes
[ "set", "the", "correct", "grid", "and", "scrollview", "sizes" ]
55b3660784ff45b1e8f69d4e15de224ebd2eb0c7
https://github.com/ghinda/gridlayout/blob/55b3660784ff45b1e8f69d4e15de224ebd2eb0c7/src/gridlayout-ie.js#L49-L94
41,250
mbroadst/thinkagain
lib/util.js
deepCopy
function deepCopy(value) { let result; if (value instanceof Buffer) { // isPlainObject(buffer) returns true. return new Buffer(value); } if (isPlainObject(value) === true) { result = {}; loopKeys(value, function(_value, key) { if (_value.hasOwnProperty(key)) { result[key] = deepCopy(_value[key]); } }); return result; } if (Array.isArray(value)) { result = []; for (let i = 0, ii = value.length; i < ii; ++i) { result.push(deepCopy(value[i])); } return result; } return value; }
javascript
function deepCopy(value) { let result; if (value instanceof Buffer) { // isPlainObject(buffer) returns true. return new Buffer(value); } if (isPlainObject(value) === true) { result = {}; loopKeys(value, function(_value, key) { if (_value.hasOwnProperty(key)) { result[key] = deepCopy(_value[key]); } }); return result; } if (Array.isArray(value)) { result = []; for (let i = 0, ii = value.length; i < ii; ++i) { result.push(deepCopy(value[i])); } return result; } return value; }
[ "function", "deepCopy", "(", "value", ")", "{", "let", "result", ";", "if", "(", "value", "instanceof", "Buffer", ")", "{", "// isPlainObject(buffer) returns true.", "return", "new", "Buffer", "(", "value", ")", ";", "}", "if", "(", "isPlainObject", "(", "value", ")", "===", "true", ")", "{", "result", "=", "{", "}", ";", "loopKeys", "(", "value", ",", "function", "(", "_value", ",", "key", ")", "{", "if", "(", "_value", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "result", "[", "key", "]", "=", "deepCopy", "(", "_value", "[", "key", "]", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "result", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "ii", "=", "value", ".", "length", ";", "i", "<", "ii", ";", "++", "i", ")", "{", "result", ".", "push", "(", "deepCopy", "(", "value", "[", "i", "]", ")", ")", ";", "}", "return", "result", ";", "}", "return", "value", ";", "}" ]
Make a "deep copy". The prototype chain is not copied.
[ "Make", "a", "deep", "copy", ".", "The", "prototype", "chain", "is", "not", "copied", "." ]
0aa6d3e82019530ce847083cd64e811aed63b36c
https://github.com/mbroadst/thinkagain/blob/0aa6d3e82019530ce847083cd64e811aed63b36c/lib/util.js#L24-L50
41,251
lakenen/node-append-query
index.js
serialize
function serialize(obj, opts, prefix) { var str = [] , useArraySyntax = false // if there's a prefix, and this object is an array, use array syntax // i.e., `prefix[]=foo&prefix[]=bar` instead of `prefix[0]=foo&prefix[1]=bar` if (Array.isArray(obj) && prefix) { useArraySyntax = true } Object.keys(obj).forEach(function (prop) { var key, query, val = obj[prop] key = prefix ? prefix + '[' + (useArraySyntax ? '' : prop) + ']' : prop if (val === null) { if (opts.removeNull) { return } query = opts.encodeComponents ? encodeURIComponent(key) : key } else if (typeof val === 'object') { query = serialize(val, opts, key) } else { query = opts.encodeComponents ? encodeURIComponent(key) + '=' + encodeURIComponent(val) : key + '=' + val; } str.push(query) }) return str.join('&') }
javascript
function serialize(obj, opts, prefix) { var str = [] , useArraySyntax = false // if there's a prefix, and this object is an array, use array syntax // i.e., `prefix[]=foo&prefix[]=bar` instead of `prefix[0]=foo&prefix[1]=bar` if (Array.isArray(obj) && prefix) { useArraySyntax = true } Object.keys(obj).forEach(function (prop) { var key, query, val = obj[prop] key = prefix ? prefix + '[' + (useArraySyntax ? '' : prop) + ']' : prop if (val === null) { if (opts.removeNull) { return } query = opts.encodeComponents ? encodeURIComponent(key) : key } else if (typeof val === 'object') { query = serialize(val, opts, key) } else { query = opts.encodeComponents ? encodeURIComponent(key) + '=' + encodeURIComponent(val) : key + '=' + val; } str.push(query) }) return str.join('&') }
[ "function", "serialize", "(", "obj", ",", "opts", ",", "prefix", ")", "{", "var", "str", "=", "[", "]", ",", "useArraySyntax", "=", "false", "// if there's a prefix, and this object is an array, use array syntax", "// i.e., `prefix[]=foo&prefix[]=bar` instead of `prefix[0]=foo&prefix[1]=bar`", "if", "(", "Array", ".", "isArray", "(", "obj", ")", "&&", "prefix", ")", "{", "useArraySyntax", "=", "true", "}", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "key", ",", "query", ",", "val", "=", "obj", "[", "prop", "]", "key", "=", "prefix", "?", "prefix", "+", "'['", "+", "(", "useArraySyntax", "?", "''", ":", "prop", ")", "+", "']'", ":", "prop", "if", "(", "val", "===", "null", ")", "{", "if", "(", "opts", ".", "removeNull", ")", "{", "return", "}", "query", "=", "opts", ".", "encodeComponents", "?", "encodeURIComponent", "(", "key", ")", ":", "key", "}", "else", "if", "(", "typeof", "val", "===", "'object'", ")", "{", "query", "=", "serialize", "(", "val", ",", "opts", ",", "key", ")", "}", "else", "{", "query", "=", "opts", ".", "encodeComponents", "?", "encodeURIComponent", "(", "key", ")", "+", "'='", "+", "encodeURIComponent", "(", "val", ")", ":", "key", "+", "'='", "+", "val", ";", "}", "str", ".", "push", "(", "query", ")", "}", ")", "return", "str", ".", "join", "(", "'&'", ")", "}" ]
serialize an object recursively
[ "serialize", "an", "object", "recursively" ]
e8daa9f1a10fb041b405d736bd34f321190c6321
https://github.com/lakenen/node-append-query/blob/e8daa9f1a10fb041b405d736bd34f321190c6321/index.js#L24-L57
41,252
jeanlauliac/kademlia-dht
lib/id.js
function (buf) { if (!(buf instanceof Buffer) || buf.length !== Id.SIZE) throw new Error('invalid buffer'); this._buf = buf; }
javascript
function (buf) { if (!(buf instanceof Buffer) || buf.length !== Id.SIZE) throw new Error('invalid buffer'); this._buf = buf; }
[ "function", "(", "buf", ")", "{", "if", "(", "!", "(", "buf", "instanceof", "Buffer", ")", "||", "buf", ".", "length", "!==", "Id", ".", "SIZE", ")", "throw", "new", "Error", "(", "'invalid buffer'", ")", ";", "this", ".", "_buf", "=", "buf", ";", "}" ]
Create an id from a `buffer`.
[ "Create", "an", "id", "from", "a", "buffer", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/id.js#L8-L12
41,253
TuyaAPI/link
index.js
TuyaLinkWizard
function TuyaLinkWizard(options) { // Set to empty object if undefined options = options ? options : {}; if (!options.email || !options.password) { throw new Error('Both email and password must be provided'); } this.email = options.email; this.password = options.password; // Set defaults this.region = options.region ? options.region : 'AZ'; this.timezone = options.timezone ? options.timezone : '-05:00'; // Don't need to check key and secret for correct format as // tuyapi/cloud already does this.api = new Cloud({key: options.apiKey, secret: options.apiSecret, region: this.region}); // Construct instance of TuyaLink this.device = new TuyaLink(); }
javascript
function TuyaLinkWizard(options) { // Set to empty object if undefined options = options ? options : {}; if (!options.email || !options.password) { throw new Error('Both email and password must be provided'); } this.email = options.email; this.password = options.password; // Set defaults this.region = options.region ? options.region : 'AZ'; this.timezone = options.timezone ? options.timezone : '-05:00'; // Don't need to check key and secret for correct format as // tuyapi/cloud already does this.api = new Cloud({key: options.apiKey, secret: options.apiSecret, region: this.region}); // Construct instance of TuyaLink this.device = new TuyaLink(); }
[ "function", "TuyaLinkWizard", "(", "options", ")", "{", "// Set to empty object if undefined", "options", "=", "options", "?", "options", ":", "{", "}", ";", "if", "(", "!", "options", ".", "email", "||", "!", "options", ".", "password", ")", "{", "throw", "new", "Error", "(", "'Both email and password must be provided'", ")", ";", "}", "this", ".", "email", "=", "options", ".", "email", ";", "this", ".", "password", "=", "options", ".", "password", ";", "// Set defaults", "this", ".", "region", "=", "options", ".", "region", "?", "options", ".", "region", ":", "'AZ'", ";", "this", ".", "timezone", "=", "options", ".", "timezone", "?", "options", ".", "timezone", ":", "'-05:00'", ";", "// Don't need to check key and secret for correct format as", "// tuyapi/cloud already does", "this", ".", "api", "=", "new", "Cloud", "(", "{", "key", ":", "options", ".", "apiKey", ",", "secret", ":", "options", ".", "apiSecret", ",", "region", ":", "this", ".", "region", "}", ")", ";", "// Construct instance of TuyaLink", "this", ".", "device", "=", "new", "TuyaLink", "(", ")", ";", "}" ]
A wrapper that combines `@tuyapi/cloud` and `(@tuyapi/link).manual` (included in this package) to make registration Just Work™️. Exported as `(@tuyapi/link).wizard`. @class @param {Object} options construction options @param {String} options.apiKey API key @param {String} options.apiSecret API secret @param {String} options.email user email @param {String} options.password user password @param {String} [options.region='AZ'] region (AZ=Americas, AY=Asia, EU=Europe) @param {String} [options.timezone='-05:00'] timezone of device @example // Note: user account does not need to already exist const register = new TuyaLink.wizard({key: 'your-api-key', secret: 'your-api-secret', email: '[email protected]', password: 'example-password'});
[ "A", "wrapper", "that", "combines" ]
58096fb5b630496f5f6ead8b083fb5d46ad71afe
https://github.com/TuyaAPI/link/blob/58096fb5b630496f5f6ead8b083fb5d46ad71afe/index.js#L25-L48
41,254
jjwchoy/mongoose-shortid
lib/genid.js
bignumToString
function bignumToString(bignum, base, alphabet) { // Prefer native conversion if (alphabet === "native" && base != 6) { return bignum.toString(base); } // Old-sk00l conversion var result = []; while (bignum.gt(0)) { var ord = bignum.mod(base); result.push(alphabet.charAt(ord)); bignum = bignum.div(base); } return result.reverse().join(""); }
javascript
function bignumToString(bignum, base, alphabet) { // Prefer native conversion if (alphabet === "native" && base != 6) { return bignum.toString(base); } // Old-sk00l conversion var result = []; while (bignum.gt(0)) { var ord = bignum.mod(base); result.push(alphabet.charAt(ord)); bignum = bignum.div(base); } return result.reverse().join(""); }
[ "function", "bignumToString", "(", "bignum", ",", "base", ",", "alphabet", ")", "{", "// Prefer native conversion", "if", "(", "alphabet", "===", "\"native\"", "&&", "base", "!=", "6", ")", "{", "return", "bignum", ".", "toString", "(", "base", ")", ";", "}", "// Old-sk00l conversion", "var", "result", "=", "[", "]", ";", "while", "(", "bignum", ".", "gt", "(", "0", ")", ")", "{", "var", "ord", "=", "bignum", ".", "mod", "(", "base", ")", ";", "result", ".", "push", "(", "alphabet", ".", "charAt", "(", "ord", ")", ")", ";", "bignum", "=", "bignum", ".", "div", "(", "base", ")", ";", "}", "return", "result", ".", "reverse", "(", ")", ".", "join", "(", "\"\"", ")", ";", "}" ]
Convert the bignum to a string with the given base
[ "Convert", "the", "bignum", "to", "a", "string", "with", "the", "given", "base" ]
a18d1a1912614afbf86c63b6bcaef9517dcfe541
https://github.com/jjwchoy/mongoose-shortid/blob/a18d1a1912614afbf86c63b6bcaef9517dcfe541/lib/genid.js#L26-L42
41,255
tvrprasad/sspi-client
src_js/sspi_client.js
function (sspiClient) { if (!initializeExecutionCompleted) { // You cannot user process.nextTick() here as it will block all // I/O which means initialization in native code will never get // a chance to run and the process will just hang. setImmediate(invokeGetNextBlob, sspiClient); } else if (!initializeSucceeded) { cb(null, null, initializeErrorCode, initializeErrorString); } else { sspiClient.sspiClientImpl.getNextBlob(serverResponse, serverResponseBeginOffset, serverResponseLength, // Cannot use => function syntax here as that does not have the 'arguments'. function() { sspiClient.getNextBlobInProgress = false; cb.apply(null, arguments); }); } }
javascript
function (sspiClient) { if (!initializeExecutionCompleted) { // You cannot user process.nextTick() here as it will block all // I/O which means initialization in native code will never get // a chance to run and the process will just hang. setImmediate(invokeGetNextBlob, sspiClient); } else if (!initializeSucceeded) { cb(null, null, initializeErrorCode, initializeErrorString); } else { sspiClient.sspiClientImpl.getNextBlob(serverResponse, serverResponseBeginOffset, serverResponseLength, // Cannot use => function syntax here as that does not have the 'arguments'. function() { sspiClient.getNextBlobInProgress = false; cb.apply(null, arguments); }); } }
[ "function", "(", "sspiClient", ")", "{", "if", "(", "!", "initializeExecutionCompleted", ")", "{", "// You cannot user process.nextTick() here as it will block all", "// I/O which means initialization in native code will never get", "// a chance to run and the process will just hang.", "setImmediate", "(", "invokeGetNextBlob", ",", "sspiClient", ")", ";", "}", "else", "if", "(", "!", "initializeSucceeded", ")", "{", "cb", "(", "null", ",", "null", ",", "initializeErrorCode", ",", "initializeErrorString", ")", ";", "}", "else", "{", "sspiClient", ".", "sspiClientImpl", ".", "getNextBlob", "(", "serverResponse", ",", "serverResponseBeginOffset", ",", "serverResponseLength", ",", "// Cannot use => function syntax here as that does not have the 'arguments'.", "function", "(", ")", "{", "sspiClient", ".", "getNextBlobInProgress", "=", "false", ";", "cb", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", ")", ";", "}", "}" ]
Wait for initialization to complete. If initialization fails, invoke callback with error information. Else, invoke native implementation.
[ "Wait", "for", "initialization", "to", "complete", ".", "If", "initialization", "fails", "invoke", "callback", "with", "error", "information", ".", "Else", "invoke", "native", "implementation", "." ]
020ebed515f5a46e9be42edcf02dcaf32666ecb5
https://github.com/tvrprasad/sspi-client/blob/020ebed515f5a46e9be42edcf02dcaf32666ecb5/src_js/sspi_client.js#L145-L161
41,256
jeanlauliac/kademlia-dht
lib/mock-rpc.js
MockRpc
function MockRpc(endpoint) { events.EventEmitter.call(this); this._endpoint = endpoint; this._handlers = {}; glNetwork[endpoint] = this; }
javascript
function MockRpc(endpoint) { events.EventEmitter.call(this); this._endpoint = endpoint; this._handlers = {}; glNetwork[endpoint] = this; }
[ "function", "MockRpc", "(", "endpoint", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_endpoint", "=", "endpoint", ";", "this", ".", "_handlers", "=", "{", "}", ";", "glNetwork", "[", "endpoint", "]", "=", "this", ";", "}" ]
Simple no-network RPC implementation, for testing purposes.
[ "Simple", "no", "-", "network", "RPC", "implementation", "for", "testing", "purposes", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/mock-rpc.js#L10-L15
41,257
tvrprasad/sspi-client
src_js/fqdn.js
getFqdnForIpAddress
function getFqdnForIpAddress(ipAddress, cb) { dns.reverse(ipAddress, function(err, fqdns) { if (err) { cb(err, fqdns); } else if (fqdns[0].toLowerCase() === localhostIdentifier) { getFqdn(localhostIdentifier, cb); } else { cb(err, fqdns[0]); } }); }
javascript
function getFqdnForIpAddress(ipAddress, cb) { dns.reverse(ipAddress, function(err, fqdns) { if (err) { cb(err, fqdns); } else if (fqdns[0].toLowerCase() === localhostIdentifier) { getFqdn(localhostIdentifier, cb); } else { cb(err, fqdns[0]); } }); }
[ "function", "getFqdnForIpAddress", "(", "ipAddress", ",", "cb", ")", "{", "dns", ".", "reverse", "(", "ipAddress", ",", "function", "(", "err", ",", "fqdns", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ",", "fqdns", ")", ";", "}", "else", "if", "(", "fqdns", "[", "0", "]", ".", "toLowerCase", "(", ")", "===", "localhostIdentifier", ")", "{", "getFqdn", "(", "localhostIdentifier", ",", "cb", ")", ";", "}", "else", "{", "cb", "(", "err", ",", "fqdns", "[", "0", "]", ")", ";", "}", "}", ")", ";", "}" ]
Do a reverse lookup on the IP address and return the first FQDN.
[ "Do", "a", "reverse", "lookup", "on", "the", "IP", "address", "and", "return", "the", "first", "FQDN", "." ]
020ebed515f5a46e9be42edcf02dcaf32666ecb5
https://github.com/tvrprasad/sspi-client/blob/020ebed515f5a46e9be42edcf02dcaf32666ecb5/src_js/fqdn.js#L10-L20
41,258
tvrprasad/sspi-client
src_js/fqdn.js
getFqdnForHostname
function getFqdnForHostname(hostname, cb) { let addressIndex = 0; dns.lookup(hostname, { all: true }, function (err, addresses, family) { const tryNextAddressOrComplete = (err, fqdn) => { addressIndex++; if (!err) { cb(err, fqdn); } else if (addressIndex != addresses.length) { getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete); } else { cb(err); } }; if (!err) { getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete); } else { cb(err); } }); }
javascript
function getFqdnForHostname(hostname, cb) { let addressIndex = 0; dns.lookup(hostname, { all: true }, function (err, addresses, family) { const tryNextAddressOrComplete = (err, fqdn) => { addressIndex++; if (!err) { cb(err, fqdn); } else if (addressIndex != addresses.length) { getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete); } else { cb(err); } }; if (!err) { getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete); } else { cb(err); } }); }
[ "function", "getFqdnForHostname", "(", "hostname", ",", "cb", ")", "{", "let", "addressIndex", "=", "0", ";", "dns", ".", "lookup", "(", "hostname", ",", "{", "all", ":", "true", "}", ",", "function", "(", "err", ",", "addresses", ",", "family", ")", "{", "const", "tryNextAddressOrComplete", "=", "(", "err", ",", "fqdn", ")", "=>", "{", "addressIndex", "++", ";", "if", "(", "!", "err", ")", "{", "cb", "(", "err", ",", "fqdn", ")", ";", "}", "else", "if", "(", "addressIndex", "!=", "addresses", ".", "length", ")", "{", "getFqdnForIpAddress", "(", "addresses", "[", "addressIndex", "]", ".", "address", ",", "tryNextAddressOrComplete", ")", ";", "}", "else", "{", "cb", "(", "err", ")", ";", "}", "}", ";", "if", "(", "!", "err", ")", "{", "getFqdnForIpAddress", "(", "addresses", "[", "addressIndex", "]", ".", "address", ",", "tryNextAddressOrComplete", ")", ";", "}", "else", "{", "cb", "(", "err", ")", ";", "}", "}", ")", ";", "}" ]
Get the IP addresses for host. For each of the IP addresses, do a reverse lookup, one IP address at a time and take the FQDN from the first successful result.
[ "Get", "the", "IP", "addresses", "for", "host", ".", "For", "each", "of", "the", "IP", "addresses", "do", "a", "reverse", "lookup", "one", "IP", "address", "at", "a", "time", "and", "take", "the", "FQDN", "from", "the", "first", "successful", "result", "." ]
020ebed515f5a46e9be42edcf02dcaf32666ecb5
https://github.com/tvrprasad/sspi-client/blob/020ebed515f5a46e9be42edcf02dcaf32666ecb5/src_js/fqdn.js#L25-L46
41,259
jeanlauliac/kademlia-dht
lib/routing-table.js
function (localId, bucketSize) { if (!(localId instanceof Id)) throw new Error('id must be a valid identifier'); this._bucketSize = bucketSize; this._root = new Bucket(bucketSize); Object.defineProperty(this, 'id', {value: localId}); }
javascript
function (localId, bucketSize) { if (!(localId instanceof Id)) throw new Error('id must be a valid identifier'); this._bucketSize = bucketSize; this._root = new Bucket(bucketSize); Object.defineProperty(this, 'id', {value: localId}); }
[ "function", "(", "localId", ",", "bucketSize", ")", "{", "if", "(", "!", "(", "localId", "instanceof", "Id", ")", ")", "throw", "new", "Error", "(", "'id must be a valid identifier'", ")", ";", "this", ".", "_bucketSize", "=", "bucketSize", ";", "this", ".", "_root", "=", "new", "Bucket", "(", "bucketSize", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'id'", ",", "{", "value", ":", "localId", "}", ")", ";", "}" ]
Associate Kademlia IDs with their endpoints. `localId` must be the ID of the local node, more close contacts are effectively stored than far contacts.
[ "Associate", "Kademlia", "IDs", "with", "their", "endpoints", ".", "localId", "must", "be", "the", "ID", "of", "the", "local", "node", "more", "close", "contacts", "are", "effectively", "stored", "than", "far", "contacts", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/routing-table.js#L11-L17
41,260
jeanlauliac/kademlia-dht
lib/routing-table.js
makeAsync
function makeAsync(cb) { return function () { var args = arguments; process.nextTick(function () { cb.apply(null, args); }); }; }
javascript
function makeAsync(cb) { return function () { var args = arguments; process.nextTick(function () { cb.apply(null, args); }); }; }
[ "function", "makeAsync", "(", "cb", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "cb", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ";", "}", ";", "}" ]
Force a callback to be async.
[ "Force", "a", "callback", "to", "be", "async", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/routing-table.js#L21-L28
41,261
jeanlauliac/kademlia-dht
lib/dht.js
checkInterface
function checkInterface(obj, funcs) { for (var i = 0; i < funcs.length; ++i) { if (typeof obj[funcs[i]] !== 'function') return false; } return true; }
javascript
function checkInterface(obj, funcs) { for (var i = 0; i < funcs.length; ++i) { if (typeof obj[funcs[i]] !== 'function') return false; } return true; }
[ "function", "checkInterface", "(", "obj", ",", "funcs", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "funcs", ".", "length", ";", "++", "i", ")", "{", "if", "(", "typeof", "obj", "[", "funcs", "[", "i", "]", "]", "!==", "'function'", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check that an object possesses the specified functions.
[ "Check", "that", "an", "object", "possesses", "the", "specified", "functions", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/dht.js#L13-L19
41,262
jeanlauliac/kademlia-dht
lib/dht.js
defaultOptions
function defaultOptions(opts) { opts.bucketSize = opts.bucketSize || 20; opts.concurrency = opts.concurrency || 3; opts.expireTime = opts.expireTime || 60 * 60 * 24; opts.refreshTime = opts.refreshTime || 60 * 60; opts.replicateTime = opts.replicateTime || 60 * 60; opts.republishTime = opts.republishTime || 60 * 60 * 24; }
javascript
function defaultOptions(opts) { opts.bucketSize = opts.bucketSize || 20; opts.concurrency = opts.concurrency || 3; opts.expireTime = opts.expireTime || 60 * 60 * 24; opts.refreshTime = opts.refreshTime || 60 * 60; opts.replicateTime = opts.replicateTime || 60 * 60; opts.republishTime = opts.republishTime || 60 * 60 * 24; }
[ "function", "defaultOptions", "(", "opts", ")", "{", "opts", ".", "bucketSize", "=", "opts", ".", "bucketSize", "||", "20", ";", "opts", ".", "concurrency", "=", "opts", ".", "concurrency", "||", "3", ";", "opts", ".", "expireTime", "=", "opts", ".", "expireTime", "||", "60", "*", "60", "*", "24", ";", "opts", ".", "refreshTime", "=", "opts", ".", "refreshTime", "||", "60", "*", "60", ";", "opts", ".", "replicateTime", "=", "opts", ".", "replicateTime", "||", "60", "*", "60", ";", "opts", ".", "republishTime", "=", "opts", ".", "republishTime", "||", "60", "*", "60", "*", "24", ";", "}" ]
Fill `opts` with the default options if needed.
[ "Fill", "opts", "with", "the", "default", "options", "if", "needed", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/dht.js#L23-L30
41,263
jeanlauliac/kademlia-dht
lib/lookup-list.js
LookupList
function LookupList(id, capacity) { if (!(id instanceof Id)) throw new Error('invalid id or selfId'); if (!(typeof capacity === 'number' && capacity > 0)) throw new Error('invalid capacity'); this._id = id; this._capacity = capacity; this._slots = []; }
javascript
function LookupList(id, capacity) { if (!(id instanceof Id)) throw new Error('invalid id or selfId'); if (!(typeof capacity === 'number' && capacity > 0)) throw new Error('invalid capacity'); this._id = id; this._capacity = capacity; this._slots = []; }
[ "function", "LookupList", "(", "id", ",", "capacity", ")", "{", "if", "(", "!", "(", "id", "instanceof", "Id", ")", ")", "throw", "new", "Error", "(", "'invalid id or selfId'", ")", ";", "if", "(", "!", "(", "typeof", "capacity", "===", "'number'", "&&", "capacity", ">", "0", ")", ")", "throw", "new", "Error", "(", "'invalid capacity'", ")", ";", "this", ".", "_id", "=", "id", ";", "this", ".", "_capacity", "=", "capacity", ";", "this", ".", "_slots", "=", "[", "]", ";", "}" ]
Store contacts in a sorted manner, from closest to fartest from the specified `id`.
[ "Store", "contacts", "in", "a", "sorted", "manner", "from", "closest", "to", "fartest", "from", "the", "specified", "id", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/lib/lookup-list.js#L9-L17
41,264
jeanlauliac/kademlia-dht
example/demo.js
demo
function demo(dht1, dht2) { dht1.set('beep', 'boop', function (err) { if (err) throw err; dht2.get('beep', function (err, value) { if (err) throw err; console.log('%s === %s', 'boop', value); }); }); }
javascript
function demo(dht1, dht2) { dht1.set('beep', 'boop', function (err) { if (err) throw err; dht2.get('beep', function (err, value) { if (err) throw err; console.log('%s === %s', 'boop', value); }); }); }
[ "function", "demo", "(", "dht1", ",", "dht2", ")", "{", "dht1", ".", "set", "(", "'beep'", ",", "'boop'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "dht2", ".", "get", "(", "'beep'", ",", "function", "(", "err", ",", "value", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "console", ".", "log", "(", "'%s === %s'", ",", "'boop'", ",", "value", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Store a value on one side and get it back on the other side.
[ "Store", "a", "value", "on", "one", "side", "and", "get", "it", "back", "on", "the", "other", "side", "." ]
e64d53d605d5e194f68c85ca268223e93f9a9241
https://github.com/jeanlauliac/kademlia-dht/blob/e64d53d605d5e194f68c85ca268223e93f9a9241/example/demo.js#L8-L16
41,265
rorymadden/neoprene
lib/errors/validator.js
ValidatorError
function ValidatorError (path, type) { var msg = type ? '"' + type + '" ' : ''; NeopreneError.call(this, 'Validator ' + msg + 'failed for path ' + path); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidatorError'; this.path = path; this.type = type; }
javascript
function ValidatorError (path, type) { var msg = type ? '"' + type + '" ' : ''; NeopreneError.call(this, 'Validator ' + msg + 'failed for path ' + path); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidatorError'; this.path = path; this.type = type; }
[ "function", "ValidatorError", "(", "path", ",", "type", ")", "{", "var", "msg", "=", "type", "?", "'\"'", "+", "type", "+", "'\" '", ":", "''", ";", "NeopreneError", ".", "call", "(", "this", ",", "'Validator '", "+", "msg", "+", "'failed for path '", "+", "path", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'ValidatorError'", ";", "this", ".", "path", "=", "path", ";", "this", ".", "type", "=", "type", ";", "}" ]
Schema validator error @param {String} path @param {String} msg @inherits NeopreneError @api private
[ "Schema", "validator", "error" ]
11f22f65a006c25b779b2add9058e9b00b053466
https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/errors/validator.js#L16-L25
41,266
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (coords) { var row; if (priv.dataType === 'array') { row = []; for (var c = 0; c < self.colCount; c++) { row.push(null); } } else { row = $.extend(true, {}, datamap.getSchema()); } if (!coords || coords.row >= self.rowCount) { priv.settings.data.push(row); } else { priv.settings.data.splice(coords.row, 0, row); } }
javascript
function (coords) { var row; if (priv.dataType === 'array') { row = []; for (var c = 0; c < self.colCount; c++) { row.push(null); } } else { row = $.extend(true, {}, datamap.getSchema()); } if (!coords || coords.row >= self.rowCount) { priv.settings.data.push(row); } else { priv.settings.data.splice(coords.row, 0, row); } }
[ "function", "(", "coords", ")", "{", "var", "row", ";", "if", "(", "priv", ".", "dataType", "===", "'array'", ")", "{", "row", "=", "[", "]", ";", "for", "(", "var", "c", "=", "0", ";", "c", "<", "self", ".", "colCount", ";", "c", "++", ")", "{", "row", ".", "push", "(", "null", ")", ";", "}", "}", "else", "{", "row", "=", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "datamap", ".", "getSchema", "(", ")", ")", ";", "}", "if", "(", "!", "coords", "||", "coords", ".", "row", ">=", "self", ".", "rowCount", ")", "{", "priv", ".", "settings", ".", "data", ".", "push", "(", "row", ")", ";", "}", "else", "{", "priv", ".", "settings", ".", "data", ".", "splice", "(", "coords", ".", "row", ",", "0", ",", "row", ")", ";", "}", "}" ]
Creates row at the bottom of the data array @param {Object} [coords] Optional. Coords of the cell before which the new row will be inserted
[ "Creates", "row", "at", "the", "bottom", "of", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L169-L186
41,267
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (coords) { if (priv.dataType === 'object' || priv.settings.columns) { throw new Error("Cannot create new column. When data source in an object, you can only have as much columns as defined in first data row, data schema or in the 'columns' setting"); } var r = 0; if (!coords || coords.col >= self.colCount) { for (; r < self.rowCount; r++) { if (typeof priv.settings.data[r] === 'undefined') { priv.settings.data[r] = []; } priv.settings.data[r].push(''); } } else { for (; r < self.rowCount; r++) { priv.settings.data[r].splice(coords.col, 0, ''); } } }
javascript
function (coords) { if (priv.dataType === 'object' || priv.settings.columns) { throw new Error("Cannot create new column. When data source in an object, you can only have as much columns as defined in first data row, data schema or in the 'columns' setting"); } var r = 0; if (!coords || coords.col >= self.colCount) { for (; r < self.rowCount; r++) { if (typeof priv.settings.data[r] === 'undefined') { priv.settings.data[r] = []; } priv.settings.data[r].push(''); } } else { for (; r < self.rowCount; r++) { priv.settings.data[r].splice(coords.col, 0, ''); } } }
[ "function", "(", "coords", ")", "{", "if", "(", "priv", ".", "dataType", "===", "'object'", "||", "priv", ".", "settings", ".", "columns", ")", "{", "throw", "new", "Error", "(", "\"Cannot create new column. When data source in an object, you can only have as much columns as defined in first data row, data schema or in the 'columns' setting\"", ")", ";", "}", "var", "r", "=", "0", ";", "if", "(", "!", "coords", "||", "coords", ".", "col", ">=", "self", ".", "colCount", ")", "{", "for", "(", ";", "r", "<", "self", ".", "rowCount", ";", "r", "++", ")", "{", "if", "(", "typeof", "priv", ".", "settings", ".", "data", "[", "r", "]", "===", "'undefined'", ")", "{", "priv", ".", "settings", ".", "data", "[", "r", "]", "=", "[", "]", ";", "}", "priv", ".", "settings", ".", "data", "[", "r", "]", ".", "push", "(", "''", ")", ";", "}", "}", "else", "{", "for", "(", ";", "r", "<", "self", ".", "rowCount", ";", "r", "++", ")", "{", "priv", ".", "settings", ".", "data", "[", "r", "]", ".", "splice", "(", "coords", ".", "col", ",", "0", ",", "''", ")", ";", "}", "}", "}" ]
Creates col at the right of the data array @param {Object} [coords] Optional. Coords of the cell before which the new column will be inserted
[ "Creates", "col", "at", "the", "right", "of", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L192-L210
41,268
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (coords, toCoords) { if (!coords || coords.row === self.rowCount - 1) { priv.settings.data.pop(); } else { priv.settings.data.splice(coords.row, toCoords.row - coords.row + 1); } }
javascript
function (coords, toCoords) { if (!coords || coords.row === self.rowCount - 1) { priv.settings.data.pop(); } else { priv.settings.data.splice(coords.row, toCoords.row - coords.row + 1); } }
[ "function", "(", "coords", ",", "toCoords", ")", "{", "if", "(", "!", "coords", "||", "coords", ".", "row", "===", "self", ".", "rowCount", "-", "1", ")", "{", "priv", ".", "settings", ".", "data", ".", "pop", "(", ")", ";", "}", "else", "{", "priv", ".", "settings", ".", "data", ".", "splice", "(", "coords", ".", "row", ",", "toCoords", ".", "row", "-", "coords", ".", "row", "+", "1", ")", ";", "}", "}" ]
Removes row at the bottom of the data array @param {Object} [coords] Optional. Coords of the cell which row will be removed @param {Object} [toCoords] Required if coords is defined. Coords of the cell until which all rows will be removed
[ "Removes", "row", "at", "the", "bottom", "of", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L217-L224
41,269
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (coords, toCoords) { if (priv.dataType === 'object' || priv.settings.columns) { throw new Error("cannot remove column with object data source or columns option specified"); } var r = 0; if (!coords || coords.col === self.colCount - 1) { for (; r < self.rowCount; r++) { priv.settings.data[r].pop(); } } else { var howMany = toCoords.col - coords.col + 1; for (; r < self.rowCount; r++) { priv.settings.data[r].splice(coords.col, howMany); } } }
javascript
function (coords, toCoords) { if (priv.dataType === 'object' || priv.settings.columns) { throw new Error("cannot remove column with object data source or columns option specified"); } var r = 0; if (!coords || coords.col === self.colCount - 1) { for (; r < self.rowCount; r++) { priv.settings.data[r].pop(); } } else { var howMany = toCoords.col - coords.col + 1; for (; r < self.rowCount; r++) { priv.settings.data[r].splice(coords.col, howMany); } } }
[ "function", "(", "coords", ",", "toCoords", ")", "{", "if", "(", "priv", ".", "dataType", "===", "'object'", "||", "priv", ".", "settings", ".", "columns", ")", "{", "throw", "new", "Error", "(", "\"cannot remove column with object data source or columns option specified\"", ")", ";", "}", "var", "r", "=", "0", ";", "if", "(", "!", "coords", "||", "coords", ".", "col", "===", "self", ".", "colCount", "-", "1", ")", "{", "for", "(", ";", "r", "<", "self", ".", "rowCount", ";", "r", "++", ")", "{", "priv", ".", "settings", ".", "data", "[", "r", "]", ".", "pop", "(", ")", ";", "}", "}", "else", "{", "var", "howMany", "=", "toCoords", ".", "col", "-", "coords", ".", "col", "+", "1", ";", "for", "(", ";", "r", "<", "self", ".", "rowCount", ";", "r", "++", ")", "{", "priv", ".", "settings", ".", "data", "[", "r", "]", ".", "splice", "(", "coords", ".", "col", ",", "howMany", ")", ";", "}", "}", "}" ]
Removes col at the right of the data array @param {Object} [coords] Optional. Coords of the cell which col will be removed @param {Object} [toCoords] Required if coords is defined. Coords of the cell until which all cols will be removed
[ "Removes", "col", "at", "the", "right", "of", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L231-L247
41,270
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (row, prop) { if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = priv.settings.data[row]; if (!out) { return null; } for (var i = 0, ilen = sliced.length; i < ilen; i++) { out = out[sliced[i]]; if (typeof out === 'undefined') { return null; } } return out; } else { return priv.settings.data[row] ? priv.settings.data[row][prop] : null; } }
javascript
function (row, prop) { if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = priv.settings.data[row]; if (!out) { return null; } for (var i = 0, ilen = sliced.length; i < ilen; i++) { out = out[sliced[i]]; if (typeof out === 'undefined') { return null; } } return out; } else { return priv.settings.data[row] ? priv.settings.data[row][prop] : null; } }
[ "function", "(", "row", ",", "prop", ")", "{", "if", "(", "typeof", "prop", "===", "'string'", "&&", "prop", ".", "indexOf", "(", "'.'", ")", ">", "-", "1", ")", "{", "var", "sliced", "=", "prop", ".", "split", "(", "\".\"", ")", ";", "var", "out", "=", "priv", ".", "settings", ".", "data", "[", "row", "]", ";", "if", "(", "!", "out", ")", "{", "return", "null", ";", "}", "for", "(", "var", "i", "=", "0", ",", "ilen", "=", "sliced", ".", "length", ";", "i", "<", "ilen", ";", "i", "++", ")", "{", "out", "=", "out", "[", "sliced", "[", "i", "]", "]", ";", "if", "(", "typeof", "out", "===", "'undefined'", ")", "{", "return", "null", ";", "}", "}", "return", "out", ";", "}", "else", "{", "return", "priv", ".", "settings", ".", "data", "[", "row", "]", "?", "priv", ".", "settings", ".", "data", "[", "row", "]", "[", "prop", "]", ":", "null", ";", "}", "}" ]
Returns single value from the data array @param {Number} row @param {Number} prop
[ "Returns", "single", "value", "from", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L254-L272
41,271
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (row, prop, value) { if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = priv.settings.data[row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { out = out[sliced[i]]; } out[sliced[i]] = value; } else { priv.settings.data[row][prop] = value; } }
javascript
function (row, prop, value) { if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = priv.settings.data[row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { out = out[sliced[i]]; } out[sliced[i]] = value; } else { priv.settings.data[row][prop] = value; } }
[ "function", "(", "row", ",", "prop", ",", "value", ")", "{", "if", "(", "typeof", "prop", "===", "'string'", "&&", "prop", ".", "indexOf", "(", "'.'", ")", ">", "-", "1", ")", "{", "var", "sliced", "=", "prop", ".", "split", "(", "\".\"", ")", ";", "var", "out", "=", "priv", ".", "settings", ".", "data", "[", "row", "]", ";", "for", "(", "var", "i", "=", "0", ",", "ilen", "=", "sliced", ".", "length", "-", "1", ";", "i", "<", "ilen", ";", "i", "++", ")", "{", "out", "=", "out", "[", "sliced", "[", "i", "]", "]", ";", "}", "out", "[", "sliced", "[", "i", "]", "]", "=", "value", ";", "}", "else", "{", "priv", ".", "settings", ".", "data", "[", "row", "]", "[", "prop", "]", "=", "value", ";", "}", "}" ]
Saves single value to the data array @param {Number} row @param {Number} prop @param {String} value
[ "Saves", "single", "value", "to", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L280-L292
41,272
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { for (var r = 0; r < self.rowCount; r++) { for (var c = 0; c < self.colCount; c++) { datamap.set(r, datamap.colToProp(c), ''); } } }
javascript
function () { for (var r = 0; r < self.rowCount; r++) { for (var c = 0; c < self.colCount; c++) { datamap.set(r, datamap.colToProp(c), ''); } } }
[ "function", "(", ")", "{", "for", "(", "var", "r", "=", "0", ";", "r", "<", "self", ".", "rowCount", ";", "r", "++", ")", "{", "for", "(", "var", "c", "=", "0", ";", "c", "<", "self", ".", "colCount", ";", "c", "++", ")", "{", "datamap", ".", "set", "(", "r", ",", "datamap", ".", "colToProp", "(", "c", ")", ",", "''", ")", ";", "}", "}", "}" ]
Clears the data array
[ "Clears", "the", "data", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L297-L303
41,273
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (start, end) { var r, rlen, c, clen, output = [], row; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(datamap.get(r, datamap.colToProp(c))); } output.push(row); } return output; }
javascript
function (start, end) { var r, rlen, c, clen, output = [], row; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(datamap.get(r, datamap.colToProp(c))); } output.push(row); } return output; }
[ "function", "(", "start", ",", "end", ")", "{", "var", "r", ",", "rlen", ",", "c", ",", "clen", ",", "output", "=", "[", "]", ",", "row", ";", "rlen", "=", "Math", ".", "max", "(", "start", ".", "row", ",", "end", ".", "row", ")", ";", "clen", "=", "Math", ".", "max", "(", "start", ".", "col", ",", "end", ".", "col", ")", ";", "for", "(", "r", "=", "Math", ".", "min", "(", "start", ".", "row", ",", "end", ".", "row", ")", ";", "r", "<=", "rlen", ";", "r", "++", ")", "{", "row", "=", "[", "]", ";", "for", "(", "c", "=", "Math", ".", "min", "(", "start", ".", "col", ",", "end", ".", "col", ")", ";", "c", "<=", "clen", ";", "c", "++", ")", "{", "row", ".", "push", "(", "datamap", ".", "get", "(", "r", ",", "datamap", ".", "colToProp", "(", "c", ")", ")", ")", ";", "}", "output", ".", "push", "(", "row", ")", ";", "}", "return", "output", ";", "}" ]
Returns data range as array @param {Object} start Start selection position @param {Object} end End selection position @return {Array}
[ "Returns", "data", "range", "as", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L319-L331
41,274
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function ($td, cellProperties) { if (priv.isPopulated) { var data = $td.data('readOnly'); if (typeof data === 'undefined') { return !cellProperties.readOnly; } else { return !data; } } return true; }
javascript
function ($td, cellProperties) { if (priv.isPopulated) { var data = $td.data('readOnly'); if (typeof data === 'undefined') { return !cellProperties.readOnly; } else { return !data; } } return true; }
[ "function", "(", "$td", ",", "cellProperties", ")", "{", "if", "(", "priv", ".", "isPopulated", ")", "{", "var", "data", "=", "$td", ".", "data", "(", "'readOnly'", ")", ";", "if", "(", "typeof", "data", "===", "'undefined'", ")", "{", "return", "!", "cellProperties", ".", "readOnly", ";", "}", "else", "{", "return", "!", "data", ";", "}", "}", "return", "true", ";", "}" ]
Is cell writable
[ "Is", "cell", "writable" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L618-L629
41,275
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (start, input, end, source) { var r, rlen, c, clen, td, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } current.row = start.row; current.col = start.col; for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > self.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > self.colCount - 1) || (current.col >= priv.settings.maxCols)) { break; } td = self.view.getCellAtCoords(current); if (self.getCellMeta(current.row, current.col).isWritable) { var p = datamap.colToProp(current.col); setData.push([current.row, p, input[r][c]]); } current.col++; if (end && c === clen - 1) { c = -1; } } current.row++; if (end && r === rlen - 1) { r = -1; } } self.setDataAtCell(setData, null, null, source || 'populateFromArray'); }
javascript
function (start, input, end, source) { var r, rlen, c, clen, td, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } current.row = start.row; current.col = start.col; for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > self.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > self.colCount - 1) || (current.col >= priv.settings.maxCols)) { break; } td = self.view.getCellAtCoords(current); if (self.getCellMeta(current.row, current.col).isWritable) { var p = datamap.colToProp(current.col); setData.push([current.row, p, input[r][c]]); } current.col++; if (end && c === clen - 1) { c = -1; } } current.row++; if (end && r === rlen - 1) { r = -1; } } self.setDataAtCell(setData, null, null, source || 'populateFromArray'); }
[ "function", "(", "start", ",", "input", ",", "end", ",", "source", ")", "{", "var", "r", ",", "rlen", ",", "c", ",", "clen", ",", "td", ",", "setData", "=", "[", "]", ",", "current", "=", "{", "}", ";", "rlen", "=", "input", ".", "length", ";", "if", "(", "rlen", "===", "0", ")", "{", "return", "false", ";", "}", "current", ".", "row", "=", "start", ".", "row", ";", "current", ".", "col", "=", "start", ".", "col", ";", "for", "(", "r", "=", "0", ";", "r", "<", "rlen", ";", "r", "++", ")", "{", "if", "(", "(", "end", "&&", "current", ".", "row", ">", "end", ".", "row", ")", "||", "(", "!", "priv", ".", "settings", ".", "minSpareRows", "&&", "current", ".", "row", ">", "self", ".", "countRows", "(", ")", "-", "1", ")", "||", "(", "current", ".", "row", ">=", "priv", ".", "settings", ".", "maxRows", ")", ")", "{", "break", ";", "}", "current", ".", "col", "=", "start", ".", "col", ";", "clen", "=", "input", "[", "r", "]", "?", "input", "[", "r", "]", ".", "length", ":", "0", ";", "for", "(", "c", "=", "0", ";", "c", "<", "clen", ";", "c", "++", ")", "{", "if", "(", "(", "end", "&&", "current", ".", "col", ">", "end", ".", "col", ")", "||", "(", "!", "priv", ".", "settings", ".", "minSpareCols", "&&", "current", ".", "col", ">", "self", ".", "colCount", "-", "1", ")", "||", "(", "current", ".", "col", ">=", "priv", ".", "settings", ".", "maxCols", ")", ")", "{", "break", ";", "}", "td", "=", "self", ".", "view", ".", "getCellAtCoords", "(", "current", ")", ";", "if", "(", "self", ".", "getCellMeta", "(", "current", ".", "row", ",", "current", ".", "col", ")", ".", "isWritable", ")", "{", "var", "p", "=", "datamap", ".", "colToProp", "(", "current", ".", "col", ")", ";", "setData", ".", "push", "(", "[", "current", ".", "row", ",", "p", ",", "input", "[", "r", "]", "[", "c", "]", "]", ")", ";", "}", "current", ".", "col", "++", ";", "if", "(", "end", "&&", "c", "===", "clen", "-", "1", ")", "{", "c", "=", "-", "1", ";", "}", "}", "current", ".", "row", "++", ";", "if", "(", "end", "&&", "r", "===", "rlen", "-", "1", ")", "{", "r", "=", "-", "1", ";", "}", "}", "self", ".", "setDataAtCell", "(", "setData", ",", "null", ",", "null", ",", "source", "||", "'populateFromArray'", ")", ";", "}" ]
Populate cells at position with 2d array @param {Object} start Start selection position @param {Array} input 2d array @param {Object} [end] End selection position (only for drag-down mode) @param {String} [source="populateFromArray"] @return {Object|undefined} ending td in pasted area (only if any cell was changed)
[ "Populate", "cells", "at", "position", "with", "2d", "array" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L639-L673
41,276
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { var tds = self.view.getAllCells(); for (var i = 0, ilen = tds.length; i < ilen; i++) { $(tds[i]).empty(); self.minWidthFix(tds[i]); } }
javascript
function () { var tds = self.view.getAllCells(); for (var i = 0, ilen = tds.length; i < ilen; i++) { $(tds[i]).empty(); self.minWidthFix(tds[i]); } }
[ "function", "(", ")", "{", "var", "tds", "=", "self", ".", "view", ".", "getAllCells", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "ilen", "=", "tds", ".", "length", ";", "i", "<", "ilen", ";", "i", "++", ")", "{", "$", "(", "tds", "[", "i", "]", ")", ".", "empty", "(", ")", ";", "self", ".", "minWidthFix", "(", "tds", "[", "i", "]", ")", ";", "}", "}" ]
Clears all cells in the grid
[ "Clears", "all", "cells", "in", "the", "grid" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L678-L684
41,277
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (start, end) { var corners = grid.getCornerCoords([start, end]); var r, c, output = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { output.push(self.view.getCellAtCoords({ row: r, col: c })); } } return output; }
javascript
function (start, end) { var corners = grid.getCornerCoords([start, end]); var r, c, output = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { output.push(self.view.getCellAtCoords({ row: r, col: c })); } } return output; }
[ "function", "(", "start", ",", "end", ")", "{", "var", "corners", "=", "grid", ".", "getCornerCoords", "(", "[", "start", ",", "end", "]", ")", ";", "var", "r", ",", "c", ",", "output", "=", "[", "]", ";", "for", "(", "r", "=", "corners", ".", "TL", ".", "row", ";", "r", "<=", "corners", ".", "BR", ".", "row", ";", "r", "++", ")", "{", "for", "(", "c", "=", "corners", ".", "TL", ".", "col", ";", "c", "<=", "corners", ".", "BR", ".", "col", ";", "c", "++", ")", "{", "output", ".", "push", "(", "self", ".", "view", ".", "getCellAtCoords", "(", "{", "row", ":", "r", ",", "col", ":", "c", "}", ")", ")", ";", "}", "}", "return", "output", ";", "}" ]
Returns array of td objects given start and end coordinates
[ "Returns", "array", "of", "td", "objects", "given", "start", "and", "end", "coordinates" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L718-L730
41,278
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (td) { selection.deselect(); priv.selStart = self.view.getCellCoords(td); selection.setRangeEnd(td); }
javascript
function (td) { selection.deselect(); priv.selStart = self.view.getCellCoords(td); selection.setRangeEnd(td); }
[ "function", "(", "td", ")", "{", "selection", ".", "deselect", "(", ")", ";", "priv", ".", "selStart", "=", "self", ".", "view", ".", "getCellCoords", "(", "td", ")", ";", "selection", ".", "setRangeEnd", "(", "td", ")", ";", "}" ]
this public assignment is only temporary Starts selection range on given td object @param td element
[ "this", "public", "assignment", "is", "only", "temporary", "Starts", "selection", "range", "on", "given", "td", "object" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L738-L742
41,279
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (td, scrollToCell) { var coords = self.view.getCellCoords(td); selection.end(coords); if (!priv.settings.multiSelect) { priv.selStart = coords; } self.rootElement.triggerHandler("selection.handsontable", [priv.selStart.row, priv.selStart.col, priv.selEnd.row, priv.selEnd.col]); self.rootElement.triggerHandler("selectionbyprop.handsontable", [priv.selStart.row, datamap.colToProp(priv.selStart.col), priv.selEnd.row, datamap.colToProp(priv.selEnd.col)]); selection.refreshBorders(); if (scrollToCell !== false) { self.view.scrollViewport(td); } }
javascript
function (td, scrollToCell) { var coords = self.view.getCellCoords(td); selection.end(coords); if (!priv.settings.multiSelect) { priv.selStart = coords; } self.rootElement.triggerHandler("selection.handsontable", [priv.selStart.row, priv.selStart.col, priv.selEnd.row, priv.selEnd.col]); self.rootElement.triggerHandler("selectionbyprop.handsontable", [priv.selStart.row, datamap.colToProp(priv.selStart.col), priv.selEnd.row, datamap.colToProp(priv.selEnd.col)]); selection.refreshBorders(); if (scrollToCell !== false) { self.view.scrollViewport(td); } }
[ "function", "(", "td", ",", "scrollToCell", ")", "{", "var", "coords", "=", "self", ".", "view", ".", "getCellCoords", "(", "td", ")", ";", "selection", ".", "end", "(", "coords", ")", ";", "if", "(", "!", "priv", ".", "settings", ".", "multiSelect", ")", "{", "priv", ".", "selStart", "=", "coords", ";", "}", "self", ".", "rootElement", ".", "triggerHandler", "(", "\"selection.handsontable\"", ",", "[", "priv", ".", "selStart", ".", "row", ",", "priv", ".", "selStart", ".", "col", ",", "priv", ".", "selEnd", ".", "row", ",", "priv", ".", "selEnd", ".", "col", "]", ")", ";", "self", ".", "rootElement", ".", "triggerHandler", "(", "\"selectionbyprop.handsontable\"", ",", "[", "priv", ".", "selStart", ".", "row", ",", "datamap", ".", "colToProp", "(", "priv", ".", "selStart", ".", "col", ")", ",", "priv", ".", "selEnd", ".", "row", ",", "datamap", ".", "colToProp", "(", "priv", ".", "selEnd", ".", "col", ")", "]", ")", ";", "selection", ".", "refreshBorders", "(", ")", ";", "if", "(", "scrollToCell", "!==", "false", ")", "{", "self", ".", "view", ".", "scrollViewport", "(", "td", ")", ";", "}", "}" ]
Ends selection range on given td object @param {Element} td @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end
[ "Ends", "selection", "range", "on", "given", "td", "object" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L749-L761
41,280
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (revertOriginal, keepEditor) { if (!keepEditor) { editproxy.destroy(revertOriginal); } if (!selection.isSelected()) { return; } selection.refreshBorderDimensions(); if (!keepEditor) { editproxy.prepare(); } }
javascript
function (revertOriginal, keepEditor) { if (!keepEditor) { editproxy.destroy(revertOriginal); } if (!selection.isSelected()) { return; } selection.refreshBorderDimensions(); if (!keepEditor) { editproxy.prepare(); } }
[ "function", "(", "revertOriginal", ",", "keepEditor", ")", "{", "if", "(", "!", "keepEditor", ")", "{", "editproxy", ".", "destroy", "(", "revertOriginal", ")", ";", "}", "if", "(", "!", "selection", ".", "isSelected", "(", ")", ")", "{", "return", ";", "}", "selection", ".", "refreshBorderDimensions", "(", ")", ";", "if", "(", "!", "keepEditor", ")", "{", "editproxy", ".", "prepare", "(", ")", ";", "}", "}" ]
Destroys editor, redraws borders around cells, prepares editor @param {Boolean} revertOriginal @param {Boolean} keepEditor
[ "Destroys", "editor", "redraws", "borders", "around", "cells", "prepares", "editor" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L768-L779
41,281
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { if (!selection.isSelected()) { return; } if (autofill.handle) { autofill.showHandle(); } priv.currentBorder.appear([priv.selStart]); highlight.on(); }
javascript
function () { if (!selection.isSelected()) { return; } if (autofill.handle) { autofill.showHandle(); } priv.currentBorder.appear([priv.selStart]); highlight.on(); }
[ "function", "(", ")", "{", "if", "(", "!", "selection", ".", "isSelected", "(", ")", ")", "{", "return", ";", "}", "if", "(", "autofill", ".", "handle", ")", "{", "autofill", ".", "showHandle", "(", ")", ";", "}", "priv", ".", "currentBorder", ".", "appear", "(", "[", "priv", ".", "selStart", "]", ")", ";", "highlight", ".", "on", "(", ")", ";", "}" ]
Redraws borders around cells
[ "Redraws", "borders", "around", "cells" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L784-L793
41,282
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { return !(priv.selEnd.col === priv.selStart.col && priv.selEnd.row === priv.selStart.row); }
javascript
function () { return !(priv.selEnd.col === priv.selStart.col && priv.selEnd.row === priv.selStart.row); }
[ "function", "(", ")", "{", "return", "!", "(", "priv", ".", "selEnd", ".", "col", "===", "priv", ".", "selStart", ".", "col", "&&", "priv", ".", "selEnd", ".", "row", "===", "priv", ".", "selStart", ".", "row", ")", ";", "}" ]
Returns information if we have a multiselection @return {Boolean}
[ "Returns", "information", "if", "we", "have", "a", "multiselection" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L819-L821
41,283
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (coords) { if (!selection.isSelected()) { return false; } var sel = grid.getCornerCoords([priv.selStart, priv.selEnd]); return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col); }
javascript
function (coords) { if (!selection.isSelected()) { return false; } var sel = grid.getCornerCoords([priv.selStart, priv.selEnd]); return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col); }
[ "function", "(", "coords", ")", "{", "if", "(", "!", "selection", ".", "isSelected", "(", ")", ")", "{", "return", "false", ";", "}", "var", "sel", "=", "grid", ".", "getCornerCoords", "(", "[", "priv", ".", "selStart", ",", "priv", ".", "selEnd", "]", ")", ";", "return", "(", "sel", ".", "TL", ".", "row", "<=", "coords", ".", "row", "&&", "sel", ".", "BR", ".", "row", ">=", "coords", ".", "row", "&&", "sel", ".", "TL", ".", "col", "<=", "coords", ".", "col", "&&", "sel", ".", "BR", ".", "col", ">=", "coords", ".", "col", ")", ";", "}" ]
Returns true if coords is within current selection coords @return {Boolean}
[ "Returns", "true", "if", "coords", "is", "within", "current", "selection", "coords" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L896-L902
41,284
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { if (!selection.isSelected()) { return; } highlight.off(); priv.currentBorder.disappear(); if (autofill.handle) { autofill.hideHandle(); } selection.end(false); editproxy.destroy(); self.rootElement.triggerHandler('deselect.handsontable'); }
javascript
function () { if (!selection.isSelected()) { return; } highlight.off(); priv.currentBorder.disappear(); if (autofill.handle) { autofill.hideHandle(); } selection.end(false); editproxy.destroy(); self.rootElement.triggerHandler('deselect.handsontable'); }
[ "function", "(", ")", "{", "if", "(", "!", "selection", ".", "isSelected", "(", ")", ")", "{", "return", ";", "}", "highlight", ".", "off", "(", ")", ";", "priv", ".", "currentBorder", ".", "disappear", "(", ")", ";", "if", "(", "autofill", ".", "handle", ")", "{", "autofill", ".", "hideHandle", "(", ")", ";", "}", "selection", ".", "end", "(", "false", ")", ";", "editproxy", ".", "destroy", "(", ")", ";", "self", ".", "rootElement", ".", "triggerHandler", "(", "'deselect.handsontable'", ")", ";", "}" ]
Deselects all selected cells
[ "Deselects", "all", "selected", "cells" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L907-L919
41,285
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { if (!priv.settings.multiSelect) { return; } var tds = self.view.getAllCells(); if (tds.length) { selection.setRangeStart(tds[0]); selection.setRangeEnd(tds[tds.length - 1], false); } }
javascript
function () { if (!priv.settings.multiSelect) { return; } var tds = self.view.getAllCells(); if (tds.length) { selection.setRangeStart(tds[0]); selection.setRangeEnd(tds[tds.length - 1], false); } }
[ "function", "(", ")", "{", "if", "(", "!", "priv", ".", "settings", ".", "multiSelect", ")", "{", "return", ";", "}", "var", "tds", "=", "self", ".", "view", ".", "getAllCells", "(", ")", ";", "if", "(", "tds", ".", "length", ")", "{", "selection", ".", "setRangeStart", "(", "tds", "[", "0", "]", ")", ";", "selection", ".", "setRangeEnd", "(", "tds", "[", "tds", ".", "length", "-", "1", "]", ",", "false", ")", ";", "}", "}" ]
Select all cells
[ "Select", "all", "cells" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L924-L933
41,286
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { if (!selection.isSelected()) { return; } var corners = grid.getCornerCoords([priv.selStart, selection.end()]); var r, c, changes = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { if (self.getCellMeta(r, c).isWritable) { changes.push([r, datamap.colToProp(c), '']); } } } self.setDataAtCell(changes); }
javascript
function () { if (!selection.isSelected()) { return; } var corners = grid.getCornerCoords([priv.selStart, selection.end()]); var r, c, changes = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { if (self.getCellMeta(r, c).isWritable) { changes.push([r, datamap.colToProp(c), '']); } } } self.setDataAtCell(changes); }
[ "function", "(", ")", "{", "if", "(", "!", "selection", ".", "isSelected", "(", ")", ")", "{", "return", ";", "}", "var", "corners", "=", "grid", ".", "getCornerCoords", "(", "[", "priv", ".", "selStart", ",", "selection", ".", "end", "(", ")", "]", ")", ";", "var", "r", ",", "c", ",", "changes", "=", "[", "]", ";", "for", "(", "r", "=", "corners", ".", "TL", ".", "row", ";", "r", "<=", "corners", ".", "BR", ".", "row", ";", "r", "++", ")", "{", "for", "(", "c", "=", "corners", ".", "TL", ".", "col", ";", "c", "<=", "corners", ".", "BR", ".", "col", ";", "c", "++", ")", "{", "if", "(", "self", ".", "getCellMeta", "(", "r", ",", "c", ")", ".", "isWritable", ")", "{", "changes", ".", "push", "(", "[", "r", ",", "datamap", ".", "colToProp", "(", "c", ")", ",", "''", "]", ")", ";", "}", "}", "}", "self", ".", "setDataAtCell", "(", "changes", ")", ";", "}" ]
Deletes data from selected cells
[ "Deletes", "data", "from", "selected", "cells" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L938-L952
41,287
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { if (!selection.isSelected()) { return false; } if (selection.isMultiple()) { priv.selectionBorder.appear([priv.selStart, selection.end()]); } else { priv.selectionBorder.disappear(); } }
javascript
function () { if (!selection.isSelected()) { return false; } if (selection.isMultiple()) { priv.selectionBorder.appear([priv.selStart, selection.end()]); } else { priv.selectionBorder.disappear(); } }
[ "function", "(", ")", "{", "if", "(", "!", "selection", ".", "isSelected", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "selection", ".", "isMultiple", "(", ")", ")", "{", "priv", ".", "selectionBorder", ".", "appear", "(", "[", "priv", ".", "selStart", ",", "selection", ".", "end", "(", ")", "]", ")", ";", "}", "else", "{", "priv", ".", "selectionBorder", ".", "disappear", "(", ")", ";", "}", "}" ]
Show border around selected cells
[ "Show", "border", "around", "selected", "cells" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L969-L979
41,288
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { if (!autofill.handle) { autofill.handle = new Handsontable.FillHandle(self); autofill.fillBorder = new Handsontable.Border(self, { className: 'htFillBorder' }); $(autofill.handle.handle).on('dblclick', autofill.selectAdjacent); } else { autofill.handle.disabled = false; autofill.fillBorder.disabled = false; } self.rootElement.on('beginediting.handsontable', function () { autofill.hideHandle(); }); self.rootElement.on('finishediting.handsontable', function () { if (selection.isSelected()) { autofill.showHandle(); } }); }
javascript
function () { if (!autofill.handle) { autofill.handle = new Handsontable.FillHandle(self); autofill.fillBorder = new Handsontable.Border(self, { className: 'htFillBorder' }); $(autofill.handle.handle).on('dblclick', autofill.selectAdjacent); } else { autofill.handle.disabled = false; autofill.fillBorder.disabled = false; } self.rootElement.on('beginediting.handsontable', function () { autofill.hideHandle(); }); self.rootElement.on('finishediting.handsontable', function () { if (selection.isSelected()) { autofill.showHandle(); } }); }
[ "function", "(", ")", "{", "if", "(", "!", "autofill", ".", "handle", ")", "{", "autofill", ".", "handle", "=", "new", "Handsontable", ".", "FillHandle", "(", "self", ")", ";", "autofill", ".", "fillBorder", "=", "new", "Handsontable", ".", "Border", "(", "self", ",", "{", "className", ":", "'htFillBorder'", "}", ")", ";", "$", "(", "autofill", ".", "handle", ".", "handle", ")", ".", "on", "(", "'dblclick'", ",", "autofill", ".", "selectAdjacent", ")", ";", "}", "else", "{", "autofill", ".", "handle", ".", "disabled", "=", "false", ";", "autofill", ".", "fillBorder", ".", "disabled", "=", "false", ";", "}", "self", ".", "rootElement", ".", "on", "(", "'beginediting.handsontable'", ",", "function", "(", ")", "{", "autofill", ".", "hideHandle", "(", ")", ";", "}", ")", ";", "self", ".", "rootElement", ".", "on", "(", "'finishediting.handsontable'", ",", "function", "(", ")", "{", "if", "(", "selection", ".", "isSelected", "(", ")", ")", "{", "autofill", ".", "showHandle", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create fill handle and fill border objects
[ "Create", "fill", "handle", "and", "fill", "border", "objects" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L999-L1022
41,289
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { var select, data, r, maxR, c; if (selection.isMultiple()) { select = priv.selectionBorder.corners; } else { select = priv.currentBorder.corners; } autofill.fillBorder.disappear(); data = datamap.getAll(); rows : for (r = select.BR.row + 1; r < self.rowCount; r++) { for (c = select.TL.col; c <= select.BR.col; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select.TL.col - 1] || !!data[r][select.BR.col + 1]) { maxR = r; } } if (maxR) { autofill.showBorder(self.view.getCellAtCoords({row: maxR, col: select.BR.col})); autofill.apply(); } }
javascript
function () { var select, data, r, maxR, c; if (selection.isMultiple()) { select = priv.selectionBorder.corners; } else { select = priv.currentBorder.corners; } autofill.fillBorder.disappear(); data = datamap.getAll(); rows : for (r = select.BR.row + 1; r < self.rowCount; r++) { for (c = select.TL.col; c <= select.BR.col; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select.TL.col - 1] || !!data[r][select.BR.col + 1]) { maxR = r; } } if (maxR) { autofill.showBorder(self.view.getCellAtCoords({row: maxR, col: select.BR.col})); autofill.apply(); } }
[ "function", "(", ")", "{", "var", "select", ",", "data", ",", "r", ",", "maxR", ",", "c", ";", "if", "(", "selection", ".", "isMultiple", "(", ")", ")", "{", "select", "=", "priv", ".", "selectionBorder", ".", "corners", ";", "}", "else", "{", "select", "=", "priv", ".", "currentBorder", ".", "corners", ";", "}", "autofill", ".", "fillBorder", ".", "disappear", "(", ")", ";", "data", "=", "datamap", ".", "getAll", "(", ")", ";", "rows", ":", "for", "(", "r", "=", "select", ".", "BR", ".", "row", "+", "1", ";", "r", "<", "self", ".", "rowCount", ";", "r", "++", ")", "{", "for", "(", "c", "=", "select", ".", "TL", ".", "col", ";", "c", "<=", "select", ".", "BR", ".", "col", ";", "c", "++", ")", "{", "if", "(", "data", "[", "r", "]", "[", "c", "]", ")", "{", "break", "rows", ";", "}", "}", "if", "(", "!", "!", "data", "[", "r", "]", "[", "select", ".", "TL", ".", "col", "-", "1", "]", "||", "!", "!", "data", "[", "r", "]", "[", "select", ".", "BR", ".", "col", "+", "1", "]", ")", "{", "maxR", "=", "r", ";", "}", "}", "if", "(", "maxR", ")", "{", "autofill", ".", "showBorder", "(", "self", ".", "view", ".", "getCellAtCoords", "(", "{", "row", ":", "maxR", ",", "col", ":", "select", ".", "BR", ".", "col", "}", ")", ")", ";", "autofill", ".", "apply", "(", ")", ";", "}", "}" ]
Selects cells down to the last row in the left column, then fills down to that cell
[ "Selects", "cells", "down", "to", "the", "last", "row", "in", "the", "left", "column", "then", "fills", "down", "to", "that", "cell" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L1035-L1062
41,290
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { var drag, select, start, end; autofill.handle.isDragged = 0; drag = autofill.fillBorder.corners; if (!drag) { return; } autofill.fillBorder.disappear(); if (selection.isMultiple()) { select = priv.selectionBorder.corners; } else { select = priv.currentBorder.corners; } if (drag.TL.row === select.TL.row && drag.TL.col < select.TL.col) { start = drag.TL; end = { row: drag.BR.row, col: select.TL.col - 1 }; } else if (drag.TL.row === select.TL.row && drag.BR.col > select.BR.col) { start = { row: drag.TL.row, col: select.BR.col + 1 }; end = drag.BR; } else if (drag.TL.row < select.TL.row && drag.TL.col === select.TL.col) { start = drag.TL; end = { row: select.TL.row - 1, col: drag.BR.col }; } else if (drag.BR.row > select.BR.row && drag.TL.col === select.TL.col) { start = { row: select.BR.row + 1, col: drag.TL.col }; end = drag.BR; } if (start) { grid.populateFromArray(start, SheetClip.parse(priv.editProxy.val()), end, 'autofill'); selection.setRangeStart(self.view.getCellAtCoords(drag.TL)); selection.setRangeEnd(self.view.getCellAtCoords(drag.BR)); } else { //reset to avoid some range bug selection.refreshBorders(); } }
javascript
function () { var drag, select, start, end; autofill.handle.isDragged = 0; drag = autofill.fillBorder.corners; if (!drag) { return; } autofill.fillBorder.disappear(); if (selection.isMultiple()) { select = priv.selectionBorder.corners; } else { select = priv.currentBorder.corners; } if (drag.TL.row === select.TL.row && drag.TL.col < select.TL.col) { start = drag.TL; end = { row: drag.BR.row, col: select.TL.col - 1 }; } else if (drag.TL.row === select.TL.row && drag.BR.col > select.BR.col) { start = { row: drag.TL.row, col: select.BR.col + 1 }; end = drag.BR; } else if (drag.TL.row < select.TL.row && drag.TL.col === select.TL.col) { start = drag.TL; end = { row: select.TL.row - 1, col: drag.BR.col }; } else if (drag.BR.row > select.BR.row && drag.TL.col === select.TL.col) { start = { row: select.BR.row + 1, col: drag.TL.col }; end = drag.BR; } if (start) { grid.populateFromArray(start, SheetClip.parse(priv.editProxy.val()), end, 'autofill'); selection.setRangeStart(self.view.getCellAtCoords(drag.TL)); selection.setRangeEnd(self.view.getCellAtCoords(drag.BR)); } else { //reset to avoid some range bug selection.refreshBorders(); } }
[ "function", "(", ")", "{", "var", "drag", ",", "select", ",", "start", ",", "end", ";", "autofill", ".", "handle", ".", "isDragged", "=", "0", ";", "drag", "=", "autofill", ".", "fillBorder", ".", "corners", ";", "if", "(", "!", "drag", ")", "{", "return", ";", "}", "autofill", ".", "fillBorder", ".", "disappear", "(", ")", ";", "if", "(", "selection", ".", "isMultiple", "(", ")", ")", "{", "select", "=", "priv", ".", "selectionBorder", ".", "corners", ";", "}", "else", "{", "select", "=", "priv", ".", "currentBorder", ".", "corners", ";", "}", "if", "(", "drag", ".", "TL", ".", "row", "===", "select", ".", "TL", ".", "row", "&&", "drag", ".", "TL", ".", "col", "<", "select", ".", "TL", ".", "col", ")", "{", "start", "=", "drag", ".", "TL", ";", "end", "=", "{", "row", ":", "drag", ".", "BR", ".", "row", ",", "col", ":", "select", ".", "TL", ".", "col", "-", "1", "}", ";", "}", "else", "if", "(", "drag", ".", "TL", ".", "row", "===", "select", ".", "TL", ".", "row", "&&", "drag", ".", "BR", ".", "col", ">", "select", ".", "BR", ".", "col", ")", "{", "start", "=", "{", "row", ":", "drag", ".", "TL", ".", "row", ",", "col", ":", "select", ".", "BR", ".", "col", "+", "1", "}", ";", "end", "=", "drag", ".", "BR", ";", "}", "else", "if", "(", "drag", ".", "TL", ".", "row", "<", "select", ".", "TL", ".", "row", "&&", "drag", ".", "TL", ".", "col", "===", "select", ".", "TL", ".", "col", ")", "{", "start", "=", "drag", ".", "TL", ";", "end", "=", "{", "row", ":", "select", ".", "TL", ".", "row", "-", "1", ",", "col", ":", "drag", ".", "BR", ".", "col", "}", ";", "}", "else", "if", "(", "drag", ".", "BR", ".", "row", ">", "select", ".", "BR", ".", "row", "&&", "drag", ".", "TL", ".", "col", "===", "select", ".", "TL", ".", "col", ")", "{", "start", "=", "{", "row", ":", "select", ".", "BR", ".", "row", "+", "1", ",", "col", ":", "drag", ".", "TL", ".", "col", "}", ";", "end", "=", "drag", ".", "BR", ";", "}", "if", "(", "start", ")", "{", "grid", ".", "populateFromArray", "(", "start", ",", "SheetClip", ".", "parse", "(", "priv", ".", "editProxy", ".", "val", "(", ")", ")", ",", "end", ",", "'autofill'", ")", ";", "selection", ".", "setRangeStart", "(", "self", ".", "view", ".", "getCellAtCoords", "(", "drag", ".", "TL", ")", ")", ";", "selection", ".", "setRangeEnd", "(", "self", ".", "view", ".", "getCellAtCoords", "(", "drag", ".", "BR", ")", ")", ";", "}", "else", "{", "//reset to avoid some range bug", "selection", ".", "refreshBorders", "(", ")", ";", "}", "}" ]
Apply fill values to the area in fill border, omitting the selection border
[ "Apply", "fill", "values", "to", "the", "area", "in", "fill", "border", "omitting", "the", "selection", "border" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L1067-L1125
41,291
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (td) { var coords = self.view.getCellCoords(td); var corners = grid.getCornerCoords([priv.selStart, priv.selEnd]); if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) { coords = {row: coords.row, col: corners.BR.col}; } else if (priv.settings.fillHandle !== 'vertical') { coords = {row: corners.BR.row, col: coords.col}; } else { return; //wrong direction } autofill.fillBorder.appear([priv.selStart, priv.selEnd, coords]); }
javascript
function (td) { var coords = self.view.getCellCoords(td); var corners = grid.getCornerCoords([priv.selStart, priv.selEnd]); if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) { coords = {row: coords.row, col: corners.BR.col}; } else if (priv.settings.fillHandle !== 'vertical') { coords = {row: corners.BR.row, col: coords.col}; } else { return; //wrong direction } autofill.fillBorder.appear([priv.selStart, priv.selEnd, coords]); }
[ "function", "(", "td", ")", "{", "var", "coords", "=", "self", ".", "view", ".", "getCellCoords", "(", "td", ")", ";", "var", "corners", "=", "grid", ".", "getCornerCoords", "(", "[", "priv", ".", "selStart", ",", "priv", ".", "selEnd", "]", ")", ";", "if", "(", "priv", ".", "settings", ".", "fillHandle", "!==", "'horizontal'", "&&", "(", "corners", ".", "BR", ".", "row", "<", "coords", ".", "row", "||", "corners", ".", "TL", ".", "row", ">", "coords", ".", "row", ")", ")", "{", "coords", "=", "{", "row", ":", "coords", ".", "row", ",", "col", ":", "corners", ".", "BR", ".", "col", "}", ";", "}", "else", "if", "(", "priv", ".", "settings", ".", "fillHandle", "!==", "'vertical'", ")", "{", "coords", "=", "{", "row", ":", "corners", ".", "BR", ".", "row", ",", "col", ":", "coords", ".", "col", "}", ";", "}", "else", "{", "return", ";", "//wrong direction", "}", "autofill", ".", "fillBorder", ".", "appear", "(", "[", "priv", ".", "selStart", ",", "priv", ".", "selEnd", ",", "coords", "]", ")", ";", "}" ]
Show fill border
[ "Show", "fill", "border" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L1144-L1157
41,292
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function () { priv.editProxy.height(priv.editProxy.parent().innerHeight() - 4); priv.editProxy.val(datamap.getText(priv.selStart, priv.selEnd)); setTimeout(editproxy.focus, 1); priv.editorDestroyer = self.view.applyCellTypeMethod('editor', self.view.getCellAtCoords(priv.selStart), priv.selStart, priv.editProxy); }
javascript
function () { priv.editProxy.height(priv.editProxy.parent().innerHeight() - 4); priv.editProxy.val(datamap.getText(priv.selStart, priv.selEnd)); setTimeout(editproxy.focus, 1); priv.editorDestroyer = self.view.applyCellTypeMethod('editor', self.view.getCellAtCoords(priv.selStart), priv.selStart, priv.editProxy); }
[ "function", "(", ")", "{", "priv", ".", "editProxy", ".", "height", "(", "priv", ".", "editProxy", ".", "parent", "(", ")", ".", "innerHeight", "(", ")", "-", "4", ")", ";", "priv", ".", "editProxy", ".", "val", "(", "datamap", ".", "getText", "(", "priv", ".", "selStart", ",", "priv", ".", "selEnd", ")", ")", ";", "setTimeout", "(", "editproxy", ".", "focus", ",", "1", ")", ";", "priv", ".", "editorDestroyer", "=", "self", ".", "view", ".", "applyCellTypeMethod", "(", "'editor'", ",", "self", ".", "view", ".", "getCellAtCoords", "(", "priv", ".", "selStart", ")", ",", "priv", ".", "selStart", ",", "priv", ".", "editProxy", ")", ";", "}" ]
Prepare text input to be displayed at given grid cell
[ "Prepare", "text", "input", "to", "be", "displayed", "at", "given", "grid", "cell" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L1357-L1362
41,293
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (i) { var deferred = $.Deferred(); deferreds.push(deferred); var originalVal = changes[i][3]; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function (source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; //perfect match break; } else if (lowercaseVal === source[s].toLowerCase()) { changes[i][3] = source[s]; //good match, fix the case found = true; break; } } if (!found) { changes[i] = null; } deferred.resolve(); } }
javascript
function (i) { var deferred = $.Deferred(); deferreds.push(deferred); var originalVal = changes[i][3]; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function (source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; //perfect match break; } else if (lowercaseVal === source[s].toLowerCase()) { changes[i][3] = source[s]; //good match, fix the case found = true; break; } } if (!found) { changes[i] = null; } deferred.resolve(); } }
[ "function", "(", "i", ")", "{", "var", "deferred", "=", "$", ".", "Deferred", "(", ")", ";", "deferreds", ".", "push", "(", "deferred", ")", ";", "var", "originalVal", "=", "changes", "[", "i", "]", "[", "3", "]", ";", "var", "lowercaseVal", "=", "typeof", "originalVal", "===", "'string'", "?", "originalVal", ".", "toLowerCase", "(", ")", ":", "null", ";", "return", "function", "(", "source", ")", "{", "var", "found", "=", "false", ";", "for", "(", "var", "s", "=", "0", ",", "slen", "=", "source", ".", "length", ";", "s", "<", "slen", ";", "s", "++", ")", "{", "if", "(", "originalVal", "===", "source", "[", "s", "]", ")", "{", "found", "=", "true", ";", "//perfect match", "break", ";", "}", "else", "if", "(", "lowercaseVal", "===", "source", "[", "s", "]", ".", "toLowerCase", "(", ")", ")", "{", "changes", "[", "i", "]", "[", "3", "]", "=", "source", "[", "s", "]", ";", "//good match, fix the case", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "found", ")", "{", "changes", "[", "i", "]", "=", "null", ";", "}", "deferred", ".", "resolve", "(", ")", ";", "}", "}" ]
validate strict autocompletes
[ "validate", "strict", "autocompletes" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L1396-L1421
41,294
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (keyboardProxy) { var el = keyboardProxy[0]; if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }
javascript
function (keyboardProxy) { var el = keyboardProxy[0]; if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }
[ "function", "(", "keyboardProxy", ")", "{", "var", "el", "=", "keyboardProxy", "[", "0", "]", ";", "if", "(", "el", ".", "selectionStart", ")", "{", "return", "el", ".", "selectionStart", ";", "}", "else", "if", "(", "document", ".", "selection", ")", "{", "el", ".", "focus", "(", ")", ";", "var", "r", "=", "document", ".", "selection", ".", "createRange", "(", ")", ";", "if", "(", "r", "==", "null", ")", "{", "return", "0", ";", "}", "var", "re", "=", "el", ".", "createTextRange", "(", ")", ",", "rc", "=", "re", ".", "duplicate", "(", ")", ";", "re", ".", "moveToBookmark", "(", "r", ".", "getBookmark", "(", ")", ")", ";", "rc", ".", "setEndPoint", "(", "'EndToStart'", ",", "re", ")", ";", "return", "rc", ".", "text", ".", "length", ";", "}", "return", "0", ";", "}" ]
Returns caret position in edit proxy @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea @return {Number}
[ "Returns", "caret", "position", "in", "edit", "proxy" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L3569-L3587
41,295
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (keyboardProxy, pos) { var el = keyboardProxy[0]; if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, pos); } else if (el.createTextRange) { var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }
javascript
function (keyboardProxy, pos) { var el = keyboardProxy[0]; if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, pos); } else if (el.createTextRange) { var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }
[ "function", "(", "keyboardProxy", ",", "pos", ")", "{", "var", "el", "=", "keyboardProxy", "[", "0", "]", ";", "if", "(", "el", ".", "setSelectionRange", ")", "{", "el", ".", "focus", "(", ")", ";", "el", ".", "setSelectionRange", "(", "pos", ",", "pos", ")", ";", "}", "else", "if", "(", "el", ".", "createTextRange", ")", "{", "var", "range", "=", "el", ".", "createTextRange", "(", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "range", ".", "moveEnd", "(", "'character'", ",", "pos", ")", ";", "range", ".", "moveStart", "(", "'character'", ",", "pos", ")", ";", "range", ".", "select", "(", ")", ";", "}", "}" ]
Sets caret position in edit proxy @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ @param {Number}
[ "Sets", "caret", "position", "in", "edit", "proxy" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L3594-L3607
41,296
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (instance, td, row, col, prop, keyboardProxy, useOriginalValue, suffix) { if (texteditor.isCellEdited) { return; } keyboardProxy.on('cut.editor', function (event) { event.stopPropagation(); }); keyboardProxy.on('paste.editor', function (event) { event.stopPropagation(); }); var $td = $(td); if (!instance.getCellMeta(row, col).isWritable) { return; } texteditor.isCellEdited = true; if (useOriginalValue) { var original = instance.getDataAtCell(row, prop); original = Handsontable.helper.stringify(original) + (suffix || ''); keyboardProxy.val(original); texteditor.setCaretPosition(keyboardProxy, original.length); } else { keyboardProxy.val(''); } texteditor.refreshDimensions(instance, $td, keyboardProxy); keyboardProxy.parent().removeClass('htHidden'); instance.rootElement.triggerHandler('beginediting.handsontable'); setTimeout(function () { //async fix for Firefox 3.6.28 (needs manual testing) keyboardProxy.parent().css({ overflow: 'visible' }); }, 1); }
javascript
function (instance, td, row, col, prop, keyboardProxy, useOriginalValue, suffix) { if (texteditor.isCellEdited) { return; } keyboardProxy.on('cut.editor', function (event) { event.stopPropagation(); }); keyboardProxy.on('paste.editor', function (event) { event.stopPropagation(); }); var $td = $(td); if (!instance.getCellMeta(row, col).isWritable) { return; } texteditor.isCellEdited = true; if (useOriginalValue) { var original = instance.getDataAtCell(row, prop); original = Handsontable.helper.stringify(original) + (suffix || ''); keyboardProxy.val(original); texteditor.setCaretPosition(keyboardProxy, original.length); } else { keyboardProxy.val(''); } texteditor.refreshDimensions(instance, $td, keyboardProxy); keyboardProxy.parent().removeClass('htHidden'); instance.rootElement.triggerHandler('beginediting.handsontable'); setTimeout(function () { //async fix for Firefox 3.6.28 (needs manual testing) keyboardProxy.parent().css({ overflow: 'visible' }); }, 1); }
[ "function", "(", "instance", ",", "td", ",", "row", ",", "col", ",", "prop", ",", "keyboardProxy", ",", "useOriginalValue", ",", "suffix", ")", "{", "if", "(", "texteditor", ".", "isCellEdited", ")", "{", "return", ";", "}", "keyboardProxy", ".", "on", "(", "'cut.editor'", ",", "function", "(", "event", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "}", ")", ";", "keyboardProxy", ".", "on", "(", "'paste.editor'", ",", "function", "(", "event", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "}", ")", ";", "var", "$td", "=", "$", "(", "td", ")", ";", "if", "(", "!", "instance", ".", "getCellMeta", "(", "row", ",", "col", ")", ".", "isWritable", ")", "{", "return", ";", "}", "texteditor", ".", "isCellEdited", "=", "true", ";", "if", "(", "useOriginalValue", ")", "{", "var", "original", "=", "instance", ".", "getDataAtCell", "(", "row", ",", "prop", ")", ";", "original", "=", "Handsontable", ".", "helper", ".", "stringify", "(", "original", ")", "+", "(", "suffix", "||", "''", ")", ";", "keyboardProxy", ".", "val", "(", "original", ")", ";", "texteditor", ".", "setCaretPosition", "(", "keyboardProxy", ",", "original", ".", "length", ")", ";", "}", "else", "{", "keyboardProxy", ".", "val", "(", "''", ")", ";", "}", "texteditor", ".", "refreshDimensions", "(", "instance", ",", "$td", ",", "keyboardProxy", ")", ";", "keyboardProxy", ".", "parent", "(", ")", ".", "removeClass", "(", "'htHidden'", ")", ";", "instance", ".", "rootElement", ".", "triggerHandler", "(", "'beginediting.handsontable'", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "//async fix for Firefox 3.6.28 (needs manual testing)", "keyboardProxy", ".", "parent", "(", ")", ".", "css", "(", "{", "overflow", ":", "'visible'", "}", ")", ";", "}", ",", "1", ")", ";", "}" ]
Shows text input in grid cell
[ "Shows", "text", "input", "in", "grid", "cell" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L3612-L3654
41,297
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function (instance, td, row, col, prop, keyboardProxy, isCancelled, ctrlDown) { if (texteditor.triggerOnlyByDestroyer) { return; } if (texteditor.isCellEdited) { texteditor.isCellEdited = false; var val; if (isCancelled) { val = [ [texteditor.originalValue] ]; } else { val = [ [$.trim(keyboardProxy.val())] ]; } if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) var sel = instance.handsontable('getSelected'); instance.populateFromArray({row: sel[0], col: sel[1]}, val, {row: sel[2], col: sel[3]}, false, 'edit'); } else { instance.populateFromArray({row: row, col: col}, val, null, false, 'edit'); } } keyboardProxy.off(".editor"); $(td).off('.editor'); keyboardProxy.css({ width: 0, height: 0 }); keyboardProxy.parent().addClass('htHidden').css({ overflow: 'hidden' }); instance.container.find('.htBorder.current').off('.editor'); instance.rootElement.triggerHandler('finishediting.handsontable'); }
javascript
function (instance, td, row, col, prop, keyboardProxy, isCancelled, ctrlDown) { if (texteditor.triggerOnlyByDestroyer) { return; } if (texteditor.isCellEdited) { texteditor.isCellEdited = false; var val; if (isCancelled) { val = [ [texteditor.originalValue] ]; } else { val = [ [$.trim(keyboardProxy.val())] ]; } if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) var sel = instance.handsontable('getSelected'); instance.populateFromArray({row: sel[0], col: sel[1]}, val, {row: sel[2], col: sel[3]}, false, 'edit'); } else { instance.populateFromArray({row: row, col: col}, val, null, false, 'edit'); } } keyboardProxy.off(".editor"); $(td).off('.editor'); keyboardProxy.css({ width: 0, height: 0 }); keyboardProxy.parent().addClass('htHidden').css({ overflow: 'hidden' }); instance.container.find('.htBorder.current').off('.editor'); instance.rootElement.triggerHandler('finishediting.handsontable'); }
[ "function", "(", "instance", ",", "td", ",", "row", ",", "col", ",", "prop", ",", "keyboardProxy", ",", "isCancelled", ",", "ctrlDown", ")", "{", "if", "(", "texteditor", ".", "triggerOnlyByDestroyer", ")", "{", "return", ";", "}", "if", "(", "texteditor", ".", "isCellEdited", ")", "{", "texteditor", ".", "isCellEdited", "=", "false", ";", "var", "val", ";", "if", "(", "isCancelled", ")", "{", "val", "=", "[", "[", "texteditor", ".", "originalValue", "]", "]", ";", "}", "else", "{", "val", "=", "[", "[", "$", ".", "trim", "(", "keyboardProxy", ".", "val", "(", ")", ")", "]", "]", ";", "}", "if", "(", "ctrlDown", ")", "{", "//if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)", "var", "sel", "=", "instance", ".", "handsontable", "(", "'getSelected'", ")", ";", "instance", ".", "populateFromArray", "(", "{", "row", ":", "sel", "[", "0", "]", ",", "col", ":", "sel", "[", "1", "]", "}", ",", "val", ",", "{", "row", ":", "sel", "[", "2", "]", ",", "col", ":", "sel", "[", "3", "]", "}", ",", "false", ",", "'edit'", ")", ";", "}", "else", "{", "instance", ".", "populateFromArray", "(", "{", "row", ":", "row", ",", "col", ":", "col", "}", ",", "val", ",", "null", ",", "false", ",", "'edit'", ")", ";", "}", "}", "keyboardProxy", ".", "off", "(", "\".editor\"", ")", ";", "$", "(", "td", ")", ".", "off", "(", "'.editor'", ")", ";", "keyboardProxy", ".", "css", "(", "{", "width", ":", "0", ",", "height", ":", "0", "}", ")", ";", "keyboardProxy", ".", "parent", "(", ")", ".", "addClass", "(", "'htHidden'", ")", ".", "css", "(", "{", "overflow", ":", "'hidden'", "}", ")", ";", "instance", ".", "container", ".", "find", "(", "'.htBorder.current'", ")", ".", "off", "(", "'.editor'", ")", ";", "instance", ".", "rootElement", ".", "triggerHandler", "(", "'finishediting.handsontable'", ")", ";", "}" ]
Finishes text input in selected cells
[ "Finishes", "text", "input", "in", "selected", "cells" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L3685-L3723
41,298
billroy/bitlash-commander
public/js/handsontable/jquery.handsontable.full.js
function(e) { var $this = $(this); // disable actual context-menu e.preventDefault(); e.stopImmediatePropagation(); // abort native-triggered events unless we're triggering on right click if (e.data.trigger != 'right' && e.originalEvent) { return; } if (!$this.hasClass('context-menu-disabled')) { // theoretically need to fire a show event at <menu> // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); // e.data.$menu.trigger(evt); $currentTrigger = $this; if (e.data.build) { var built = e.data.build($currentTrigger, e); // abort if build() returned false if (built === false) { return; } // dynamically build menu on invocation e.data = $.extend(true, {}, defaults, e.data, built || {}); // abort if there are no items to display if (!e.data.items || $.isEmptyObject(e.data.items)) { // Note: jQuery captures and ignores errors from event handlers if (window.console) { (console.error || console.log)("No items specified to show in contextMenu"); } throw new Error('No Items sepcified'); } // backreference for custom command type creation e.data.$trigger = $currentTrigger; op.create(e.data); } // show menu op.show.call($this, e.data, e.pageX, e.pageY); } }
javascript
function(e) { var $this = $(this); // disable actual context-menu e.preventDefault(); e.stopImmediatePropagation(); // abort native-triggered events unless we're triggering on right click if (e.data.trigger != 'right' && e.originalEvent) { return; } if (!$this.hasClass('context-menu-disabled')) { // theoretically need to fire a show event at <menu> // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); // e.data.$menu.trigger(evt); $currentTrigger = $this; if (e.data.build) { var built = e.data.build($currentTrigger, e); // abort if build() returned false if (built === false) { return; } // dynamically build menu on invocation e.data = $.extend(true, {}, defaults, e.data, built || {}); // abort if there are no items to display if (!e.data.items || $.isEmptyObject(e.data.items)) { // Note: jQuery captures and ignores errors from event handlers if (window.console) { (console.error || console.log)("No items specified to show in contextMenu"); } throw new Error('No Items sepcified'); } // backreference for custom command type creation e.data.$trigger = $currentTrigger; op.create(e.data); } // show menu op.show.call($this, e.data, e.pageX, e.pageY); } }
[ "function", "(", "e", ")", "{", "var", "$this", "=", "$", "(", "this", ")", ";", "// disable actual context-menu", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "stopImmediatePropagation", "(", ")", ";", "// abort native-triggered events unless we're triggering on right click", "if", "(", "e", ".", "data", ".", "trigger", "!=", "'right'", "&&", "e", ".", "originalEvent", ")", "{", "return", ";", "}", "if", "(", "!", "$this", ".", "hasClass", "(", "'context-menu-disabled'", ")", ")", "{", "// theoretically need to fire a show event at <menu>", "// http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus", "// var evt = jQuery.Event(\"show\", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this });", "// e.data.$menu.trigger(evt);", "$currentTrigger", "=", "$this", ";", "if", "(", "e", ".", "data", ".", "build", ")", "{", "var", "built", "=", "e", ".", "data", ".", "build", "(", "$currentTrigger", ",", "e", ")", ";", "// abort if build() returned false", "if", "(", "built", "===", "false", ")", "{", "return", ";", "}", "// dynamically build menu on invocation", "e", ".", "data", "=", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "defaults", ",", "e", ".", "data", ",", "built", "||", "{", "}", ")", ";", "// abort if there are no items to display", "if", "(", "!", "e", ".", "data", ".", "items", "||", "$", ".", "isEmptyObject", "(", "e", ".", "data", ".", "items", ")", ")", "{", "// Note: jQuery captures and ignores errors from event handlers", "if", "(", "window", ".", "console", ")", "{", "(", "console", ".", "error", "||", "console", ".", "log", ")", "(", "\"No items specified to show in contextMenu\"", ")", ";", "}", "throw", "new", "Error", "(", "'No Items sepcified'", ")", ";", "}", "// backreference for custom command type creation", "e", ".", "data", ".", "$trigger", "=", "$currentTrigger", ";", "op", ".", "create", "(", "e", ".", "data", ")", ";", "}", "// show menu", "op", ".", "show", ".", "call", "(", "$this", ",", "e", ".", "data", ",", "e", ".", "pageX", ",", "e", ".", "pageY", ")", ";", "}", "}" ]
contextmenu show dispatcher
[ "contextmenu", "show", "dispatcher" ]
06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d
https://github.com/billroy/bitlash-commander/blob/06480b6d9ac3fd0d81b5fe089d4bcd714bf7745d/public/js/handsontable/jquery.handsontable.full.js#L5286-L5333
41,299
rorymadden/neoprene
lib/schema/string.js
SchemaString
function SchemaString (key, options) { this.enumValues = []; this.regExp = null; SchemaType.call(this, key, options, 'String'); }
javascript
function SchemaString (key, options) { this.enumValues = []; this.regExp = null; SchemaType.call(this, key, options, 'String'); }
[ "function", "SchemaString", "(", "key", ",", "options", ")", "{", "this", ".", "enumValues", "=", "[", "]", ";", "this", ".", "regExp", "=", "null", ";", "SchemaType", ".", "call", "(", "this", ",", "key", ",", "options", ",", "'String'", ")", ";", "}" ]
String SchemaType constructor. @param {String} key @param {Object} options @inherits SchemaType @api private
[ "String", "SchemaType", "constructor", "." ]
11f22f65a006c25b779b2add9058e9b00b053466
https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/schema/string.js#L18-L22