id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
40,900
graphql-factory/graphql-factory
src-old/directives/by.js
defaultResolveUser
function defaultResolveUser(source, args, context, info) { return ( get(args, ['userID']) || get(context, ['userID']) || get(info, ['rootValue', 'userID']) ); }
javascript
function defaultResolveUser(source, args, context, info) { return ( get(args, ['userID']) || get(context, ['userID']) || get(info, ['rootValue', 'userID']) ); }
[ "function", "defaultResolveUser", "(", "source", ",", "args", ",", "context", ",", "info", ")", "{", "return", "(", "get", "(", "args", ",", "[", "'userID'", "]", ")", "||", "get", "(", "context", ",", "[", "'userID'", "]", ")", "||", "get", "(", "info", ",", "[", "'rootValue'", ",", "'userID'", "]", ")", ")", ";", "}" ]
Default user id resolver, checks args, then context, then rootValue for a userID value @param {*} source @param {*} args @param {*} context @param {*} info
[ "Default", "user", "id", "resolver", "checks", "args", "then", "context", "then", "rootValue", "for", "a", "userID", "value" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/directives/by.js#L16-L22
40,901
graphql-factory/graphql-factory
archive/src/generate/backing.js
resolverMiddleware
function resolverMiddleware (resolver) { return function (req, res, next) { try { const { source, args, context, info } = req const nonCircularReq = _.omit(req, [ 'context' ]) const ctx = _.assign({}, context, { req: nonCircularReq, res, next }) const value = resolver(source, args, ctx, info) // return a resolved promise return Promise.resolve(value) .then(result => { req.result = result return next() }) .catch(next) } catch (err) { return next(err) } } }
javascript
function resolverMiddleware (resolver) { return function (req, res, next) { try { const { source, args, context, info } = req const nonCircularReq = _.omit(req, [ 'context' ]) const ctx = _.assign({}, context, { req: nonCircularReq, res, next }) const value = resolver(source, args, ctx, info) // return a resolved promise return Promise.resolve(value) .then(result => { req.result = result return next() }) .catch(next) } catch (err) { return next(err) } } }
[ "function", "resolverMiddleware", "(", "resolver", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "try", "{", "const", "{", "source", ",", "args", ",", "context", ",", "info", "}", "=", "req", "const", "nonCircularReq", "=", "_", ".", "omit", "(", "req", ",", "[", "'context'", "]", ")", "const", "ctx", "=", "_", ".", "assign", "(", "{", "}", ",", "context", ",", "{", "req", ":", "nonCircularReq", ",", "res", ",", "next", "}", ")", "const", "value", "=", "resolver", "(", "source", ",", "args", ",", "ctx", ",", "info", ")", "// return a resolved promise", "return", "Promise", ".", "resolve", "(", "value", ")", ".", "then", "(", "result", "=>", "{", "req", ".", "result", "=", "result", "return", "next", "(", ")", "}", ")", ".", "catch", "(", "next", ")", "}", "catch", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "}", "}" ]
Creates a middleware function from the field resolve @param resolver @returns {Function}
[ "Creates", "a", "middleware", "function", "from", "the", "field", "resolve" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src/generate/backing.js#L36-L55
40,902
graphql-factory/graphql-factory
archive/src/generate/backing.js
addTypeFunction
function addTypeFunction (typeName, funcName, func) { if (!stringValue(typeName)) { throw new Error('Invalid "typeName" argument, must be String') } else if (!_.isFunction(func) && !stringValue(func)) { throw new Error('Invalid func argument, must be function') } _.set(this.backing, [ typeName, `_${funcName}` ], func) return this }
javascript
function addTypeFunction (typeName, funcName, func) { if (!stringValue(typeName)) { throw new Error('Invalid "typeName" argument, must be String') } else if (!_.isFunction(func) && !stringValue(func)) { throw new Error('Invalid func argument, must be function') } _.set(this.backing, [ typeName, `_${funcName}` ], func) return this }
[ "function", "addTypeFunction", "(", "typeName", ",", "funcName", ",", "func", ")", "{", "if", "(", "!", "stringValue", "(", "typeName", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid \"typeName\" argument, must be String'", ")", "}", "else", "if", "(", "!", "_", ".", "isFunction", "(", "func", ")", "&&", "!", "stringValue", "(", "func", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid func argument, must be function'", ")", "}", "_", ".", "set", "(", "this", ".", "backing", ",", "[", "typeName", ",", "`", "${", "funcName", "}", "`", "]", ",", "func", ")", "return", "this", "}" ]
Adds a type function to the backing @param typeName @param funcName @param func @returns {addTypeFunction}
[ "Adds", "a", "type", "function", "to", "the", "backing" ]
22f98d8e8ada5affcc8eac214b864109dcbb74d7
https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src/generate/backing.js#L64-L72
40,903
sony/cordova-plugin-cdp-nativebridge
dev/platforms/android/cordova/lib/prepare.js
deleteDefaultResourceAt
function deleteDefaultResourceAt(baseDir, resourceName) { shell.ls(path.join(baseDir, 'res/drawable-*')) .forEach(function (drawableFolder) { var imagePath = path.join(drawableFolder, resourceName); shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]); events.emit('verbose', 'Deleted ' + imagePath); }); }
javascript
function deleteDefaultResourceAt(baseDir, resourceName) { shell.ls(path.join(baseDir, 'res/drawable-*')) .forEach(function (drawableFolder) { var imagePath = path.join(drawableFolder, resourceName); shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]); events.emit('verbose', 'Deleted ' + imagePath); }); }
[ "function", "deleteDefaultResourceAt", "(", "baseDir", ",", "resourceName", ")", "{", "shell", ".", "ls", "(", "path", ".", "join", "(", "baseDir", ",", "'res/drawable-*'", ")", ")", ".", "forEach", "(", "function", "(", "drawableFolder", ")", "{", "var", "imagePath", "=", "path", ".", "join", "(", "drawableFolder", ",", "resourceName", ")", ";", "shell", ".", "rm", "(", "'-f'", ",", "[", "imagePath", ",", "imagePath", ".", "replace", "(", "/", "\\.png$", "/", ",", "'.9.png'", ")", "]", ")", ";", "events", ".", "emit", "(", "'verbose'", ",", "'Deleted '", "+", "imagePath", ")", ";", "}", ")", ";", "}" ]
remove the default resource name from all drawable folders
[ "remove", "the", "default", "resource", "name", "from", "all", "drawable", "folders" ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/android/cordova/lib/prepare.js#L310-L317
40,904
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.app.plugins.js
queryTargetScripts
function queryTargetScripts(targetDir) { var scripts = []; fs.readdirSync(targetDir).forEach(function (file) { if (!path.basename(file).toLowerCase().match(/.d.ts/g) && path.basename(file).toLowerCase().match(/\.ts$/i)) { scripts.push(path.basename(file, path.extname(file))); } }); return scripts; }
javascript
function queryTargetScripts(targetDir) { var scripts = []; fs.readdirSync(targetDir).forEach(function (file) { if (!path.basename(file).toLowerCase().match(/.d.ts/g) && path.basename(file).toLowerCase().match(/\.ts$/i)) { scripts.push(path.basename(file, path.extname(file))); } }); return scripts; }
[ "function", "queryTargetScripts", "(", "targetDir", ")", "{", "var", "scripts", "=", "[", "]", ";", "fs", ".", "readdirSync", "(", "targetDir", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "if", "(", "!", "path", ".", "basename", "(", "file", ")", ".", "toLowerCase", "(", ")", ".", "match", "(", "/", ".d.ts", "/", "g", ")", "&&", "path", ".", "basename", "(", "file", ")", ".", "toLowerCase", "(", ")", ".", "match", "(", "/", "\\.ts$", "/", "i", ")", ")", "{", "scripts", ".", "push", "(", "path", ".", "basename", "(", "file", ",", "path", ".", "extname", "(", "file", ")", ")", ")", ";", "}", "}", ")", ";", "return", "scripts", ";", "}" ]
query build target scripts.
[ "query", "build", "target", "scripts", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.app.plugins.js#L377-L385
40,905
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.app.plugins.js
queryPluginVersion
function queryPluginVersion(pluginDir) { var pluginXml = path.join(pluginDir, 'plugin.xml'); var domPluginXml = jsdom.jsdom(fs.readFileSync(pluginXml).toString()); return $(domPluginXml).find('plugin').attr('version'); }
javascript
function queryPluginVersion(pluginDir) { var pluginXml = path.join(pluginDir, 'plugin.xml'); var domPluginXml = jsdom.jsdom(fs.readFileSync(pluginXml).toString()); return $(domPluginXml).find('plugin').attr('version'); }
[ "function", "queryPluginVersion", "(", "pluginDir", ")", "{", "var", "pluginXml", "=", "path", ".", "join", "(", "pluginDir", ",", "'plugin.xml'", ")", ";", "var", "domPluginXml", "=", "jsdom", ".", "jsdom", "(", "fs", ".", "readFileSync", "(", "pluginXml", ")", ".", "toString", "(", ")", ")", ";", "return", "$", "(", "domPluginXml", ")", ".", "find", "(", "'plugin'", ")", ".", "attr", "(", "'version'", ")", ";", "}" ]
query plugin version.
[ "query", "plugin", "version", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.app.plugins.js#L388-L393
40,906
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.app.plugins.js
setBanner
function setBanner() { if (grunt.config.get('app_plugins_mode_release')) { var moduleName = grunt.config.get('app_plugins_work_script_name') + '.js'; var version = grunt.config.get('app_plugins_work_version'); var src = path.join( grunt.config.get('app_plugins_root_dir'), grunt.config.get('app_plugins_work_id'), grunt.config.get('plugins_www'), grunt.config.get('app_plugins_work_script_name') + '.js' ); var info = { src: src, moduleName: moduleName, version: version, }; grunt.config.set('banner_info', info); grunt.task.run('banner_setup'); } }
javascript
function setBanner() { if (grunt.config.get('app_plugins_mode_release')) { var moduleName = grunt.config.get('app_plugins_work_script_name') + '.js'; var version = grunt.config.get('app_plugins_work_version'); var src = path.join( grunt.config.get('app_plugins_root_dir'), grunt.config.get('app_plugins_work_id'), grunt.config.get('plugins_www'), grunt.config.get('app_plugins_work_script_name') + '.js' ); var info = { src: src, moduleName: moduleName, version: version, }; grunt.config.set('banner_info', info); grunt.task.run('banner_setup'); } }
[ "function", "setBanner", "(", ")", "{", "if", "(", "grunt", ".", "config", ".", "get", "(", "'app_plugins_mode_release'", ")", ")", "{", "var", "moduleName", "=", "grunt", ".", "config", ".", "get", "(", "'app_plugins_work_script_name'", ")", "+", "'.js'", ";", "var", "version", "=", "grunt", ".", "config", ".", "get", "(", "'app_plugins_work_version'", ")", ";", "var", "src", "=", "path", ".", "join", "(", "grunt", ".", "config", ".", "get", "(", "'app_plugins_root_dir'", ")", ",", "grunt", ".", "config", ".", "get", "(", "'app_plugins_work_id'", ")", ",", "grunt", ".", "config", ".", "get", "(", "'plugins_www'", ")", ",", "grunt", ".", "config", ".", "get", "(", "'app_plugins_work_script_name'", ")", "+", "'.js'", ")", ";", "var", "info", "=", "{", "src", ":", "src", ",", "moduleName", ":", "moduleName", ",", "version", ":", "version", ",", "}", ";", "grunt", ".", "config", ".", "set", "(", "'banner_info'", ",", "info", ")", ";", "grunt", ".", "task", ".", "run", "(", "'banner_setup'", ")", ";", "}", "}" ]
set banner if needed.
[ "set", "banner", "if", "needed", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.app.plugins.js#L396-L416
40,907
sony/cordova-plugin-cdp-nativebridge
dev/platforms/ios/cordova/Api.js
Api
function Api(platform, platformRootDir, events) { // 'platform' property is required as per PlatformApi spec this.platform = platform || 'ios'; this.root = platformRootDir || path.resolve(__dirname, '..'); this.events = events || ConsoleLogger.get(); // NOTE: trick to share one EventEmitter instance across all js code require('cordova-common').events = this.events; var xcodeProjDir; var xcodeCordovaProj; try { xcodeProjDir = fs.readdirSync(this.root).filter( function(e) { return e.match(/\.xcodeproj$/i); })[0]; if (!xcodeProjDir) { throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.'); } var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep)+1, xcodeProjDir.indexOf('.xcodeproj')); xcodeCordovaProj = path.join(this.root, cordovaProjName); } catch(e) { throw new CordovaError('The provided path "'+this.root+'" is not a Cordova iOS project.'); } this.locations = { root: this.root, www: path.join(this.root, 'www'), platformWww: path.join(this.root, 'platform_www'), configXml: path.join(xcodeCordovaProj, 'config.xml'), defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'), pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'), xcodeProjDir: path.join(this.root, xcodeProjDir), xcodeCordovaProj: xcodeCordovaProj, // NOTE: this is required by browserify logic. // As per platformApi spec we return relative to template root paths here cordovaJs: 'bin/CordovaLib/cordova.js', cordovaJsSrc: 'bin/cordova-js-src' }; }
javascript
function Api(platform, platformRootDir, events) { // 'platform' property is required as per PlatformApi spec this.platform = platform || 'ios'; this.root = platformRootDir || path.resolve(__dirname, '..'); this.events = events || ConsoleLogger.get(); // NOTE: trick to share one EventEmitter instance across all js code require('cordova-common').events = this.events; var xcodeProjDir; var xcodeCordovaProj; try { xcodeProjDir = fs.readdirSync(this.root).filter( function(e) { return e.match(/\.xcodeproj$/i); })[0]; if (!xcodeProjDir) { throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.'); } var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep)+1, xcodeProjDir.indexOf('.xcodeproj')); xcodeCordovaProj = path.join(this.root, cordovaProjName); } catch(e) { throw new CordovaError('The provided path "'+this.root+'" is not a Cordova iOS project.'); } this.locations = { root: this.root, www: path.join(this.root, 'www'), platformWww: path.join(this.root, 'platform_www'), configXml: path.join(xcodeCordovaProj, 'config.xml'), defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'), pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'), xcodeProjDir: path.join(this.root, xcodeProjDir), xcodeCordovaProj: xcodeCordovaProj, // NOTE: this is required by browserify logic. // As per platformApi spec we return relative to template root paths here cordovaJs: 'bin/CordovaLib/cordova.js', cordovaJsSrc: 'bin/cordova-js-src' }; }
[ "function", "Api", "(", "platform", ",", "platformRootDir", ",", "events", ")", "{", "// 'platform' property is required as per PlatformApi spec", "this", ".", "platform", "=", "platform", "||", "'ios'", ";", "this", ".", "root", "=", "platformRootDir", "||", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ")", ";", "this", ".", "events", "=", "events", "||", "ConsoleLogger", ".", "get", "(", ")", ";", "// NOTE: trick to share one EventEmitter instance across all js code", "require", "(", "'cordova-common'", ")", ".", "events", "=", "this", ".", "events", ";", "var", "xcodeProjDir", ";", "var", "xcodeCordovaProj", ";", "try", "{", "xcodeProjDir", "=", "fs", ".", "readdirSync", "(", "this", ".", "root", ")", ".", "filter", "(", "function", "(", "e", ")", "{", "return", "e", ".", "match", "(", "/", "\\.xcodeproj$", "/", "i", ")", ";", "}", ")", "[", "0", "]", ";", "if", "(", "!", "xcodeProjDir", ")", "{", "throw", "new", "CordovaError", "(", "'The provided path \"'", "+", "this", ".", "root", "+", "'\" is not a Cordova iOS project.'", ")", ";", "}", "var", "cordovaProjName", "=", "xcodeProjDir", ".", "substring", "(", "xcodeProjDir", ".", "lastIndexOf", "(", "path", ".", "sep", ")", "+", "1", ",", "xcodeProjDir", ".", "indexOf", "(", "'.xcodeproj'", ")", ")", ";", "xcodeCordovaProj", "=", "path", ".", "join", "(", "this", ".", "root", ",", "cordovaProjName", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "CordovaError", "(", "'The provided path \"'", "+", "this", ".", "root", "+", "'\" is not a Cordova iOS project.'", ")", ";", "}", "this", ".", "locations", "=", "{", "root", ":", "this", ".", "root", ",", "www", ":", "path", ".", "join", "(", "this", ".", "root", ",", "'www'", ")", ",", "platformWww", ":", "path", ".", "join", "(", "this", ".", "root", ",", "'platform_www'", ")", ",", "configXml", ":", "path", ".", "join", "(", "xcodeCordovaProj", ",", "'config.xml'", ")", ",", "defaultConfigXml", ":", "path", ".", "join", "(", "this", ".", "root", ",", "'cordova/defaults.xml'", ")", ",", "pbxproj", ":", "path", ".", "join", "(", "this", ".", "root", ",", "xcodeProjDir", ",", "'project.pbxproj'", ")", ",", "xcodeProjDir", ":", "path", ".", "join", "(", "this", ".", "root", ",", "xcodeProjDir", ")", ",", "xcodeCordovaProj", ":", "xcodeCordovaProj", ",", "// NOTE: this is required by browserify logic.", "// As per platformApi spec we return relative to template root paths here", "cordovaJs", ":", "'bin/CordovaLib/cordova.js'", ",", "cordovaJsSrc", ":", "'bin/cordova-js-src'", "}", ";", "}" ]
Creates a new PlatformApi instance. @param {String} [platform] Platform name, used for backward compatibility w/ PlatformPoly (CordovaLib). @param {String} [platformRootDir] Platform root location, used for backward compatibility w/ PlatformPoly (CordovaLib). @param {EventEmitter} [events] An EventEmitter instance that will be used for logging purposes. If no EventEmitter provided, all events will be logged to console
[ "Creates", "a", "new", "PlatformApi", "instance", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/ios/cordova/Api.js#L39-L77
40,908
sony/cordova-plugin-cdp-nativebridge
dev/platforms/ios/cordova/lib/prepare.js
parseTargetDevicePreference
function parseTargetDevicePreference(value) { if (!value) return null; var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"'}; if (map[value.toLowerCase()]) { return map[value.toLowerCase()]; } events.emit('warn', 'Unknown target-device preference value: "' + value + '".'); return null; }
javascript
function parseTargetDevicePreference(value) { if (!value) return null; var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"'}; if (map[value.toLowerCase()]) { return map[value.toLowerCase()]; } events.emit('warn', 'Unknown target-device preference value: "' + value + '".'); return null; }
[ "function", "parseTargetDevicePreference", "(", "value", ")", "{", "if", "(", "!", "value", ")", "return", "null", ";", "var", "map", "=", "{", "'universal'", ":", "'\"1,2\"'", ",", "'handset'", ":", "'\"1\"'", ",", "'tablet'", ":", "'\"2\"'", "}", ";", "if", "(", "map", "[", "value", ".", "toLowerCase", "(", ")", "]", ")", "{", "return", "map", "[", "value", ".", "toLowerCase", "(", ")", "]", ";", "}", "events", ".", "emit", "(", "'warn'", ",", "'Unknown target-device preference value: \"'", "+", "value", "+", "'\".'", ")", ";", "return", "null", ";", "}" ]
Converts cordova specific representation of target device to XCode value
[ "Converts", "cordova", "specific", "representation", "of", "target", "device", "to", "XCode", "value" ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/ios/cordova/lib/prepare.js#L535-L543
40,909
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.lazyload.js
getDocDom
function getDocDom() { return jsdom.jsdom(fs.readFileSync(path.join(grunt.config.get('tmpdir'), 'index.html')).toString()); }
javascript
function getDocDom() { return jsdom.jsdom(fs.readFileSync(path.join(grunt.config.get('tmpdir'), 'index.html')).toString()); }
[ "function", "getDocDom", "(", ")", "{", "return", "jsdom", ".", "jsdom", "(", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "grunt", ".", "config", ".", "get", "(", "'tmpdir'", ")", ",", "'index.html'", ")", ")", ".", "toString", "(", ")", ")", ";", "}" ]
! get doc dom from index.html.
[ "!", "get", "doc", "dom", "from", "index", ".", "html", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L99-L101
40,910
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.lazyload.js
getExtension
function getExtension(file) { var ret; if (file) { var fileTypes = file.split('.'); var len = fileTypes.length; if (0 === len) { return ret; } ret = fileTypes[len - 1]; return ret; } }
javascript
function getExtension(file) { var ret; if (file) { var fileTypes = file.split('.'); var len = fileTypes.length; if (0 === len) { return ret; } ret = fileTypes[len - 1]; return ret; } }
[ "function", "getExtension", "(", "file", ")", "{", "var", "ret", ";", "if", "(", "file", ")", "{", "var", "fileTypes", "=", "file", ".", "split", "(", "'.'", ")", ";", "var", "len", "=", "fileTypes", ".", "length", ";", "if", "(", "0", "===", "len", ")", "{", "return", "ret", ";", "}", "ret", "=", "fileTypes", "[", "len", "-", "1", "]", ";", "return", "ret", ";", "}", "}" ]
! get file extension.
[ "!", "get", "file", "extension", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L104-L115
40,911
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.lazyload.js
getScriptElements
function getScriptElements($typeLazy) { var scripts; var src = $typeLazy.attr("src"); if ("js" === getExtension(src).toLowerCase()) { return $typeLazy; } else { src = path.join(grunt.config.get('tmpdir'), src); if (fs.existsSync(src)) { scripts = jsdom.jsdom(fs.readFileSync(src).toString()); return $(scripts).find("script"); } else { return $(); } } }
javascript
function getScriptElements($typeLazy) { var scripts; var src = $typeLazy.attr("src"); if ("js" === getExtension(src).toLowerCase()) { return $typeLazy; } else { src = path.join(grunt.config.get('tmpdir'), src); if (fs.existsSync(src)) { scripts = jsdom.jsdom(fs.readFileSync(src).toString()); return $(scripts).find("script"); } else { return $(); } } }
[ "function", "getScriptElements", "(", "$typeLazy", ")", "{", "var", "scripts", ";", "var", "src", "=", "$typeLazy", ".", "attr", "(", "\"src\"", ")", ";", "if", "(", "\"js\"", "===", "getExtension", "(", "src", ")", ".", "toLowerCase", "(", ")", ")", "{", "return", "$typeLazy", ";", "}", "else", "{", "src", "=", "path", ".", "join", "(", "grunt", ".", "config", ".", "get", "(", "'tmpdir'", ")", ",", "src", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "src", ")", ")", "{", "scripts", "=", "jsdom", ".", "jsdom", "(", "fs", ".", "readFileSync", "(", "src", ")", ".", "toString", "(", ")", ")", ";", "return", "$", "(", "scripts", ")", ".", "find", "(", "\"script\"", ")", ";", "}", "else", "{", "return", "$", "(", ")", ";", "}", "}", "}" ]
! get script element.
[ "!", "get", "script", "element", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L118-L132
40,912
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.lazyload.js
prepareAppScriptsInfo
function prepareAppScriptsInfo(docDom) { // read index file, and getting target ts files. var appScripts = []; var $appScripts = $(docDom).find('script[type="lazy"]'); var findAppJs = false; $appScripts.each(function () { var $scripts = getScriptElements($(this)); $scripts.each(function () { var src = $(this).attr('src'); if (src.match(/app.js$/i)) { findAppJs = true; } appScripts.push(path.join(grunt.config.get('tmpdir'), src).replace(/\.js$/i, '.ts')); }); }); if (!findAppJs) { grunt.config.set('app_js_suffix', '-all'); } // set app_scripts grunt.config.set('app_scripts', appScripts); }
javascript
function prepareAppScriptsInfo(docDom) { // read index file, and getting target ts files. var appScripts = []; var $appScripts = $(docDom).find('script[type="lazy"]'); var findAppJs = false; $appScripts.each(function () { var $scripts = getScriptElements($(this)); $scripts.each(function () { var src = $(this).attr('src'); if (src.match(/app.js$/i)) { findAppJs = true; } appScripts.push(path.join(grunt.config.get('tmpdir'), src).replace(/\.js$/i, '.ts')); }); }); if (!findAppJs) { grunt.config.set('app_js_suffix', '-all'); } // set app_scripts grunt.config.set('app_scripts', appScripts); }
[ "function", "prepareAppScriptsInfo", "(", "docDom", ")", "{", "// read index file, and getting target ts files.", "var", "appScripts", "=", "[", "]", ";", "var", "$appScripts", "=", "$", "(", "docDom", ")", ".", "find", "(", "'script[type=\"lazy\"]'", ")", ";", "var", "findAppJs", "=", "false", ";", "$appScripts", ".", "each", "(", "function", "(", ")", "{", "var", "$scripts", "=", "getScriptElements", "(", "$", "(", "this", ")", ")", ";", "$scripts", ".", "each", "(", "function", "(", ")", "{", "var", "src", "=", "$", "(", "this", ")", ".", "attr", "(", "'src'", ")", ";", "if", "(", "src", ".", "match", "(", "/", "app.js$", "/", "i", ")", ")", "{", "findAppJs", "=", "true", ";", "}", "appScripts", ".", "push", "(", "path", ".", "join", "(", "grunt", ".", "config", ".", "get", "(", "'tmpdir'", ")", ",", "src", ")", ".", "replace", "(", "/", "\\.js$", "/", "i", ",", "'.ts'", ")", ")", ";", "}", ")", ";", "}", ")", ";", "if", "(", "!", "findAppJs", ")", "{", "grunt", ".", "config", ".", "set", "(", "'app_js_suffix'", ",", "'-all'", ")", ";", "}", "// set app_scripts", "grunt", ".", "config", ".", "set", "(", "'app_scripts'", ",", "appScripts", ")", ";", "}" ]
! extract app scripts and reset app.js script tag.
[ "!", "extract", "app", "scripts", "and", "reset", "app", ".", "js", "script", "tag", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L135-L158
40,913
sony/cordova-plugin-cdp-nativebridge
dev/platforms/ios/cordova/lib/run.js
deployToSim
function deployToSim(appPath, target) { // Select target device for emulator. Default is 'iPhone-6' if (!target) { return require('./list-emulator-images').run() .then(function (emulators) { if (emulators.length > 0) { target = emulators[0]; } emulators.forEach(function (emulator) { if (emulator.indexOf('iPhone') === 0) { target = emulator; } }); events.emit('log','No target specified for emulator. Deploying to ' + target + ' simulator'); return startSim(appPath, target); }); } else { return startSim(appPath, target); } }
javascript
function deployToSim(appPath, target) { // Select target device for emulator. Default is 'iPhone-6' if (!target) { return require('./list-emulator-images').run() .then(function (emulators) { if (emulators.length > 0) { target = emulators[0]; } emulators.forEach(function (emulator) { if (emulator.indexOf('iPhone') === 0) { target = emulator; } }); events.emit('log','No target specified for emulator. Deploying to ' + target + ' simulator'); return startSim(appPath, target); }); } else { return startSim(appPath, target); } }
[ "function", "deployToSim", "(", "appPath", ",", "target", ")", "{", "// Select target device for emulator. Default is 'iPhone-6' ", "if", "(", "!", "target", ")", "{", "return", "require", "(", "'./list-emulator-images'", ")", ".", "run", "(", ")", ".", "then", "(", "function", "(", "emulators", ")", "{", "if", "(", "emulators", ".", "length", ">", "0", ")", "{", "target", "=", "emulators", "[", "0", "]", ";", "}", "emulators", ".", "forEach", "(", "function", "(", "emulator", ")", "{", "if", "(", "emulator", ".", "indexOf", "(", "'iPhone'", ")", "===", "0", ")", "{", "target", "=", "emulator", ";", "}", "}", ")", ";", "events", ".", "emit", "(", "'log'", ",", "'No target specified for emulator. Deploying to '", "+", "target", "+", "' simulator'", ")", ";", "return", "startSim", "(", "appPath", ",", "target", ")", ";", "}", ")", ";", "}", "else", "{", "return", "startSim", "(", "appPath", ",", "target", ")", ";", "}", "}" ]
Deploy specified app package to ios-sim simulator @param {String} appPath Path to application package @param {String} target Target device type @return {Promise} Resolves when deploy succeeds otherwise rejects
[ "Deploy", "specified", "app", "package", "to", "ios", "-", "sim", "simulator" ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/ios/cordova/lib/run.js#L147-L166
40,914
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.library.module.js
prepareCssModulesInfo
function prepareCssModulesInfo(docDom) { var cssModule = { name: '' }, cssModulesInfo = []; $(docDom).find('link[rel="stylesheet"]') .filter(function () { if (grunt.config.get('lib_kind_fileter_enable')) { var type = path.join(grunt.config.get('lib_kind'), grunt.config.get('stylesheets')); var regexp = new RegExp('^' + type + '\/', 'i'); return $(this).attr('href').match(regexp) ? true : false; } else { return true; } }) .each(function () { var href = $(this).attr('href'); var name = href.slice(href.lastIndexOf('/') + 1, href.length).replace(/\.css$/i, ''); cssModule = { name: name, version: $(this).attr('data-version'), }; cssModulesInfo.push(cssModule); }); // set lib_css_modules_info grunt.config.set('lib_css_modules_info', cssModulesInfo); }
javascript
function prepareCssModulesInfo(docDom) { var cssModule = { name: '' }, cssModulesInfo = []; $(docDom).find('link[rel="stylesheet"]') .filter(function () { if (grunt.config.get('lib_kind_fileter_enable')) { var type = path.join(grunt.config.get('lib_kind'), grunt.config.get('stylesheets')); var regexp = new RegExp('^' + type + '\/', 'i'); return $(this).attr('href').match(regexp) ? true : false; } else { return true; } }) .each(function () { var href = $(this).attr('href'); var name = href.slice(href.lastIndexOf('/') + 1, href.length).replace(/\.css$/i, ''); cssModule = { name: name, version: $(this).attr('data-version'), }; cssModulesInfo.push(cssModule); }); // set lib_css_modules_info grunt.config.set('lib_css_modules_info', cssModulesInfo); }
[ "function", "prepareCssModulesInfo", "(", "docDom", ")", "{", "var", "cssModule", "=", "{", "name", ":", "''", "}", ",", "cssModulesInfo", "=", "[", "]", ";", "$", "(", "docDom", ")", ".", "find", "(", "'link[rel=\"stylesheet\"]'", ")", ".", "filter", "(", "function", "(", ")", "{", "if", "(", "grunt", ".", "config", ".", "get", "(", "'lib_kind_fileter_enable'", ")", ")", "{", "var", "type", "=", "path", ".", "join", "(", "grunt", ".", "config", ".", "get", "(", "'lib_kind'", ")", ",", "grunt", ".", "config", ".", "get", "(", "'stylesheets'", ")", ")", ";", "var", "regexp", "=", "new", "RegExp", "(", "'^'", "+", "type", "+", "'\\/'", ",", "'i'", ")", ";", "return", "$", "(", "this", ")", ".", "attr", "(", "'href'", ")", ".", "match", "(", "regexp", ")", "?", "true", ":", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}", ")", ".", "each", "(", "function", "(", ")", "{", "var", "href", "=", "$", "(", "this", ")", ".", "attr", "(", "'href'", ")", ";", "var", "name", "=", "href", ".", "slice", "(", "href", ".", "lastIndexOf", "(", "'/'", ")", "+", "1", ",", "href", ".", "length", ")", ".", "replace", "(", "/", "\\.css$", "/", "i", ",", "''", ")", ";", "cssModule", "=", "{", "name", ":", "name", ",", "version", ":", "$", "(", "this", ")", ".", "attr", "(", "'data-version'", ")", ",", "}", ";", "cssModulesInfo", ".", "push", "(", "cssModule", ")", ";", "}", ")", ";", "// set lib_css_modules_info", "grunt", ".", "config", ".", "set", "(", "'lib_css_modules_info'", ",", "cssModulesInfo", ")", ";", "}" ]
Helper API ! extract css libraries info.
[ "Helper", "API", "!", "extract", "css", "libraries", "info", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.library.module.js#L292-L316
40,915
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.lower.js
lowerScriptsInfo
function lowerScriptsInfo(docDom) { // read index file, and getting target ts files. var $scripts = $(docDom).find('script[src]'); $scripts.each(function () { $(this).attr('src', function (idx, path) { return path.toLowerCase(); }); }); }
javascript
function lowerScriptsInfo(docDom) { // read index file, and getting target ts files. var $scripts = $(docDom).find('script[src]'); $scripts.each(function () { $(this).attr('src', function (idx, path) { return path.toLowerCase(); }); }); }
[ "function", "lowerScriptsInfo", "(", "docDom", ")", "{", "// read index file, and getting target ts files.", "var", "$scripts", "=", "$", "(", "docDom", ")", ".", "find", "(", "'script[src]'", ")", ";", "$scripts", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "attr", "(", "'src'", ",", "function", "(", "idx", ",", "path", ")", "{", "return", "path", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
lower src of scripts .
[ "lower", "src", "of", "scripts", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lower.js#L96-L104
40,916
sony/cordova-plugin-cdp-nativebridge
dev/build/tasks/build.lower.js
lowerCSSInfo
function lowerCSSInfo(docDom) { // read index file, and getting target ts files. var $scripts = $(docDom).find('link[rel="stylesheet"][href]'); $scripts.each(function () { $(this).attr('href', function (idx, path) { return path.toLowerCase(); }); }); }
javascript
function lowerCSSInfo(docDom) { // read index file, and getting target ts files. var $scripts = $(docDom).find('link[rel="stylesheet"][href]'); $scripts.each(function () { $(this).attr('href', function (idx, path) { return path.toLowerCase(); }); }); }
[ "function", "lowerCSSInfo", "(", "docDom", ")", "{", "// read index file, and getting target ts files.", "var", "$scripts", "=", "$", "(", "docDom", ")", ".", "find", "(", "'link[rel=\"stylesheet\"][href]'", ")", ";", "$scripts", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "attr", "(", "'href'", ",", "function", "(", "idx", ",", "path", ")", "{", "return", "path", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
lower href of CSS .
[ "lower", "href", "of", "CSS", "." ]
6c4f0c3bb875a81395c9ce727f8f6e335a465705
https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lower.js#L107-L115
40,917
vega/vega-loader
src/loader.js
sanitize
function sanitize(uri, options) { options = extend({}, this.options, options); return new Promise(function(accept, reject) { var result = {href: null}, isFile, hasProtocol, loadFile, base; if (uri == null || typeof uri !== 'string') { reject('Sanitize failure, invalid URI: ' + stringValue(uri)); return; } hasProtocol = protocol_re.test(uri); // if relative url (no protocol/host), prepend baseURL if ((base = options.baseURL) && !hasProtocol) { // Ensure that there is a slash between the baseURL (e.g. hostname) and url if (!startsWith(uri, '/') && base[base.length-1] !== '/') { uri = '/' + uri; } uri = base + uri; } // should we load from file system? loadFile = (isFile = startsWith(uri, fileProtocol)) || options.mode === 'file' || options.mode !== 'http' && !hasProtocol && fs(); if (isFile) { // strip file protocol uri = uri.slice(fileProtocol.length); } else if (startsWith(uri, '//')) { if (options.defaultProtocol === 'file') { // if is file, strip protocol and set loadFile flag uri = uri.slice(2); loadFile = true; } else { // if relative protocol (starts with '//'), prepend default protocol uri = (options.defaultProtocol || 'http') + ':' + uri; } } // set non-enumerable mode flag to indicate local file load Object.defineProperty(result, 'localFile', {value: !!loadFile}); // set uri result.href = uri; // set default result target, if specified if (options.target) { result.target = options.target + ''; } // return accept(result); }); }
javascript
function sanitize(uri, options) { options = extend({}, this.options, options); return new Promise(function(accept, reject) { var result = {href: null}, isFile, hasProtocol, loadFile, base; if (uri == null || typeof uri !== 'string') { reject('Sanitize failure, invalid URI: ' + stringValue(uri)); return; } hasProtocol = protocol_re.test(uri); // if relative url (no protocol/host), prepend baseURL if ((base = options.baseURL) && !hasProtocol) { // Ensure that there is a slash between the baseURL (e.g. hostname) and url if (!startsWith(uri, '/') && base[base.length-1] !== '/') { uri = '/' + uri; } uri = base + uri; } // should we load from file system? loadFile = (isFile = startsWith(uri, fileProtocol)) || options.mode === 'file' || options.mode !== 'http' && !hasProtocol && fs(); if (isFile) { // strip file protocol uri = uri.slice(fileProtocol.length); } else if (startsWith(uri, '//')) { if (options.defaultProtocol === 'file') { // if is file, strip protocol and set loadFile flag uri = uri.slice(2); loadFile = true; } else { // if relative protocol (starts with '//'), prepend default protocol uri = (options.defaultProtocol || 'http') + ':' + uri; } } // set non-enumerable mode flag to indicate local file load Object.defineProperty(result, 'localFile', {value: !!loadFile}); // set uri result.href = uri; // set default result target, if specified if (options.target) { result.target = options.target + ''; } // return accept(result); }); }
[ "function", "sanitize", "(", "uri", ",", "options", ")", "{", "options", "=", "extend", "(", "{", "}", ",", "this", ".", "options", ",", "options", ")", ";", "return", "new", "Promise", "(", "function", "(", "accept", ",", "reject", ")", "{", "var", "result", "=", "{", "href", ":", "null", "}", ",", "isFile", ",", "hasProtocol", ",", "loadFile", ",", "base", ";", "if", "(", "uri", "==", "null", "||", "typeof", "uri", "!==", "'string'", ")", "{", "reject", "(", "'Sanitize failure, invalid URI: '", "+", "stringValue", "(", "uri", ")", ")", ";", "return", ";", "}", "hasProtocol", "=", "protocol_re", ".", "test", "(", "uri", ")", ";", "// if relative url (no protocol/host), prepend baseURL", "if", "(", "(", "base", "=", "options", ".", "baseURL", ")", "&&", "!", "hasProtocol", ")", "{", "// Ensure that there is a slash between the baseURL (e.g. hostname) and url", "if", "(", "!", "startsWith", "(", "uri", ",", "'/'", ")", "&&", "base", "[", "base", ".", "length", "-", "1", "]", "!==", "'/'", ")", "{", "uri", "=", "'/'", "+", "uri", ";", "}", "uri", "=", "base", "+", "uri", ";", "}", "// should we load from file system?", "loadFile", "=", "(", "isFile", "=", "startsWith", "(", "uri", ",", "fileProtocol", ")", ")", "||", "options", ".", "mode", "===", "'file'", "||", "options", ".", "mode", "!==", "'http'", "&&", "!", "hasProtocol", "&&", "fs", "(", ")", ";", "if", "(", "isFile", ")", "{", "// strip file protocol", "uri", "=", "uri", ".", "slice", "(", "fileProtocol", ".", "length", ")", ";", "}", "else", "if", "(", "startsWith", "(", "uri", ",", "'//'", ")", ")", "{", "if", "(", "options", ".", "defaultProtocol", "===", "'file'", ")", "{", "// if is file, strip protocol and set loadFile flag", "uri", "=", "uri", ".", "slice", "(", "2", ")", ";", "loadFile", "=", "true", ";", "}", "else", "{", "// if relative protocol (starts with '//'), prepend default protocol", "uri", "=", "(", "options", ".", "defaultProtocol", "||", "'http'", ")", "+", "':'", "+", "uri", ";", "}", "}", "// set non-enumerable mode flag to indicate local file load", "Object", ".", "defineProperty", "(", "result", ",", "'localFile'", ",", "{", "value", ":", "!", "!", "loadFile", "}", ")", ";", "// set uri", "result", ".", "href", "=", "uri", ";", "// set default result target, if specified", "if", "(", "options", ".", "target", ")", "{", "result", ".", "target", "=", "options", ".", "target", "+", "''", ";", "}", "// return", "accept", "(", "result", ")", ";", "}", ")", ";", "}" ]
URI sanitizer function. @param {string} uri - The uri (url or filename) to sanity check. @param {object} options - An options hash. @return {Promise} - A promise that resolves to an object containing sanitized uri data, or rejects it the input uri is deemed invalid. The properties of the resolved object are assumed to be valid attributes for an HTML 'a' tag. The sanitized uri *must* be provided by the 'href' property of the returned object.
[ "URI", "sanitizer", "function", "." ]
1f537ef53e3b7d6ccced0f4326ec302adc6a1832
https://github.com/vega/vega-loader/blob/1f537ef53e3b7d6ccced0f4326ec302adc6a1832/src/loader.js#L57-L113
40,918
vega/vega-loader
src/loader.js
http
function http(url, options) { return request(url, extend({}, this.options.http, options)) .then(function(response) { if (!response.ok) throw response.status + '' + response.statusText; return response.text(); }); }
javascript
function http(url, options) { return request(url, extend({}, this.options.http, options)) .then(function(response) { if (!response.ok) throw response.status + '' + response.statusText; return response.text(); }); }
[ "function", "http", "(", "url", ",", "options", ")", "{", "return", "request", "(", "url", ",", "extend", "(", "{", "}", ",", "this", ".", "options", ".", "http", ",", "options", ")", ")", ".", "then", "(", "function", "(", "response", ")", "{", "if", "(", "!", "response", ".", "ok", ")", "throw", "response", ".", "status", "+", "''", "+", "response", ".", "statusText", ";", "return", "response", ".", "text", "(", ")", ";", "}", ")", ";", "}" ]
HTTP request loader. @param {string} url - The url to request. @param {object} options - An options hash. @return {Promise} - A promise that resolves to the file contents.
[ "HTTP", "request", "loader", "." ]
1f537ef53e3b7d6ccced0f4326ec302adc6a1832
https://github.com/vega/vega-loader/blob/1f537ef53e3b7d6ccced0f4326ec302adc6a1832/src/loader.js#L121-L127
40,919
creationix/brozula
cli.js
compile
function compile(path, callback) { if (/\.luax/.test(path)) { // Load already compiled bytecode loadBytecode(path); } if (/\.lua$/.test(path)) { luaToBytecode(path, function (err, newpath) { if (err) return callback(err); loadBytecode(newpath); }); } function loadBytecode(path) { readFile(path, function (err, buffer) { if (err) return callback(err); generate(buffer); }); } function generate(buffer) { var program; try { program = parse(buffer); } catch (err) { return callback(err); } callback(null, program); } }
javascript
function compile(path, callback) { if (/\.luax/.test(path)) { // Load already compiled bytecode loadBytecode(path); } if (/\.lua$/.test(path)) { luaToBytecode(path, function (err, newpath) { if (err) return callback(err); loadBytecode(newpath); }); } function loadBytecode(path) { readFile(path, function (err, buffer) { if (err) return callback(err); generate(buffer); }); } function generate(buffer) { var program; try { program = parse(buffer); } catch (err) { return callback(err); } callback(null, program); } }
[ "function", "compile", "(", "path", ",", "callback", ")", "{", "if", "(", "/", "\\.luax", "/", ".", "test", "(", "path", ")", ")", "{", "// Load already compiled bytecode", "loadBytecode", "(", "path", ")", ";", "}", "if", "(", "/", "\\.lua$", "/", ".", "test", "(", "path", ")", ")", "{", "luaToBytecode", "(", "path", ",", "function", "(", "err", ",", "newpath", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "loadBytecode", "(", "newpath", ")", ";", "}", ")", ";", "}", "function", "loadBytecode", "(", "path", ")", "{", "readFile", "(", "path", ",", "function", "(", "err", ",", "buffer", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "generate", "(", "buffer", ")", ";", "}", ")", ";", "}", "function", "generate", "(", "buffer", ")", "{", "var", "program", ";", "try", "{", "program", "=", "parse", "(", "buffer", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "program", ")", ";", "}", "}" ]
Compile a lua script to javascript source string
[ "Compile", "a", "lua", "script", "to", "javascript", "source", "string" ]
d3a0b315d23e17fd6d1c71c3e87ce3601949a8fc
https://github.com/creationix/brozula/blob/d3a0b315d23e17fd6d1c71c3e87ce3601949a8fc/cli.js#L48-L75
40,920
IonicaBizau/electronify
lib/index.js
Electronify
function Electronify(path, options) { if (!_isReady) { app.on("ready", () => Electronify(path, options)); return app; } // Defaults var bwOpts = ul.merge(options, { width: 800 , height: 600 , _path: path }); _opts = bwOpts; createWindow(_opts); return app; }
javascript
function Electronify(path, options) { if (!_isReady) { app.on("ready", () => Electronify(path, options)); return app; } // Defaults var bwOpts = ul.merge(options, { width: 800 , height: 600 , _path: path }); _opts = bwOpts; createWindow(_opts); return app; }
[ "function", "Electronify", "(", "path", ",", "options", ")", "{", "if", "(", "!", "_isReady", ")", "{", "app", ".", "on", "(", "\"ready\"", ",", "(", ")", "=>", "Electronify", "(", "path", ",", "options", ")", ")", ";", "return", "app", ";", "}", "// Defaults", "var", "bwOpts", "=", "ul", ".", "merge", "(", "options", ",", "{", "width", ":", "800", ",", "height", ":", "600", ",", "_path", ":", "path", "}", ")", ";", "_opts", "=", "bwOpts", ";", "createWindow", "(", "_opts", ")", ";", "return", "app", ";", "}" ]
Electronify Creates a new browser window based on Electron. @name Electronify @function @param {String} path The path to the HTML file. @param {Object} options An object representing the browser window options. It has the following defaults: - `width` (Number): The window width (default: `800`). - `height` (Number): The window height (default: `600`). @return {ElectronApp} The Electron app object extended with the following fields: - `mainWindow` (BrowserWindow): The browser window that was created.
[ "Electronify", "Creates", "a", "new", "browser", "window", "based", "on", "Electron", "." ]
38678753073e24a59532e2f7a6276a702ad8496e
https://github.com/IonicaBizau/electronify/blob/38678753073e24a59532e2f7a6276a702ad8496e/lib/index.js#L49-L66
40,921
IjzerenHein/famous-map
examples/homer/example.js
_createFPS
function _createFPS(context) { // Render FPS in right-top var modifier = new Modifier({ align: [1, 0], origin: [1, 0], size: [100, 50] }); var surface = new Surface({ content: 'fps', classes: ['fps'] }); context.add(modifier).add(surface); // Update every 5 ticks Timer.every(function () { surface.setContent(Math.round(Engine.getFPS()) + ' fps'); }, 2); }
javascript
function _createFPS(context) { // Render FPS in right-top var modifier = new Modifier({ align: [1, 0], origin: [1, 0], size: [100, 50] }); var surface = new Surface({ content: 'fps', classes: ['fps'] }); context.add(modifier).add(surface); // Update every 5 ticks Timer.every(function () { surface.setContent(Math.round(Engine.getFPS()) + ' fps'); }, 2); }
[ "function", "_createFPS", "(", "context", ")", "{", "// Render FPS in right-top", "var", "modifier", "=", "new", "Modifier", "(", "{", "align", ":", "[", "1", ",", "0", "]", ",", "origin", ":", "[", "1", ",", "0", "]", ",", "size", ":", "[", "100", ",", "50", "]", "}", ")", ";", "var", "surface", "=", "new", "Surface", "(", "{", "content", ":", "'fps'", ",", "classes", ":", "[", "'fps'", "]", "}", ")", ";", "context", ".", "add", "(", "modifier", ")", ".", "add", "(", "surface", ")", ";", "// Update every 5 ticks", "Timer", ".", "every", "(", "function", "(", ")", "{", "surface", ".", "setContent", "(", "Math", ".", "round", "(", "Engine", ".", "getFPS", "(", ")", ")", "+", "' fps'", ")", ";", "}", ",", "2", ")", ";", "}" ]
Creates the FPS-indicator in the right-top corner. @method _createFPS @private
[ "Creates", "the", "FPS", "-", "indicator", "in", "the", "right", "-", "top", "corner", "." ]
aa9b173dc0693503be4cab52c6c88ff3ac6315dd
https://github.com/IjzerenHein/famous-map/blob/aa9b173dc0693503be4cab52c6c88ff3ac6315dd/examples/homer/example.js#L131-L149
40,922
koajs/is-json
index.js
isJSON
function isJSON(body) { if (!body) return false; if ('string' == typeof body) return false; if ('function' == typeof body.pipe) return false; if (Buffer.isBuffer(body)) return false; return true; }
javascript
function isJSON(body) { if (!body) return false; if ('string' == typeof body) return false; if ('function' == typeof body.pipe) return false; if (Buffer.isBuffer(body)) return false; return true; }
[ "function", "isJSON", "(", "body", ")", "{", "if", "(", "!", "body", ")", "return", "false", ";", "if", "(", "'string'", "==", "typeof", "body", ")", "return", "false", ";", "if", "(", "'function'", "==", "typeof", "body", ".", "pipe", ")", "return", "false", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "body", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
Check if `body` should be interpreted as json.
[ "Check", "if", "body", "should", "be", "interpreted", "as", "json", "." ]
e8e2633d37ecf7250ef1bd04b88e084d543d2a53
https://github.com/koajs/is-json/blob/e8e2633d37ecf7250ef1bd04b88e084d543d2a53/index.js#L8-L14
40,923
IjzerenHein/famous-map
examples/photos/main.js
_createPhotoMarker
function _createPhotoMarker(photo) { var randomAngle = (Math.PI / 180) * (10 - (Math.random() * 20)); var marker = { mapModifier: new MapModifier({ mapView: mapView, position: photo.loc }), modifier: new StateModifier({ align: [0, 0], origin: [0.5, 0.5] }), content: { modifier: new Modifier({ size: [36, 26], transform: Transform.rotateZ(randomAngle) }), back: new Surface({ classes: ['photo-frame'] }), photoModifier: new Modifier({ origin: [0.5, 0.5], align: [0.5, 0.5], transform: Transform.scale(0.86, 0.78, 1) }), photo: new ImageSurface({ classes: ['photo'] }) } }; marker.renderable = new RenderNode(marker.mapModifier); var renderable = marker.renderable.add(marker.modifier).add(marker.content.modifier); renderable.add(marker.content.back); renderable.add(marker.content.photoModifier).add(marker.content.photo); return marker; }
javascript
function _createPhotoMarker(photo) { var randomAngle = (Math.PI / 180) * (10 - (Math.random() * 20)); var marker = { mapModifier: new MapModifier({ mapView: mapView, position: photo.loc }), modifier: new StateModifier({ align: [0, 0], origin: [0.5, 0.5] }), content: { modifier: new Modifier({ size: [36, 26], transform: Transform.rotateZ(randomAngle) }), back: new Surface({ classes: ['photo-frame'] }), photoModifier: new Modifier({ origin: [0.5, 0.5], align: [0.5, 0.5], transform: Transform.scale(0.86, 0.78, 1) }), photo: new ImageSurface({ classes: ['photo'] }) } }; marker.renderable = new RenderNode(marker.mapModifier); var renderable = marker.renderable.add(marker.modifier).add(marker.content.modifier); renderable.add(marker.content.back); renderable.add(marker.content.photoModifier).add(marker.content.photo); return marker; }
[ "function", "_createPhotoMarker", "(", "photo", ")", "{", "var", "randomAngle", "=", "(", "Math", ".", "PI", "/", "180", ")", "*", "(", "10", "-", "(", "Math", ".", "random", "(", ")", "*", "20", ")", ")", ";", "var", "marker", "=", "{", "mapModifier", ":", "new", "MapModifier", "(", "{", "mapView", ":", "mapView", ",", "position", ":", "photo", ".", "loc", "}", ")", ",", "modifier", ":", "new", "StateModifier", "(", "{", "align", ":", "[", "0", ",", "0", "]", ",", "origin", ":", "[", "0.5", ",", "0.5", "]", "}", ")", ",", "content", ":", "{", "modifier", ":", "new", "Modifier", "(", "{", "size", ":", "[", "36", ",", "26", "]", ",", "transform", ":", "Transform", ".", "rotateZ", "(", "randomAngle", ")", "}", ")", ",", "back", ":", "new", "Surface", "(", "{", "classes", ":", "[", "'photo-frame'", "]", "}", ")", ",", "photoModifier", ":", "new", "Modifier", "(", "{", "origin", ":", "[", "0.5", ",", "0.5", "]", ",", "align", ":", "[", "0.5", ",", "0.5", "]", ",", "transform", ":", "Transform", ".", "scale", "(", "0.86", ",", "0.78", ",", "1", ")", "}", ")", ",", "photo", ":", "new", "ImageSurface", "(", "{", "classes", ":", "[", "'photo'", "]", "}", ")", "}", "}", ";", "marker", ".", "renderable", "=", "new", "RenderNode", "(", "marker", ".", "mapModifier", ")", ";", "var", "renderable", "=", "marker", ".", "renderable", ".", "add", "(", "marker", ".", "modifier", ")", ".", "add", "(", "marker", ".", "content", ".", "modifier", ")", ";", "renderable", ".", "add", "(", "marker", ".", "content", ".", "back", ")", ";", "renderable", ".", "add", "(", "marker", ".", "content", ".", "photoModifier", ")", ".", "add", "(", "marker", ".", "content", ".", "photo", ")", ";", "return", "marker", ";", "}" ]
Creates a photo-marker
[ "Creates", "a", "photo", "-", "marker" ]
aa9b173dc0693503be4cab52c6c88ff3ac6315dd
https://github.com/IjzerenHein/famous-map/blob/aa9b173dc0693503be4cab52c6c88ff3ac6315dd/examples/photos/main.js#L147-L181
40,924
IjzerenHein/famous-map
dist/famous-map.js
_elementIsChildOfMapView
function _elementIsChildOfMapView(element) { if (element.className.indexOf('fm-mapview') >= 0) { return true; } return element.parentElement ? _elementIsChildOfMapView(element.parentElement) : false; }
javascript
function _elementIsChildOfMapView(element) { if (element.className.indexOf('fm-mapview') >= 0) { return true; } return element.parentElement ? _elementIsChildOfMapView(element.parentElement) : false; }
[ "function", "_elementIsChildOfMapView", "(", "element", ")", "{", "if", "(", "element", ".", "className", ".", "indexOf", "(", "'fm-mapview'", ")", ">=", "0", ")", "{", "return", "true", ";", "}", "return", "element", ".", "parentElement", "?", "_elementIsChildOfMapView", "(", "element", ".", "parentElement", ")", ":", "false", ";", "}" ]
Helper function that checks whether the given DOM element is a child of a MapView.
[ "Helper", "function", "that", "checks", "whether", "the", "given", "DOM", "element", "is", "a", "child", "of", "a", "MapView", "." ]
aa9b173dc0693503be4cab52c6c88ff3ac6315dd
https://github.com/IjzerenHein/famous-map/blob/aa9b173dc0693503be4cab52c6c88ff3ac6315dd/dist/famous-map.js#L1026-L1031
40,925
LukaszWatroba/v-tabs
src/vTabs/directives/vTab.js
TabDirectiveController
function TabDirectiveController ($scope) { var ctrl = this; ctrl.isActive = function isActive () { return !!$scope.isActive; }; ctrl.activate = function activate () { $scope.tabsCtrl.activate($scope); }; $scope.internalControl = { activate: ctrl.activate, isActive: ctrl.isActive }; }
javascript
function TabDirectiveController ($scope) { var ctrl = this; ctrl.isActive = function isActive () { return !!$scope.isActive; }; ctrl.activate = function activate () { $scope.tabsCtrl.activate($scope); }; $scope.internalControl = { activate: ctrl.activate, isActive: ctrl.isActive }; }
[ "function", "TabDirectiveController", "(", "$scope", ")", "{", "var", "ctrl", "=", "this", ";", "ctrl", ".", "isActive", "=", "function", "isActive", "(", ")", "{", "return", "!", "!", "$scope", ".", "isActive", ";", "}", ";", "ctrl", ".", "activate", "=", "function", "activate", "(", ")", "{", "$scope", ".", "tabsCtrl", ".", "activate", "(", "$scope", ")", ";", "}", ";", "$scope", ".", "internalControl", "=", "{", "activate", ":", "ctrl", ".", "activate", ",", "isActive", ":", "ctrl", ".", "isActive", "}", ";", "}" ]
vTab directive controller
[ "vTab", "directive", "controller" ]
82ce9f8f82ea3af5094b13280f0788a5ce3cd94b
https://github.com/LukaszWatroba/v-tabs/blob/82ce9f8f82ea3af5094b13280f0788a5ce3cd94b/src/vTabs/directives/vTab.js#L129-L144
40,926
Pupix/lol-esports-api
API.js
init
function init() { require('dotenv').load(); app.port = process.env.PORT || 3002; // Default route app.get('/', function (req, res) { res.json({ name: 'League of Legends eSports API', version: "0.9.0", author: "Robert Manolea <[email protected]>", repository: "https://github.com/Pupix/lol-esports-api" }); }); // Dynamic API routes XP.forEach(routes, function (func, route) { app.get(route, requestHandler); }); //Error Handling app.use(function (req, res) { res.status(404).json({error: 404, message: "Not Found"}); }); app.use(function (req, res) { res.status(500).json({error: 500, message: 'Internal Server Error'}); }); // Listening app.listen(app.port, function () { console.log('League of Legends eSports API is listening on port ' + app.port); }); }
javascript
function init() { require('dotenv').load(); app.port = process.env.PORT || 3002; // Default route app.get('/', function (req, res) { res.json({ name: 'League of Legends eSports API', version: "0.9.0", author: "Robert Manolea <[email protected]>", repository: "https://github.com/Pupix/lol-esports-api" }); }); // Dynamic API routes XP.forEach(routes, function (func, route) { app.get(route, requestHandler); }); //Error Handling app.use(function (req, res) { res.status(404).json({error: 404, message: "Not Found"}); }); app.use(function (req, res) { res.status(500).json({error: 500, message: 'Internal Server Error'}); }); // Listening app.listen(app.port, function () { console.log('League of Legends eSports API is listening on port ' + app.port); }); }
[ "function", "init", "(", ")", "{", "require", "(", "'dotenv'", ")", ".", "load", "(", ")", ";", "app", ".", "port", "=", "process", ".", "env", ".", "PORT", "||", "3002", ";", "// Default route", "app", ".", "get", "(", "'/'", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "json", "(", "{", "name", ":", "'League of Legends eSports API'", ",", "version", ":", "\"0.9.0\"", ",", "author", ":", "\"Robert Manolea <[email protected]>\"", ",", "repository", ":", "\"https://github.com/Pupix/lol-esports-api\"", "}", ")", ";", "}", ")", ";", "// Dynamic API routes", "XP", ".", "forEach", "(", "routes", ",", "function", "(", "func", ",", "route", ")", "{", "app", ".", "get", "(", "route", ",", "requestHandler", ")", ";", "}", ")", ";", "//Error Handling", "app", ".", "use", "(", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "404", ")", ".", "json", "(", "{", "error", ":", "404", ",", "message", ":", "\"Not Found\"", "}", ")", ";", "}", ")", ";", "app", ".", "use", "(", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "500", ")", ".", "json", "(", "{", "error", ":", "500", ",", "message", ":", "'Internal Server Error'", "}", ")", ";", "}", ")", ";", "// Listening", "app", ".", "listen", "(", "app", ".", "port", ",", "function", "(", ")", "{", "console", ".", "log", "(", "'League of Legends eSports API is listening on port '", "+", "app", ".", "port", ")", ";", "}", ")", ";", "}" ]
Main function of the API
[ "Main", "function", "of", "the", "API" ]
43aada008d50dfcf1a3b1a27c1c1054348ddd03e
https://github.com/Pupix/lol-esports-api/blob/43aada008d50dfcf1a3b1a27c1c1054348ddd03e/API.js#L137-L164
40,927
LukaszWatroba/v-tabs
src/vTabs/directives/vPages.js
vPagesDirectiveController
function vPagesDirectiveController ($scope) { var ctrl = this; $scope.pages = []; ctrl.getPagesId = function getPagesId () { return $scope.id; }; ctrl.getPageByIndex = function (index) { return $scope.pages[index]; }; ctrl.getPageIndex = function (page) { return $scope.pages.indexOf(page); }; ctrl.getPageIndexById = function getPageIndexById (id) { var length = $scope.pages.length, index = null; for (var i = 0; i < length; i++) { var iteratedPage = $scope.pages[i]; if (iteratedPage.id && iteratedPage.id === id) { index = i; } } return index; }; ctrl.addPage = function (page) { $scope.pages.push(page); if ($scope.activeIndex === ctrl.getPageIndex(page)) { ctrl.activate(page); } }; ctrl.next = function () { var newActiveIndex = $scope.activeIndex + 1; if (newActiveIndex > $scope.pages.length - 1) { newActiveIndex = 0; } $scope.activeIndex = newActiveIndex; }; ctrl.previous = function () { var newActiveIndex = $scope.activeIndex - 1; if (newActiveIndex < 0) { newActiveIndex = $scope.pages.length - 1; } $scope.activeIndex = newActiveIndex; }; ctrl.activate = function (pageToActivate) { if (!pageToActivate) { return; } if (!pageToActivate.isActive) { pageToActivate.isActive = true; angular.forEach($scope.pages, function (iteratedPage) { if (iteratedPage !== pageToActivate && iteratedPage.isActive) { iteratedPage.isActive = false; } }); } }; $scope.$watch('activeIndex', function (newValue, oldValue) { if (newValue === oldValue) { return; } var pageToActivate = ctrl.getPageByIndex(newValue); if (pageToActivate.isDisabled) { $scope.activeIndex = (angular.isDefined(oldValue)) ? oldValue : 0; return false; } ctrl.activate(pageToActivate); }); // API $scope.internalControl = { next: function () { ctrl.next(); }, previous: function () { ctrl.previous(); }, activate: function (indexOrId) { if (angular.isString(indexOrId)) { $scope.activeIndex = ctrl.getPageIndexById(indexOrId); } else { $scope.activeIndex = indexOrId; } } }; }
javascript
function vPagesDirectiveController ($scope) { var ctrl = this; $scope.pages = []; ctrl.getPagesId = function getPagesId () { return $scope.id; }; ctrl.getPageByIndex = function (index) { return $scope.pages[index]; }; ctrl.getPageIndex = function (page) { return $scope.pages.indexOf(page); }; ctrl.getPageIndexById = function getPageIndexById (id) { var length = $scope.pages.length, index = null; for (var i = 0; i < length; i++) { var iteratedPage = $scope.pages[i]; if (iteratedPage.id && iteratedPage.id === id) { index = i; } } return index; }; ctrl.addPage = function (page) { $scope.pages.push(page); if ($scope.activeIndex === ctrl.getPageIndex(page)) { ctrl.activate(page); } }; ctrl.next = function () { var newActiveIndex = $scope.activeIndex + 1; if (newActiveIndex > $scope.pages.length - 1) { newActiveIndex = 0; } $scope.activeIndex = newActiveIndex; }; ctrl.previous = function () { var newActiveIndex = $scope.activeIndex - 1; if (newActiveIndex < 0) { newActiveIndex = $scope.pages.length - 1; } $scope.activeIndex = newActiveIndex; }; ctrl.activate = function (pageToActivate) { if (!pageToActivate) { return; } if (!pageToActivate.isActive) { pageToActivate.isActive = true; angular.forEach($scope.pages, function (iteratedPage) { if (iteratedPage !== pageToActivate && iteratedPage.isActive) { iteratedPage.isActive = false; } }); } }; $scope.$watch('activeIndex', function (newValue, oldValue) { if (newValue === oldValue) { return; } var pageToActivate = ctrl.getPageByIndex(newValue); if (pageToActivate.isDisabled) { $scope.activeIndex = (angular.isDefined(oldValue)) ? oldValue : 0; return false; } ctrl.activate(pageToActivate); }); // API $scope.internalControl = { next: function () { ctrl.next(); }, previous: function () { ctrl.previous(); }, activate: function (indexOrId) { if (angular.isString(indexOrId)) { $scope.activeIndex = ctrl.getPageIndexById(indexOrId); } else { $scope.activeIndex = indexOrId; } } }; }
[ "function", "vPagesDirectiveController", "(", "$scope", ")", "{", "var", "ctrl", "=", "this", ";", "$scope", ".", "pages", "=", "[", "]", ";", "ctrl", ".", "getPagesId", "=", "function", "getPagesId", "(", ")", "{", "return", "$scope", ".", "id", ";", "}", ";", "ctrl", ".", "getPageByIndex", "=", "function", "(", "index", ")", "{", "return", "$scope", ".", "pages", "[", "index", "]", ";", "}", ";", "ctrl", ".", "getPageIndex", "=", "function", "(", "page", ")", "{", "return", "$scope", ".", "pages", ".", "indexOf", "(", "page", ")", ";", "}", ";", "ctrl", ".", "getPageIndexById", "=", "function", "getPageIndexById", "(", "id", ")", "{", "var", "length", "=", "$scope", ".", "pages", ".", "length", ",", "index", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "var", "iteratedPage", "=", "$scope", ".", "pages", "[", "i", "]", ";", "if", "(", "iteratedPage", ".", "id", "&&", "iteratedPage", ".", "id", "===", "id", ")", "{", "index", "=", "i", ";", "}", "}", "return", "index", ";", "}", ";", "ctrl", ".", "addPage", "=", "function", "(", "page", ")", "{", "$scope", ".", "pages", ".", "push", "(", "page", ")", ";", "if", "(", "$scope", ".", "activeIndex", "===", "ctrl", ".", "getPageIndex", "(", "page", ")", ")", "{", "ctrl", ".", "activate", "(", "page", ")", ";", "}", "}", ";", "ctrl", ".", "next", "=", "function", "(", ")", "{", "var", "newActiveIndex", "=", "$scope", ".", "activeIndex", "+", "1", ";", "if", "(", "newActiveIndex", ">", "$scope", ".", "pages", ".", "length", "-", "1", ")", "{", "newActiveIndex", "=", "0", ";", "}", "$scope", ".", "activeIndex", "=", "newActiveIndex", ";", "}", ";", "ctrl", ".", "previous", "=", "function", "(", ")", "{", "var", "newActiveIndex", "=", "$scope", ".", "activeIndex", "-", "1", ";", "if", "(", "newActiveIndex", "<", "0", ")", "{", "newActiveIndex", "=", "$scope", ".", "pages", ".", "length", "-", "1", ";", "}", "$scope", ".", "activeIndex", "=", "newActiveIndex", ";", "}", ";", "ctrl", ".", "activate", "=", "function", "(", "pageToActivate", ")", "{", "if", "(", "!", "pageToActivate", ")", "{", "return", ";", "}", "if", "(", "!", "pageToActivate", ".", "isActive", ")", "{", "pageToActivate", ".", "isActive", "=", "true", ";", "angular", ".", "forEach", "(", "$scope", ".", "pages", ",", "function", "(", "iteratedPage", ")", "{", "if", "(", "iteratedPage", "!==", "pageToActivate", "&&", "iteratedPage", ".", "isActive", ")", "{", "iteratedPage", ".", "isActive", "=", "false", ";", "}", "}", ")", ";", "}", "}", ";", "$scope", ".", "$watch", "(", "'activeIndex'", ",", "function", "(", "newValue", ",", "oldValue", ")", "{", "if", "(", "newValue", "===", "oldValue", ")", "{", "return", ";", "}", "var", "pageToActivate", "=", "ctrl", ".", "getPageByIndex", "(", "newValue", ")", ";", "if", "(", "pageToActivate", ".", "isDisabled", ")", "{", "$scope", ".", "activeIndex", "=", "(", "angular", ".", "isDefined", "(", "oldValue", ")", ")", "?", "oldValue", ":", "0", ";", "return", "false", ";", "}", "ctrl", ".", "activate", "(", "pageToActivate", ")", ";", "}", ")", ";", "// API", "$scope", ".", "internalControl", "=", "{", "next", ":", "function", "(", ")", "{", "ctrl", ".", "next", "(", ")", ";", "}", ",", "previous", ":", "function", "(", ")", "{", "ctrl", ".", "previous", "(", ")", ";", "}", ",", "activate", ":", "function", "(", "indexOrId", ")", "{", "if", "(", "angular", ".", "isString", "(", "indexOrId", ")", ")", "{", "$scope", ".", "activeIndex", "=", "ctrl", ".", "getPageIndexById", "(", "indexOrId", ")", ";", "}", "else", "{", "$scope", ".", "activeIndex", "=", "indexOrId", ";", "}", "}", "}", ";", "}" ]
vPages directive controller
[ "vPages", "directive", "controller" ]
82ce9f8f82ea3af5094b13280f0788a5ce3cd94b
https://github.com/LukaszWatroba/v-tabs/blob/82ce9f8f82ea3af5094b13280f0788a5ce3cd94b/src/vTabs/directives/vPages.js#L59-L156
40,928
ancasicolica/node-wifi-scanner
lib/netsh.js
parseOutput
function parseOutput(str, callback) { var blocks = str.split('\n\n'); var wifis = []; var err = null; try { if (blocks.length < 2) { // 2nd try, with \r\n blocks = str.split('\r\n\r\n') } if (!blocks || blocks.length === 1) { // No WiFis found return callback(null, []); } // Each block has the same structure, while some parts might be available and others // not. A sample structure: // SSID 1 : AP-Test1 // Network type : Infrastructure // Authentication : WPA2-Personal // Encryption : CCMP // BSSID 1 : 00:aa:f2:77:a5:53 // Signal : 46% // Radio type : 802.11n // Channel : 6 // Basic rates (MBit/s) : 1 2 5.5 11 // Other rates (MBit/s) : 6 9 12 18 24 36 48 54 for (var i = 1, l = blocks.length; i < l; i++) { var network = {}; var lines = blocks[i].split('\n'); var regexChannel = /[a-zA-Z0-9()\s]+:[\s]*[0-9]+$/g; if (!lines || lines.length < 2) { continue; } // First line is always the SSID (which can be empty) var ssid = lines[0].substring(lines[0].indexOf(':') + 1).trim(); for (var t = 1, n = lines.length; t < n; t++) { if (lines[t].split(':').length === 7) { // This is the mac address, use this one as trigger for a new network if (network.mac) { wifis.push(network); } network = { ssid: ssid, mac : lines[t].substring(lines[t].indexOf(':') + 1).trim() }; } else if (lines[t].indexOf('%') > 0) { // Network signal strength, identified by '%' var level = parseInt(lines[t].split(':')[1].split('%')[0].trim(), 10); network.rssi = (level / 2) - 100; } else if (!network.channel) { // A tricky one: the channel is the first one having just ONE number. Set only // if the channel is not already set ("Basic Rates" can be a single number also) if (regexChannel.exec(lines[t].trim())) { network.channel = parseInt(lines[t].split(':')[1].trim(), 10); } } } if (network) { wifis.push(network); } } } catch (ex) { err = ex; } callback(err, wifis); }
javascript
function parseOutput(str, callback) { var blocks = str.split('\n\n'); var wifis = []; var err = null; try { if (blocks.length < 2) { // 2nd try, with \r\n blocks = str.split('\r\n\r\n') } if (!blocks || blocks.length === 1) { // No WiFis found return callback(null, []); } // Each block has the same structure, while some parts might be available and others // not. A sample structure: // SSID 1 : AP-Test1 // Network type : Infrastructure // Authentication : WPA2-Personal // Encryption : CCMP // BSSID 1 : 00:aa:f2:77:a5:53 // Signal : 46% // Radio type : 802.11n // Channel : 6 // Basic rates (MBit/s) : 1 2 5.5 11 // Other rates (MBit/s) : 6 9 12 18 24 36 48 54 for (var i = 1, l = blocks.length; i < l; i++) { var network = {}; var lines = blocks[i].split('\n'); var regexChannel = /[a-zA-Z0-9()\s]+:[\s]*[0-9]+$/g; if (!lines || lines.length < 2) { continue; } // First line is always the SSID (which can be empty) var ssid = lines[0].substring(lines[0].indexOf(':') + 1).trim(); for (var t = 1, n = lines.length; t < n; t++) { if (lines[t].split(':').length === 7) { // This is the mac address, use this one as trigger for a new network if (network.mac) { wifis.push(network); } network = { ssid: ssid, mac : lines[t].substring(lines[t].indexOf(':') + 1).trim() }; } else if (lines[t].indexOf('%') > 0) { // Network signal strength, identified by '%' var level = parseInt(lines[t].split(':')[1].split('%')[0].trim(), 10); network.rssi = (level / 2) - 100; } else if (!network.channel) { // A tricky one: the channel is the first one having just ONE number. Set only // if the channel is not already set ("Basic Rates" can be a single number also) if (regexChannel.exec(lines[t].trim())) { network.channel = parseInt(lines[t].split(':')[1].trim(), 10); } } } if (network) { wifis.push(network); } } } catch (ex) { err = ex; } callback(err, wifis); }
[ "function", "parseOutput", "(", "str", ",", "callback", ")", "{", "var", "blocks", "=", "str", ".", "split", "(", "'\\n\\n'", ")", ";", "var", "wifis", "=", "[", "]", ";", "var", "err", "=", "null", ";", "try", "{", "if", "(", "blocks", ".", "length", "<", "2", ")", "{", "// 2nd try, with \\r\\n", "blocks", "=", "str", ".", "split", "(", "'\\r\\n\\r\\n'", ")", "}", "if", "(", "!", "blocks", "||", "blocks", ".", "length", "===", "1", ")", "{", "// No WiFis found", "return", "callback", "(", "null", ",", "[", "]", ")", ";", "}", "// Each block has the same structure, while some parts might be available and others", "// not. A sample structure:", "// SSID 1 : AP-Test1", "// Network type : Infrastructure", "// Authentication : WPA2-Personal", "// Encryption : CCMP", "// BSSID 1 : 00:aa:f2:77:a5:53", "// Signal : 46%", "// Radio type : 802.11n", "// Channel : 6", "// Basic rates (MBit/s) : 1 2 5.5 11", "// Other rates (MBit/s) : 6 9 12 18 24 36 48 54", "for", "(", "var", "i", "=", "1", ",", "l", "=", "blocks", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "network", "=", "{", "}", ";", "var", "lines", "=", "blocks", "[", "i", "]", ".", "split", "(", "'\\n'", ")", ";", "var", "regexChannel", "=", "/", "[a-zA-Z0-9()\\s]+:[\\s]*[0-9]+$", "/", "g", ";", "if", "(", "!", "lines", "||", "lines", ".", "length", "<", "2", ")", "{", "continue", ";", "}", "// First line is always the SSID (which can be empty)", "var", "ssid", "=", "lines", "[", "0", "]", ".", "substring", "(", "lines", "[", "0", "]", ".", "indexOf", "(", "':'", ")", "+", "1", ")", ".", "trim", "(", ")", ";", "for", "(", "var", "t", "=", "1", ",", "n", "=", "lines", ".", "length", ";", "t", "<", "n", ";", "t", "++", ")", "{", "if", "(", "lines", "[", "t", "]", ".", "split", "(", "':'", ")", ".", "length", "===", "7", ")", "{", "// This is the mac address, use this one as trigger for a new network", "if", "(", "network", ".", "mac", ")", "{", "wifis", ".", "push", "(", "network", ")", ";", "}", "network", "=", "{", "ssid", ":", "ssid", ",", "mac", ":", "lines", "[", "t", "]", ".", "substring", "(", "lines", "[", "t", "]", ".", "indexOf", "(", "':'", ")", "+", "1", ")", ".", "trim", "(", ")", "}", ";", "}", "else", "if", "(", "lines", "[", "t", "]", ".", "indexOf", "(", "'%'", ")", ">", "0", ")", "{", "// Network signal strength, identified by '%'", "var", "level", "=", "parseInt", "(", "lines", "[", "t", "]", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "split", "(", "'%'", ")", "[", "0", "]", ".", "trim", "(", ")", ",", "10", ")", ";", "network", ".", "rssi", "=", "(", "level", "/", "2", ")", "-", "100", ";", "}", "else", "if", "(", "!", "network", ".", "channel", ")", "{", "// A tricky one: the channel is the first one having just ONE number. Set only", "// if the channel is not already set (\"Basic Rates\" can be a single number also)", "if", "(", "regexChannel", ".", "exec", "(", "lines", "[", "t", "]", ".", "trim", "(", ")", ")", ")", "{", "network", ".", "channel", "=", "parseInt", "(", "lines", "[", "t", "]", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "trim", "(", ")", ",", "10", ")", ";", "}", "}", "}", "if", "(", "network", ")", "{", "wifis", ".", "push", "(", "network", ")", ";", "}", "}", "}", "catch", "(", "ex", ")", "{", "err", "=", "ex", ";", "}", "callback", "(", "err", ",", "wifis", ")", ";", "}" ]
Parsing netnsh output. Unfortunately netsh supplies the network information in the language of the operating system. Translating the terms into every language supplied is not possible, therefore this implementation follows an approach of analyzing the structure of the output
[ "Parsing", "netnsh", "output", ".", "Unfortunately", "netsh", "supplies", "the", "network", "information", "in", "the", "language", "of", "the", "operating", "system", ".", "Translating", "the", "terms", "into", "every", "language", "supplied", "is", "not", "possible", "therefore", "this", "implementation", "follows", "an", "approach", "of", "analyzing", "the", "structure", "of", "the", "output" ]
bc61dc2f02c07169bfd0b43e9fbc9230ab316c85
https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/lib/netsh.js#L17-L88
40,929
LukaszWatroba/v-tabs
src/vTabs/directives/vPage.js
PageDirectiveController
function PageDirectiveController ($scope) { var ctrl = this; ctrl.isActive = function isActive () { return !!$scope.isActive; }; ctrl.activate = function activate () { $scope.pagesCtrl.activate($scope); }; $scope.internalControl = { activate: ctrl.activate, isActive: ctrl.isActive }; }
javascript
function PageDirectiveController ($scope) { var ctrl = this; ctrl.isActive = function isActive () { return !!$scope.isActive; }; ctrl.activate = function activate () { $scope.pagesCtrl.activate($scope); }; $scope.internalControl = { activate: ctrl.activate, isActive: ctrl.isActive }; }
[ "function", "PageDirectiveController", "(", "$scope", ")", "{", "var", "ctrl", "=", "this", ";", "ctrl", ".", "isActive", "=", "function", "isActive", "(", ")", "{", "return", "!", "!", "$scope", ".", "isActive", ";", "}", ";", "ctrl", ".", "activate", "=", "function", "activate", "(", ")", "{", "$scope", ".", "pagesCtrl", ".", "activate", "(", "$scope", ")", ";", "}", ";", "$scope", ".", "internalControl", "=", "{", "activate", ":", "ctrl", ".", "activate", ",", "isActive", ":", "ctrl", ".", "isActive", "}", ";", "}" ]
vPage directive controller
[ "vPage", "directive", "controller" ]
82ce9f8f82ea3af5094b13280f0788a5ce3cd94b
https://github.com/LukaszWatroba/v-tabs/blob/82ce9f8f82ea3af5094b13280f0788a5ce3cd94b/src/vTabs/directives/vPage.js#L62-L77
40,930
ancasicolica/node-wifi-scanner
index.js
initTools
function initTools(callback) { // When a command is not found, an error is issued and async would finish. Therefore we pack // the error into the result and check it later on. async.parallel([ function (cb) { exec(airport.detector, function (err) { cb(null, {err: err, scanner: airport} ) } ); }, function (cb) { exec(iwlist.detector, function (err) { cb(null, {err: err, scanner: iwlist} ) } ); }, function (cb) { exec(netsh.detector, function (err) { cb(null, {err: err, scanner: netsh} ) } ); } ], function (err, results) { var res = _.find(results, function (f) { return !f.err }); if (res) { return callback(null, res.scanner); } callback(new Error('No scanner found')); } ); }
javascript
function initTools(callback) { // When a command is not found, an error is issued and async would finish. Therefore we pack // the error into the result and check it later on. async.parallel([ function (cb) { exec(airport.detector, function (err) { cb(null, {err: err, scanner: airport} ) } ); }, function (cb) { exec(iwlist.detector, function (err) { cb(null, {err: err, scanner: iwlist} ) } ); }, function (cb) { exec(netsh.detector, function (err) { cb(null, {err: err, scanner: netsh} ) } ); } ], function (err, results) { var res = _.find(results, function (f) { return !f.err }); if (res) { return callback(null, res.scanner); } callback(new Error('No scanner found')); } ); }
[ "function", "initTools", "(", "callback", ")", "{", "// When a command is not found, an error is issued and async would finish. Therefore we pack", "// the error into the result and check it later on.", "async", ".", "parallel", "(", "[", "function", "(", "cb", ")", "{", "exec", "(", "airport", ".", "detector", ",", "function", "(", "err", ")", "{", "cb", "(", "null", ",", "{", "err", ":", "err", ",", "scanner", ":", "airport", "}", ")", "}", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "exec", "(", "iwlist", ".", "detector", ",", "function", "(", "err", ")", "{", "cb", "(", "null", ",", "{", "err", ":", "err", ",", "scanner", ":", "iwlist", "}", ")", "}", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "exec", "(", "netsh", ".", "detector", ",", "function", "(", "err", ")", "{", "cb", "(", "null", ",", "{", "err", ":", "err", ",", "scanner", ":", "netsh", "}", ")", "}", ")", ";", "}", "]", ",", "function", "(", "err", ",", "results", ")", "{", "var", "res", "=", "_", ".", "find", "(", "results", ",", "function", "(", "f", ")", "{", "return", "!", "f", ".", "err", "}", ")", ";", "if", "(", "res", ")", "{", "return", "callback", "(", "null", ",", "res", ".", "scanner", ")", ";", "}", "callback", "(", "new", "Error", "(", "'No scanner found'", ")", ")", ";", "}", ")", ";", "}" ]
Initializing the tools
[ "Initializing", "the", "tools" ]
bc61dc2f02c07169bfd0b43e9fbc9230ab316c85
https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/index.js#L17-L56
40,931
ancasicolica/node-wifi-scanner
index.js
scanNetworks
function scanNetworks(callback) { exec(scanner.cmdLine, function (err, stdout) { if (err) { callback(err, null); return; } scanner.parseOutput(stdout, callback); }); }
javascript
function scanNetworks(callback) { exec(scanner.cmdLine, function (err, stdout) { if (err) { callback(err, null); return; } scanner.parseOutput(stdout, callback); }); }
[ "function", "scanNetworks", "(", "callback", ")", "{", "exec", "(", "scanner", ".", "cmdLine", ",", "function", "(", "err", ",", "stdout", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "return", ";", "}", "scanner", ".", "parseOutput", "(", "stdout", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Scan the networks with the scanner detected before @param callback
[ "Scan", "the", "networks", "with", "the", "scanner", "detected", "before" ]
bc61dc2f02c07169bfd0b43e9fbc9230ab316c85
https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/index.js#L62-L70
40,932
ancasicolica/node-wifi-scanner
index.js
function (callback) { if (!scanner) { initTools(function (err, s) { if (err) { return callback(err); } scanner = s; scanNetworks(callback); }); return; } scanNetworks(callback); }
javascript
function (callback) { if (!scanner) { initTools(function (err, s) { if (err) { return callback(err); } scanner = s; scanNetworks(callback); }); return; } scanNetworks(callback); }
[ "function", "(", "callback", ")", "{", "if", "(", "!", "scanner", ")", "{", "initTools", "(", "function", "(", "err", ",", "s", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "scanner", "=", "s", ";", "scanNetworks", "(", "callback", ")", ";", "}", ")", ";", "return", ";", "}", "scanNetworks", "(", "callback", ")", ";", "}" ]
Scan for wifis @param callback
[ "Scan", "for", "wifis" ]
bc61dc2f02c07169bfd0b43e9fbc9230ab316c85
https://github.com/ancasicolica/node-wifi-scanner/blob/bc61dc2f02c07169bfd0b43e9fbc9230ab316c85/index.js#L77-L89
40,933
steveush/foodoc
src/static/js/table-of-contents.js
TOC
function TOC(enabled){ if (!(this instanceof TOC)) return new TOC(enabled); this.enabled = !!enabled; this._items = {all:[],h1:[],h2:[],h3:[],h4:[]}; this._last = {h1:null,h2:null,h3:null,h4:null}; }
javascript
function TOC(enabled){ if (!(this instanceof TOC)) return new TOC(enabled); this.enabled = !!enabled; this._items = {all:[],h1:[],h2:[],h3:[],h4:[]}; this._last = {h1:null,h2:null,h3:null,h4:null}; }
[ "function", "TOC", "(", "enabled", ")", "{", "if", "(", "!", "(", "this", "instanceof", "TOC", ")", ")", "return", "new", "TOC", "(", "enabled", ")", ";", "this", ".", "enabled", "=", "!", "!", "enabled", ";", "this", ".", "_items", "=", "{", "all", ":", "[", "]", ",", "h1", ":", "[", "]", ",", "h2", ":", "[", "]", ",", "h3", ":", "[", "]", ",", "h4", ":", "[", "]", "}", ";", "this", ".", "_last", "=", "{", "h1", ":", "null", ",", "h2", ":", "null", ",", "h3", ":", "null", ",", "h4", ":", "null", "}", ";", "}" ]
While this is called `TOC` it actually performs a few functions related to anchors and scrolling. 1. It parses the page for all `H1`, `H2`, `H3` and `H4` elements and ensures they have an id, using either the existing one or generating one by slugifying the headers' text. 2. It adds an `A` element with a link icon that appears on hover to all parsed headers that when clicked simply links back to the current symbol allowing a user to easily get a link to specific documentation. 3. It builds the Table of Contents from the parsed headers and provides the underlying logic for that component. 4. It listens to the `hashchange` event and hijacks all anchor element clicks in the page to ensure when navigating the browser correctly offsets itself. When disabled by setting the `showTableOfContents` option, the above steps 1, 2 and 4 are still performed to ensure anchor clicks are handled correctly. @summary Used to parse the page for headers to build the Table of Contents. @constructor TOC @param {boolean} enabled - Whether or not the Table of Contents is enabled for this doclet. @example {@caption The following shows the ready callback that is registered when this script is loaded. The `DOCLET_TOC_ENABLED` variable is set by the template on `window` object.} $(function(){ var toc = new TOC(DOCLET_TOC_ENABLED); toc.parse(); if (toc.enabled && toc.any()) { toc.init(); } else { toc.fixColumns(); } toc.offsetScroll(60); });
[ "While", "this", "is", "called", "TOC", "it", "actually", "performs", "a", "few", "functions", "related", "to", "anchors", "and", "scrolling", "." ]
b7cc2cd1fbbeaeb08e12f74352399a5371d29f7e
https://github.com/steveush/foodoc/blob/b7cc2cd1fbbeaeb08e12f74352399a5371d29f7e/src/static/js/table-of-contents.js#L29-L34
40,934
timshadel/passport-oauth2-public-client
lib/passport-oauth2-public-client/strategy.js
Strategy
function Strategy(options, verifyPublic) { if (typeof options == 'function') { verifyPublic = options; options = {}; } if (!verifyPublic) throw new Error('OAuth 2.0 public client strategy requires a verifyPublic function'); passport.Strategy.call(this); this.name = 'oauth2-public-client'; this._verifyPublic = verifyPublic; this._passReqToCallback = options.passReqToCallback; }
javascript
function Strategy(options, verifyPublic) { if (typeof options == 'function') { verifyPublic = options; options = {}; } if (!verifyPublic) throw new Error('OAuth 2.0 public client strategy requires a verifyPublic function'); passport.Strategy.call(this); this.name = 'oauth2-public-client'; this._verifyPublic = verifyPublic; this._passReqToCallback = options.passReqToCallback; }
[ "function", "Strategy", "(", "options", ",", "verifyPublic", ")", "{", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "verifyPublic", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "!", "verifyPublic", ")", "throw", "new", "Error", "(", "'OAuth 2.0 public client strategy requires a verifyPublic function'", ")", ";", "passport", ".", "Strategy", ".", "call", "(", "this", ")", ";", "this", ".", "name", "=", "'oauth2-public-client'", ";", "this", ".", "_verifyPublic", "=", "verifyPublic", ";", "this", ".", "_passReqToCallback", "=", "options", ".", "passReqToCallback", ";", "}" ]
`PublicClientStrategy` constructor. @api protected
[ "PublicClientStrategy", "constructor", "." ]
aeb71104b80e74bb18516acb18b2401e5e0b19ef
https://github.com/timshadel/passport-oauth2-public-client/blob/aeb71104b80e74bb18516acb18b2401e5e0b19ef/lib/passport-oauth2-public-client/strategy.js#L13-L24
40,935
amper5and/voice.js
examples/tokens.js
newToken
function newToken(){ // check if the client has all the tokens var allRetrieved = true; var tokens = client.getTokens(); ['auth', 'gvx', 'rnr'].forEach(function(type){ if(!tokens.hasOwnProperty(type)){ allRetrieved = false; } }); if(allRetrieved){ // save tokens once all have been retrieved fs.writeFileSync('./tokens.json', JSON.stringify(tokens)); console.log('\n\nALL TOKENS SAVED TO tokens.json') } }
javascript
function newToken(){ // check if the client has all the tokens var allRetrieved = true; var tokens = client.getTokens(); ['auth', 'gvx', 'rnr'].forEach(function(type){ if(!tokens.hasOwnProperty(type)){ allRetrieved = false; } }); if(allRetrieved){ // save tokens once all have been retrieved fs.writeFileSync('./tokens.json', JSON.stringify(tokens)); console.log('\n\nALL TOKENS SAVED TO tokens.json') } }
[ "function", "newToken", "(", ")", "{", "// check if the client has all the tokens", "var", "allRetrieved", "=", "true", ";", "var", "tokens", "=", "client", ".", "getTokens", "(", ")", ";", "[", "'auth'", ",", "'gvx'", ",", "'rnr'", "]", ".", "forEach", "(", "function", "(", "type", ")", "{", "if", "(", "!", "tokens", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "allRetrieved", "=", "false", ";", "}", "}", ")", ";", "if", "(", "allRetrieved", ")", "{", "// save tokens once all have been retrieved", "fs", ".", "writeFileSync", "(", "'./tokens.json'", ",", "JSON", ".", "stringify", "(", "tokens", ")", ")", ";", "console", ".", "log", "(", "'\\n\\nALL TOKENS SAVED TO tokens.json'", ")", "}", "}" ]
This fn will monitor token events until all 3 tokens are retrieved. When all three are retrieved, they will be saved to tokens.json
[ "This", "fn", "will", "monitor", "token", "events", "until", "all", "3", "tokens", "are", "retrieved", ".", "When", "all", "three", "are", "retrieved", "they", "will", "be", "saved", "to", "tokens", ".", "json" ]
362992e3be792ac4c3a948d8b445df2aea19d926
https://github.com/amper5and/voice.js/blob/362992e3be792ac4c3a948d8b445df2aea19d926/examples/tokens.js#L15-L29
40,936
olalonde/eslint-import-resolver-babel-root-import
src/index.js
getConfigFromBabel
function getConfigFromBabel(start, babelrc = '.babelrc') { if (start === '/') return []; const packageJSONPath = path.join(start, 'package.json'); const packageJSON = require(packageJSONPath); const babelConfig = packageJSON.babel; if (babelConfig) { const pluginConfig = babelConfig.plugins.find(p => ( p[0] === 'babel-root-import' )); process.chdir(path.dirname(packageJSONPath)); return pluginConfig[1]; } const babelrcPath = path.join(start, babelrc); if (fs.existsSync(babelrcPath)) { const babelrcJson = JSON5.parse(fs.readFileSync(babelrcPath, 'utf8')); if (babelrcJson && Array.isArray(babelrcJson.plugins)) { const pluginConfig = babelrcJson.plugins.find(p => ( p[0] === 'babel-plugin-root-import' )); // The src path inside babelrc are from the root so we have // to change the working directory for the same directory // to make the mapping to work properly process.chdir(path.dirname(babelrcPath)); return pluginConfig[1]; } } return getConfigFromBabel(path.dirname(start)); }
javascript
function getConfigFromBabel(start, babelrc = '.babelrc') { if (start === '/') return []; const packageJSONPath = path.join(start, 'package.json'); const packageJSON = require(packageJSONPath); const babelConfig = packageJSON.babel; if (babelConfig) { const pluginConfig = babelConfig.plugins.find(p => ( p[0] === 'babel-root-import' )); process.chdir(path.dirname(packageJSONPath)); return pluginConfig[1]; } const babelrcPath = path.join(start, babelrc); if (fs.existsSync(babelrcPath)) { const babelrcJson = JSON5.parse(fs.readFileSync(babelrcPath, 'utf8')); if (babelrcJson && Array.isArray(babelrcJson.plugins)) { const pluginConfig = babelrcJson.plugins.find(p => ( p[0] === 'babel-plugin-root-import' )); // The src path inside babelrc are from the root so we have // to change the working directory for the same directory // to make the mapping to work properly process.chdir(path.dirname(babelrcPath)); return pluginConfig[1]; } } return getConfigFromBabel(path.dirname(start)); }
[ "function", "getConfigFromBabel", "(", "start", ",", "babelrc", "=", "'.babelrc'", ")", "{", "if", "(", "start", "===", "'/'", ")", "return", "[", "]", ";", "const", "packageJSONPath", "=", "path", ".", "join", "(", "start", ",", "'package.json'", ")", ";", "const", "packageJSON", "=", "require", "(", "packageJSONPath", ")", ";", "const", "babelConfig", "=", "packageJSON", ".", "babel", ";", "if", "(", "babelConfig", ")", "{", "const", "pluginConfig", "=", "babelConfig", ".", "plugins", ".", "find", "(", "p", "=>", "(", "p", "[", "0", "]", "===", "'babel-root-import'", ")", ")", ";", "process", ".", "chdir", "(", "path", ".", "dirname", "(", "packageJSONPath", ")", ")", ";", "return", "pluginConfig", "[", "1", "]", ";", "}", "const", "babelrcPath", "=", "path", ".", "join", "(", "start", ",", "babelrc", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "babelrcPath", ")", ")", "{", "const", "babelrcJson", "=", "JSON5", ".", "parse", "(", "fs", ".", "readFileSync", "(", "babelrcPath", ",", "'utf8'", ")", ")", ";", "if", "(", "babelrcJson", "&&", "Array", ".", "isArray", "(", "babelrcJson", ".", "plugins", ")", ")", "{", "const", "pluginConfig", "=", "babelrcJson", ".", "plugins", ".", "find", "(", "p", "=>", "(", "p", "[", "0", "]", "===", "'babel-plugin-root-import'", ")", ")", ";", "// The src path inside babelrc are from the root so we have", "// to change the working directory for the same directory", "// to make the mapping to work properly", "process", ".", "chdir", "(", "path", ".", "dirname", "(", "babelrcPath", ")", ")", ";", "return", "pluginConfig", "[", "1", "]", ";", "}", "}", "return", "getConfigFromBabel", "(", "path", ".", "dirname", "(", "start", ")", ")", ";", "}" ]
returns the root import config as an object
[ "returns", "the", "root", "import", "config", "as", "an", "object" ]
86c7a0358489c89519df63fb69b5b7b4cd849c7a
https://github.com/olalonde/eslint-import-resolver-babel-root-import/blob/86c7a0358489c89519df63fb69b5b7b4cd849c7a/src/index.js#L28-L57
40,937
FauzanKhan/angular-popover
src/js/ngPopover.js
function($scope, element, attrs, ctrl) { $scope.popoverClass = attrs.popoverClass; $scope.dropDirection = attrs.direction || 'bottom'; var left, top; var trigger = document.querySelector('#'+$scope.trigger); var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); // Add click event listener to trigger trigger.addEventListener('click', function(ev){ var left, top; var trigger = this; //get trigger element var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); //get triger's target popover ev.preventDefault(); calcPopoverPosition(trigger, target); //calculate the position of the popover hideAllPopovers(trigger); target.classList.toggle('hide'); //toggle display of target popover // if target popover is visible then add click listener to body and call the open popover callback if(!target.classList.contains('hide')){ ctrl.registerBodyListener(); $scope.onOpen(); $scope.$apply(); } //else remove click listener from body and call close popover callback else{ ctrl.unregisterBodyListener(); $scope.onClose(); $scope.$apply(); } }); var getTriggerOffset = function(){ var triggerRect = trigger.getBoundingClientRect(); var bodyRect = document.body.getBoundingClientRect(); return { top: triggerRect.top + document.body.scrollTop, left: triggerRect.left + document.body.scrollLeft } }; // calculates the position of the popover var calcPopoverPosition = function(trigger, target){ target.classList.toggle('hide'); var targetWidth = target.offsetWidth; var targetHeight = target.offsetHeight; target.classList.toggle('hide'); var triggerWidth = trigger.offsetWidth; var triggerHeight = trigger.offsetHeight; switch($scope.dropDirection){ case 'left': { left = getTriggerOffset().left - targetWidth - 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case 'right':{ left = getTriggerOffset().left + triggerWidth + 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case'top':{ left = getTriggerOffset().left + 'px'; top = getTriggerOffset().top - targetHeight - 10 + 'px'; break; } default:{ left = getTriggerOffset().left +'px'; top = getTriggerOffset().top + triggerHeight + 10 + 'px' } } target.style.position = 'absolute'; target.style.left = left; target.style.top = top; } calcPopoverPosition(trigger, target); }
javascript
function($scope, element, attrs, ctrl) { $scope.popoverClass = attrs.popoverClass; $scope.dropDirection = attrs.direction || 'bottom'; var left, top; var trigger = document.querySelector('#'+$scope.trigger); var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); // Add click event listener to trigger trigger.addEventListener('click', function(ev){ var left, top; var trigger = this; //get trigger element var target = document.querySelector('.ng-popover[trigger="'+$scope.trigger+'"]'); //get triger's target popover ev.preventDefault(); calcPopoverPosition(trigger, target); //calculate the position of the popover hideAllPopovers(trigger); target.classList.toggle('hide'); //toggle display of target popover // if target popover is visible then add click listener to body and call the open popover callback if(!target.classList.contains('hide')){ ctrl.registerBodyListener(); $scope.onOpen(); $scope.$apply(); } //else remove click listener from body and call close popover callback else{ ctrl.unregisterBodyListener(); $scope.onClose(); $scope.$apply(); } }); var getTriggerOffset = function(){ var triggerRect = trigger.getBoundingClientRect(); var bodyRect = document.body.getBoundingClientRect(); return { top: triggerRect.top + document.body.scrollTop, left: triggerRect.left + document.body.scrollLeft } }; // calculates the position of the popover var calcPopoverPosition = function(trigger, target){ target.classList.toggle('hide'); var targetWidth = target.offsetWidth; var targetHeight = target.offsetHeight; target.classList.toggle('hide'); var triggerWidth = trigger.offsetWidth; var triggerHeight = trigger.offsetHeight; switch($scope.dropDirection){ case 'left': { left = getTriggerOffset().left - targetWidth - 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case 'right':{ left = getTriggerOffset().left + triggerWidth + 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case'top':{ left = getTriggerOffset().left + 'px'; top = getTriggerOffset().top - targetHeight - 10 + 'px'; break; } default:{ left = getTriggerOffset().left +'px'; top = getTriggerOffset().top + triggerHeight + 10 + 'px' } } target.style.position = 'absolute'; target.style.left = left; target.style.top = top; } calcPopoverPosition(trigger, target); }
[ "function", "(", "$scope", ",", "element", ",", "attrs", ",", "ctrl", ")", "{", "$scope", ".", "popoverClass", "=", "attrs", ".", "popoverClass", ";", "$scope", ".", "dropDirection", "=", "attrs", ".", "direction", "||", "'bottom'", ";", "var", "left", ",", "top", ";", "var", "trigger", "=", "document", ".", "querySelector", "(", "'#'", "+", "$scope", ".", "trigger", ")", ";", "var", "target", "=", "document", ".", "querySelector", "(", "'.ng-popover[trigger=\"'", "+", "$scope", ".", "trigger", "+", "'\"]'", ")", ";", "// Add click event listener to trigger", "trigger", ".", "addEventListener", "(", "'click'", ",", "function", "(", "ev", ")", "{", "var", "left", ",", "top", ";", "var", "trigger", "=", "this", ";", "//get trigger element ", "var", "target", "=", "document", ".", "querySelector", "(", "'.ng-popover[trigger=\"'", "+", "$scope", ".", "trigger", "+", "'\"]'", ")", ";", "//get triger's target popover", "ev", ".", "preventDefault", "(", ")", ";", "calcPopoverPosition", "(", "trigger", ",", "target", ")", ";", "//calculate the position of the popover", "hideAllPopovers", "(", "trigger", ")", ";", "target", ".", "classList", ".", "toggle", "(", "'hide'", ")", ";", "//toggle display of target popover", "// if target popover is visible then add click listener to body and call the open popover callback", "if", "(", "!", "target", ".", "classList", ".", "contains", "(", "'hide'", ")", ")", "{", "ctrl", ".", "registerBodyListener", "(", ")", ";", "$scope", ".", "onOpen", "(", ")", ";", "$scope", ".", "$apply", "(", ")", ";", "}", "//else remove click listener from body and call close popover callback", "else", "{", "ctrl", ".", "unregisterBodyListener", "(", ")", ";", "$scope", ".", "onClose", "(", ")", ";", "$scope", ".", "$apply", "(", ")", ";", "}", "}", ")", ";", "var", "getTriggerOffset", "=", "function", "(", ")", "{", "var", "triggerRect", "=", "trigger", ".", "getBoundingClientRect", "(", ")", ";", "var", "bodyRect", "=", "document", ".", "body", ".", "getBoundingClientRect", "(", ")", ";", "return", "{", "top", ":", "triggerRect", ".", "top", "+", "document", ".", "body", ".", "scrollTop", ",", "left", ":", "triggerRect", ".", "left", "+", "document", ".", "body", ".", "scrollLeft", "}", "}", ";", "// calculates the position of the popover", "var", "calcPopoverPosition", "=", "function", "(", "trigger", ",", "target", ")", "{", "target", ".", "classList", ".", "toggle", "(", "'hide'", ")", ";", "var", "targetWidth", "=", "target", ".", "offsetWidth", ";", "var", "targetHeight", "=", "target", ".", "offsetHeight", ";", "target", ".", "classList", ".", "toggle", "(", "'hide'", ")", ";", "var", "triggerWidth", "=", "trigger", ".", "offsetWidth", ";", "var", "triggerHeight", "=", "trigger", ".", "offsetHeight", ";", "switch", "(", "$scope", ".", "dropDirection", ")", "{", "case", "'left'", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "-", "targetWidth", "-", "10", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "+", "'px'", ";", "break", ";", "}", "case", "'right'", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "+", "triggerWidth", "+", "10", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "+", "'px'", ";", "break", ";", "}", "case", "'top'", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "-", "targetHeight", "-", "10", "+", "'px'", ";", "break", ";", "}", "default", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "+", "triggerHeight", "+", "10", "+", "'px'", "}", "}", "target", ".", "style", ".", "position", "=", "'absolute'", ";", "target", ".", "style", ".", "left", "=", "left", ";", "target", ".", "style", ".", "top", "=", "top", ";", "}", "calcPopoverPosition", "(", "trigger", ",", "target", ")", ";", "}" ]
we want to insert custom content inside the directive
[ "we", "want", "to", "insert", "custom", "content", "inside", "the", "directive" ]
057869772aa22e2df643495e4595dc7448975875
https://github.com/FauzanKhan/angular-popover/blob/057869772aa22e2df643495e4595dc7448975875/src/js/ngPopover.js#L16-L92
40,938
FauzanKhan/angular-popover
src/js/ngPopover.js
function(trigger, target){ target.classList.toggle('hide'); var targetWidth = target.offsetWidth; var targetHeight = target.offsetHeight; target.classList.toggle('hide'); var triggerWidth = trigger.offsetWidth; var triggerHeight = trigger.offsetHeight; switch($scope.dropDirection){ case 'left': { left = getTriggerOffset().left - targetWidth - 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case 'right':{ left = getTriggerOffset().left + triggerWidth + 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case'top':{ left = getTriggerOffset().left + 'px'; top = getTriggerOffset().top - targetHeight - 10 + 'px'; break; } default:{ left = getTriggerOffset().left +'px'; top = getTriggerOffset().top + triggerHeight + 10 + 'px' } } target.style.position = 'absolute'; target.style.left = left; target.style.top = top; }
javascript
function(trigger, target){ target.classList.toggle('hide'); var targetWidth = target.offsetWidth; var targetHeight = target.offsetHeight; target.classList.toggle('hide'); var triggerWidth = trigger.offsetWidth; var triggerHeight = trigger.offsetHeight; switch($scope.dropDirection){ case 'left': { left = getTriggerOffset().left - targetWidth - 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case 'right':{ left = getTriggerOffset().left + triggerWidth + 10 + 'px'; top = getTriggerOffset().top + 'px'; break; } case'top':{ left = getTriggerOffset().left + 'px'; top = getTriggerOffset().top - targetHeight - 10 + 'px'; break; } default:{ left = getTriggerOffset().left +'px'; top = getTriggerOffset().top + triggerHeight + 10 + 'px' } } target.style.position = 'absolute'; target.style.left = left; target.style.top = top; }
[ "function", "(", "trigger", ",", "target", ")", "{", "target", ".", "classList", ".", "toggle", "(", "'hide'", ")", ";", "var", "targetWidth", "=", "target", ".", "offsetWidth", ";", "var", "targetHeight", "=", "target", ".", "offsetHeight", ";", "target", ".", "classList", ".", "toggle", "(", "'hide'", ")", ";", "var", "triggerWidth", "=", "trigger", ".", "offsetWidth", ";", "var", "triggerHeight", "=", "trigger", ".", "offsetHeight", ";", "switch", "(", "$scope", ".", "dropDirection", ")", "{", "case", "'left'", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "-", "targetWidth", "-", "10", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "+", "'px'", ";", "break", ";", "}", "case", "'right'", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "+", "triggerWidth", "+", "10", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "+", "'px'", ";", "break", ";", "}", "case", "'top'", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "-", "targetHeight", "-", "10", "+", "'px'", ";", "break", ";", "}", "default", ":", "{", "left", "=", "getTriggerOffset", "(", ")", ".", "left", "+", "'px'", ";", "top", "=", "getTriggerOffset", "(", ")", ".", "top", "+", "triggerHeight", "+", "10", "+", "'px'", "}", "}", "target", ".", "style", ".", "position", "=", "'absolute'", ";", "target", ".", "style", ".", "left", "=", "left", ";", "target", ".", "style", ".", "top", "=", "top", ";", "}" ]
calculates the position of the popover
[ "calculates", "the", "position", "of", "the", "popover" ]
057869772aa22e2df643495e4595dc7448975875
https://github.com/FauzanKhan/angular-popover/blob/057869772aa22e2df643495e4595dc7448975875/src/js/ngPopover.js#L56-L90
40,939
FauzanKhan/angular-popover
src/js/ngPopover.js
function(trigger){ var triggerId; if(trigger) triggerId = trigger.getAttribute('id'); var allPopovers = trigger != undefined ? document.querySelectorAll('.ng-popover:not([trigger="'+triggerId+'"])') : document.querySelectorAll('.ng-popover'); for(var i =0; i<allPopovers.length; i++){ var popover = allPopovers[i]; if(!popover.classList.contains('hide')) popover.classList.add('hide') } }
javascript
function(trigger){ var triggerId; if(trigger) triggerId = trigger.getAttribute('id'); var allPopovers = trigger != undefined ? document.querySelectorAll('.ng-popover:not([trigger="'+triggerId+'"])') : document.querySelectorAll('.ng-popover'); for(var i =0; i<allPopovers.length; i++){ var popover = allPopovers[i]; if(!popover.classList.contains('hide')) popover.classList.add('hide') } }
[ "function", "(", "trigger", ")", "{", "var", "triggerId", ";", "if", "(", "trigger", ")", "triggerId", "=", "trigger", ".", "getAttribute", "(", "'id'", ")", ";", "var", "allPopovers", "=", "trigger", "!=", "undefined", "?", "document", ".", "querySelectorAll", "(", "'.ng-popover:not([trigger=\"'", "+", "triggerId", "+", "'\"])'", ")", ":", "document", ".", "querySelectorAll", "(", "'.ng-popover'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allPopovers", ".", "length", ";", "i", "++", ")", "{", "var", "popover", "=", "allPopovers", "[", "i", "]", ";", "if", "(", "!", "popover", ".", "classList", ".", "contains", "(", "'hide'", ")", ")", "popover", ".", "classList", ".", "add", "(", "'hide'", ")", "}", "}" ]
Hides all popovers, skips the popover whose trigger Id is provided in the function call
[ "Hides", "all", "popovers", "skips", "the", "popover", "whose", "trigger", "Id", "is", "provided", "in", "the", "function", "call" ]
057869772aa22e2df643495e4595dc7448975875
https://github.com/FauzanKhan/angular-popover/blob/057869772aa22e2df643495e4595dc7448975875/src/js/ngPopover.js#L140-L150
40,940
gwtw/js-binary-heap
index.js
heapify
function heapify(heap, i) { var l = getLeft(i); var r = getRight(i); var smallest = i; if (l < heap.list.length && heap.compare(heap.list[l], heap.list[i]) < 0) { smallest = l; } if (r < heap.list.length && heap.compare(heap.list[r], heap.list[smallest]) < 0) { smallest = r; } if (smallest !== i) { swap(heap.list, i, smallest); heapify(heap, smallest); } }
javascript
function heapify(heap, i) { var l = getLeft(i); var r = getRight(i); var smallest = i; if (l < heap.list.length && heap.compare(heap.list[l], heap.list[i]) < 0) { smallest = l; } if (r < heap.list.length && heap.compare(heap.list[r], heap.list[smallest]) < 0) { smallest = r; } if (smallest !== i) { swap(heap.list, i, smallest); heapify(heap, smallest); } }
[ "function", "heapify", "(", "heap", ",", "i", ")", "{", "var", "l", "=", "getLeft", "(", "i", ")", ";", "var", "r", "=", "getRight", "(", "i", ")", ";", "var", "smallest", "=", "i", ";", "if", "(", "l", "<", "heap", ".", "list", ".", "length", "&&", "heap", ".", "compare", "(", "heap", ".", "list", "[", "l", "]", ",", "heap", ".", "list", "[", "i", "]", ")", "<", "0", ")", "{", "smallest", "=", "l", ";", "}", "if", "(", "r", "<", "heap", ".", "list", ".", "length", "&&", "heap", ".", "compare", "(", "heap", ".", "list", "[", "r", "]", ",", "heap", ".", "list", "[", "smallest", "]", ")", "<", "0", ")", "{", "smallest", "=", "r", ";", "}", "if", "(", "smallest", "!==", "i", ")", "{", "swap", "(", "heap", ".", "list", ",", "i", ",", "smallest", ")", ";", "heapify", "(", "heap", ",", "smallest", ")", ";", "}", "}" ]
Heapifies a node. @private @param {BinaryHeap} heap The heap containing the node to heapify. @param {number} i The index of the node to heapify.
[ "Heapifies", "a", "node", "." ]
4550c7a686672333433bbfe134e34d84a35ddc91
https://github.com/gwtw/js-binary-heap/blob/4550c7a686672333433bbfe134e34d84a35ddc91/index.js#L151-L167
40,941
gwtw/js-binary-heap
index.js
buildHeapFromNodeArray
function buildHeapFromNodeArray(heap, nodeArray) { heap.list = nodeArray; for (var i = Math.floor(heap.list.length / 2); i >= 0; i--) { heapify(heap, i); } }
javascript
function buildHeapFromNodeArray(heap, nodeArray) { heap.list = nodeArray; for (var i = Math.floor(heap.list.length / 2); i >= 0; i--) { heapify(heap, i); } }
[ "function", "buildHeapFromNodeArray", "(", "heap", ",", "nodeArray", ")", "{", "heap", ".", "list", "=", "nodeArray", ";", "for", "(", "var", "i", "=", "Math", ".", "floor", "(", "heap", ".", "list", ".", "length", "/", "2", ")", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "heapify", "(", "heap", ",", "i", ")", ";", "}", "}" ]
Builds a heap from a node array, this will discard the heap's current data. @private @param {BinaryHeap} heap The heap to override. @param {Node[]} nodeArray The array of nodes for the new heap.
[ "Builds", "a", "heap", "from", "a", "node", "array", "this", "will", "discard", "the", "heap", "s", "current", "data", "." ]
4550c7a686672333433bbfe134e34d84a35ddc91
https://github.com/gwtw/js-binary-heap/blob/4550c7a686672333433bbfe134e34d84a35ddc91/index.js#L176-L181
40,942
SmartTeleMax/MaSha
docs/js/packed.js
function() { var this_ = this; this.msg = (typeof this.options.select_message == 'string'? document.getElementById(this.options.select_message): this.options.select_message); this.close_button = this.get_close_button(); this.msg_autoclose = null; addEvent(this.close_button, 'click', function(e){ preventDefault(e); this_.hide_message(); this_.save_message_closed(); clearTimeout(this_.msg_autoclose); }); }
javascript
function() { var this_ = this; this.msg = (typeof this.options.select_message == 'string'? document.getElementById(this.options.select_message): this.options.select_message); this.close_button = this.get_close_button(); this.msg_autoclose = null; addEvent(this.close_button, 'click', function(e){ preventDefault(e); this_.hide_message(); this_.save_message_closed(); clearTimeout(this_.msg_autoclose); }); }
[ "function", "(", ")", "{", "var", "this_", "=", "this", ";", "this", ".", "msg", "=", "(", "typeof", "this", ".", "options", ".", "select_message", "==", "'string'", "?", "document", ".", "getElementById", "(", "this", ".", "options", ".", "select_message", ")", ":", "this", ".", "options", ".", "select_message", ")", ";", "this", ".", "close_button", "=", "this", ".", "get_close_button", "(", ")", ";", "this", ".", "msg_autoclose", "=", "null", ";", "addEvent", "(", "this", ".", "close_button", ",", "'click'", ",", "function", "(", "e", ")", "{", "preventDefault", "(", "e", ")", ";", "this_", ".", "hide_message", "(", ")", ";", "this_", ".", "save_message_closed", "(", ")", ";", "clearTimeout", "(", "this_", ".", "msg_autoclose", ")", ";", "}", ")", ";", "}" ]
message.js
[ "message", ".", "js" ]
5002411033f3f3969930a61e7aaa4b8e818cf5d8
https://github.com/SmartTeleMax/MaSha/blob/5002411033f3f3969930a61e7aaa4b8e818cf5d8/docs/js/packed.js#L12195-L12210
40,943
ngokevin/aframe-physics-components
src/index.js
function () { var body = this.body; var el = this.el; el.setAttribute('position', body.position); el.setAttribute('rotation', { x: deg(body.quaternion.x), y: deg(body.quaternion.y), z: deg(body.quaternion.z) }); }
javascript
function () { var body = this.body; var el = this.el; el.setAttribute('position', body.position); el.setAttribute('rotation', { x: deg(body.quaternion.x), y: deg(body.quaternion.y), z: deg(body.quaternion.z) }); }
[ "function", "(", ")", "{", "var", "body", "=", "this", ".", "body", ";", "var", "el", "=", "this", ".", "el", ";", "el", ".", "setAttribute", "(", "'position'", ",", "body", ".", "position", ")", ";", "el", ".", "setAttribute", "(", "'rotation'", ",", "{", "x", ":", "deg", "(", "body", ".", "quaternion", ".", "x", ")", ",", "y", ":", "deg", "(", "body", ".", "quaternion", ".", "y", ")", ",", "z", ":", "deg", "(", "body", ".", "quaternion", ".", "z", ")", "}", ")", ";", "}" ]
Copy CANNON rigid body properties to THREE object3D.
[ "Copy", "CANNON", "rigid", "body", "properties", "to", "THREE", "object3D", "." ]
3676f496d36a0c7e2611f184fe4be528b010cb9a
https://github.com/ngokevin/aframe-physics-components/blob/3676f496d36a0c7e2611f184fe4be528b010cb9a/src/index.js#L269-L278
40,944
SmartTeleMax/MaSha
src/js/masha.js
function(numclasses) { for (var i = numclasses.length; i--;) { var numclass = numclasses[i]; var spans = byClassName(this.selectable, numclass); var closewrap = firstWithClass(spans[spans.length - 1], 'closewrap'); closewrap.parentNode.removeChild(closewrap); this.removeTextSelection(spans); delete this.ranges[numclass]; } }
javascript
function(numclasses) { for (var i = numclasses.length; i--;) { var numclass = numclasses[i]; var spans = byClassName(this.selectable, numclass); var closewrap = firstWithClass(spans[spans.length - 1], 'closewrap'); closewrap.parentNode.removeChild(closewrap); this.removeTextSelection(spans); delete this.ranges[numclass]; } }
[ "function", "(", "numclasses", ")", "{", "for", "(", "var", "i", "=", "numclasses", ".", "length", ";", "i", "--", ";", ")", "{", "var", "numclass", "=", "numclasses", "[", "i", "]", ";", "var", "spans", "=", "byClassName", "(", "this", ".", "selectable", ",", "numclass", ")", ";", "var", "closewrap", "=", "firstWithClass", "(", "spans", "[", "spans", ".", "length", "-", "1", "]", ",", "'closewrap'", ")", ";", "closewrap", ".", "parentNode", ".", "removeChild", "(", "closewrap", ")", ";", "this", ".", "removeTextSelection", "(", "spans", ")", ";", "delete", "this", ".", "ranges", "[", "numclass", "]", ";", "}", "}" ]
XXX sort methods logically
[ "XXX", "sort", "methods", "logically" ]
5002411033f3f3969930a61e7aaa4b8e818cf5d8
https://github.com/SmartTeleMax/MaSha/blob/5002411033f3f3969930a61e7aaa4b8e818cf5d8/src/js/masha.js#L333-L343
40,945
vega/vega-scale
src/scales.js
create
function create(type, constructor) { return function scale() { var s = constructor(); if (!s.invertRange) { s.invertRange = s.invert ? invertRange(s) : s.invertExtent ? invertRangeExtent(s) : undefined; } s.type = type; return s; }; }
javascript
function create(type, constructor) { return function scale() { var s = constructor(); if (!s.invertRange) { s.invertRange = s.invert ? invertRange(s) : s.invertExtent ? invertRangeExtent(s) : undefined; } s.type = type; return s; }; }
[ "function", "create", "(", "type", ",", "constructor", ")", "{", "return", "function", "scale", "(", ")", "{", "var", "s", "=", "constructor", "(", ")", ";", "if", "(", "!", "s", ".", "invertRange", ")", "{", "s", ".", "invertRange", "=", "s", ".", "invert", "?", "invertRange", "(", "s", ")", ":", "s", ".", "invertExtent", "?", "invertRangeExtent", "(", "s", ")", ":", "undefined", ";", "}", "s", ".", "type", "=", "type", ";", "return", "s", ";", "}", ";", "}" ]
Augment scales with their type and needed inverse methods.
[ "Augment", "scales", "with", "their", "type", "and", "needed", "inverse", "methods", "." ]
6c29c4a4e6ddf50ac2cdeb8e105228a9b86f86b5
https://github.com/vega/vega-scale/blob/6c29c4a4e6ddf50ac2cdeb8e105228a9b86f86b5/src/scales.js#L18-L31
40,946
rd-dev-ukraine/angular-io-datepicker
src/datepicker/datePicker.js
parserFabric
function parserFabric(mode, format) { return function (value, parseFn) { parseFn = parseFn || moment_1.utc; if (value === null || value === undefined || value === "") { return null; } var formatsToParse = parseFormat[mode || "date"]; return parseFn(value, [format].concat(formatsToParse), true); }; }
javascript
function parserFabric(mode, format) { return function (value, parseFn) { parseFn = parseFn || moment_1.utc; if (value === null || value === undefined || value === "") { return null; } var formatsToParse = parseFormat[mode || "date"]; return parseFn(value, [format].concat(formatsToParse), true); }; }
[ "function", "parserFabric", "(", "mode", ",", "format", ")", "{", "return", "function", "(", "value", ",", "parseFn", ")", "{", "parseFn", "=", "parseFn", "||", "moment_1", ".", "utc", ";", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", "||", "value", "===", "\"\"", ")", "{", "return", "null", ";", "}", "var", "formatsToParse", "=", "parseFormat", "[", "mode", "||", "\"date\"", "]", ";", "return", "parseFn", "(", "value", ",", "[", "format", "]", ".", "concat", "(", "formatsToParse", ")", ",", "true", ")", ";", "}", ";", "}" ]
Parses the given value as date using moment.js. If value cannot be parsed the invalid Moment object is returned. The calling code should not assume if the method returns local or utc value and must convert value to corresponding form itself.
[ "Parses", "the", "given", "value", "as", "date", "using", "moment", ".", "js", ".", "If", "value", "cannot", "be", "parsed", "the", "invalid", "Moment", "object", "is", "returned", ".", "The", "calling", "code", "should", "not", "assume", "if", "the", "method", "returns", "local", "or", "utc", "value", "and", "must", "convert", "value", "to", "corresponding", "form", "itself", "." ]
8338812942fd9f7f68138b328dc637a4f0ff33e0
https://github.com/rd-dev-ukraine/angular-io-datepicker/blob/8338812942fd9f7f68138b328dc637a4f0ff33e0/src/datepicker/datePicker.js#L60-L69
40,947
ryym/mocha-each
gulpfile.babel.js
runAndWatch
function runAndWatch(watchPattern, initialValue, task) { gulp.watch(watchPattern, event => { task(event.path, event); }); return task(initialValue); }
javascript
function runAndWatch(watchPattern, initialValue, task) { gulp.watch(watchPattern, event => { task(event.path, event); }); return task(initialValue); }
[ "function", "runAndWatch", "(", "watchPattern", ",", "initialValue", ",", "task", ")", "{", "gulp", ".", "watch", "(", "watchPattern", ",", "event", "=>", "{", "task", "(", "event", ".", "path", ",", "event", ")", ";", "}", ")", ";", "return", "task", "(", "initialValue", ")", ";", "}" ]
Run a given task. And re-run it whenever the specified files change.
[ "Run", "a", "given", "task", ".", "And", "re", "-", "run", "it", "whenever", "the", "specified", "files", "change", "." ]
99d70474c4ec222c6eab6ceaac0886410dfe0dca
https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/gulpfile.babel.js#L53-L58
40,948
ryym/mocha-each
gulpfile.babel.js
lintFiles
function lintFiles(pattern, strict, configs) { const linter = new eslint.CLIEngine(configs); const report = linter.executeOnFiles([pattern]); const formatter = linter.getFormatter(); console.log(formatter(report.results)); if (0 < report.errorCount || (strict && 0 < report.warningCount)) { throw new Error('eslint reports some problems.'); } }
javascript
function lintFiles(pattern, strict, configs) { const linter = new eslint.CLIEngine(configs); const report = linter.executeOnFiles([pattern]); const formatter = linter.getFormatter(); console.log(formatter(report.results)); if (0 < report.errorCount || (strict && 0 < report.warningCount)) { throw new Error('eslint reports some problems.'); } }
[ "function", "lintFiles", "(", "pattern", ",", "strict", ",", "configs", ")", "{", "const", "linter", "=", "new", "eslint", ".", "CLIEngine", "(", "configs", ")", ";", "const", "report", "=", "linter", ".", "executeOnFiles", "(", "[", "pattern", "]", ")", ";", "const", "formatter", "=", "linter", ".", "getFormatter", "(", ")", ";", "console", ".", "log", "(", "formatter", "(", "report", ".", "results", ")", ")", ";", "if", "(", "0", "<", "report", ".", "errorCount", "||", "(", "strict", "&&", "0", "<", "report", ".", "warningCount", ")", ")", "{", "throw", "new", "Error", "(", "'eslint reports some problems.'", ")", ";", "}", "}" ]
Lint the specified files using eslint.
[ "Lint", "the", "specified", "files", "using", "eslint", "." ]
99d70474c4ec222c6eab6ceaac0886410dfe0dca
https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/gulpfile.babel.js#L86-L94
40,949
ryym/mocha-each
lib/index.js
forEach
function forEach(parameters, dIt = global.it, dDescribe = global.describe) { const it = makeTestCaseDefiner(parameters, dIt); it.skip = makeParameterizedSkip(parameters, dIt); it.only = makeParameterizedOnly(parameters, dIt); const describe = makeTestCaseDefiner(parameters, dDescribe); describe.skip = makeParameterizedSkip(parameters, dDescribe); describe.only = makeParameterizedOnly(parameters, dDescribe); return { it, describe }; }
javascript
function forEach(parameters, dIt = global.it, dDescribe = global.describe) { const it = makeTestCaseDefiner(parameters, dIt); it.skip = makeParameterizedSkip(parameters, dIt); it.only = makeParameterizedOnly(parameters, dIt); const describe = makeTestCaseDefiner(parameters, dDescribe); describe.skip = makeParameterizedSkip(parameters, dDescribe); describe.only = makeParameterizedOnly(parameters, dDescribe); return { it, describe }; }
[ "function", "forEach", "(", "parameters", ",", "dIt", "=", "global", ".", "it", ",", "dDescribe", "=", "global", ".", "describe", ")", "{", "const", "it", "=", "makeTestCaseDefiner", "(", "parameters", ",", "dIt", ")", ";", "it", ".", "skip", "=", "makeParameterizedSkip", "(", "parameters", ",", "dIt", ")", ";", "it", ".", "only", "=", "makeParameterizedOnly", "(", "parameters", ",", "dIt", ")", ";", "const", "describe", "=", "makeTestCaseDefiner", "(", "parameters", ",", "dDescribe", ")", ";", "describe", ".", "skip", "=", "makeParameterizedSkip", "(", "parameters", ",", "dDescribe", ")", ";", "describe", ".", "only", "=", "makeParameterizedOnly", "(", "parameters", ",", "dDescribe", ")", ";", "return", "{", "it", ",", "describe", "}", ";", "}" ]
Defines Mocha test cases for each given parameter. @param {Array} parameters @param {function} dIt - The 'it' function used in this function. If omitted, 'it' in global name space is used. @param {function} dDescribe - The 'describe' function used in this function. If omitted, 'describe' in global name space is used. @return {Object} The object which has a method to define test cases.
[ "Defines", "Mocha", "test", "cases", "for", "each", "given", "parameter", "." ]
99d70474c4ec222c6eab6ceaac0886410dfe0dca
https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/lib/index.js#L14-L22
40,950
ryym/mocha-each
lib/index.js
makeParameterizedOnly
function makeParameterizedOnly(parameters, defaultIt) { return function(title, test) { const it = makeTestCaseDefiner(parameters, defaultIt); global.describe.only('', () => it(title, test)); }; }
javascript
function makeParameterizedOnly(parameters, defaultIt) { return function(title, test) { const it = makeTestCaseDefiner(parameters, defaultIt); global.describe.only('', () => it(title, test)); }; }
[ "function", "makeParameterizedOnly", "(", "parameters", ",", "defaultIt", ")", "{", "return", "function", "(", "title", ",", "test", ")", "{", "const", "it", "=", "makeTestCaseDefiner", "(", "parameters", ",", "defaultIt", ")", ";", "global", ".", "describe", ".", "only", "(", "''", ",", "(", ")", "=>", "it", "(", "title", ",", "test", ")", ")", ";", "}", ";", "}" ]
Create a function which define exclusive parameterized tests. @private
[ "Create", "a", "function", "which", "define", "exclusive", "parameterized", "tests", "." ]
99d70474c4ec222c6eab6ceaac0886410dfe0dca
https://github.com/ryym/mocha-each/blob/99d70474c4ec222c6eab6ceaac0886410dfe0dca/lib/index.js#L40-L45
40,951
rd-dev-ukraine/angular-io-datepicker
src/datepicker/dateUtils.js
monthCalendar
function monthCalendar(date) { var start = date.clone().startOf("month").startOf("week").startOf("day"); var end = date.clone().endOf("month").endOf("week").startOf("day"); var result = []; var current = start.weekday(0).subtract(1, "d"); while (true) { current = current.clone().add(1, "d"); result.push(current); if (areDatesEqual(current, end)) { break; } } return result; }
javascript
function monthCalendar(date) { var start = date.clone().startOf("month").startOf("week").startOf("day"); var end = date.clone().endOf("month").endOf("week").startOf("day"); var result = []; var current = start.weekday(0).subtract(1, "d"); while (true) { current = current.clone().add(1, "d"); result.push(current); if (areDatesEqual(current, end)) { break; } } return result; }
[ "function", "monthCalendar", "(", "date", ")", "{", "var", "start", "=", "date", ".", "clone", "(", ")", ".", "startOf", "(", "\"month\"", ")", ".", "startOf", "(", "\"week\"", ")", ".", "startOf", "(", "\"day\"", ")", ";", "var", "end", "=", "date", ".", "clone", "(", ")", ".", "endOf", "(", "\"month\"", ")", ".", "endOf", "(", "\"week\"", ")", ".", "startOf", "(", "\"day\"", ")", ";", "var", "result", "=", "[", "]", ";", "var", "current", "=", "start", ".", "weekday", "(", "0", ")", ".", "subtract", "(", "1", ",", "\"d\"", ")", ";", "while", "(", "true", ")", "{", "current", "=", "current", ".", "clone", "(", ")", ".", "add", "(", "1", ",", "\"d\"", ")", ";", "result", ".", "push", "(", "current", ")", ";", "if", "(", "areDatesEqual", "(", "current", ",", "end", ")", ")", "{", "break", ";", "}", "}", "return", "result", ";", "}" ]
Array of days belongs to the month of the specified date including previous and next month days which are on the same week as first and last month days.
[ "Array", "of", "days", "belongs", "to", "the", "month", "of", "the", "specified", "date", "including", "previous", "and", "next", "month", "days", "which", "are", "on", "the", "same", "week", "as", "first", "and", "last", "month", "days", "." ]
8338812942fd9f7f68138b328dc637a4f0ff33e0
https://github.com/rd-dev-ukraine/angular-io-datepicker/blob/8338812942fd9f7f68138b328dc637a4f0ff33e0/src/datepicker/dateUtils.js#L19-L32
40,952
rd-dev-ukraine/angular-io-datepicker
src/datepicker/dateUtils.js
daysOfWeek
function daysOfWeek() { var result = []; for (var weekday = 0; weekday < 7; weekday++) { result.push(moment_1.utc().weekday(weekday).format("dd")); } return result; }
javascript
function daysOfWeek() { var result = []; for (var weekday = 0; weekday < 7; weekday++) { result.push(moment_1.utc().weekday(weekday).format("dd")); } return result; }
[ "function", "daysOfWeek", "(", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "weekday", "=", "0", ";", "weekday", "<", "7", ";", "weekday", "++", ")", "{", "result", ".", "push", "(", "moment_1", ".", "utc", "(", ")", ".", "weekday", "(", "weekday", ")", ".", "format", "(", "\"dd\"", ")", ")", ";", "}", "return", "result", ";", "}" ]
Gets array of localized days of week.
[ "Gets", "array", "of", "localized", "days", "of", "week", "." ]
8338812942fd9f7f68138b328dc637a4f0ff33e0
https://github.com/rd-dev-ukraine/angular-io-datepicker/blob/8338812942fd9f7f68138b328dc637a4f0ff33e0/src/datepicker/dateUtils.js#L37-L43
40,953
mairatma/babel-plugin-globals
index.js
assignDeclarationToGlobal
function assignDeclarationToGlobal(state, nodes, declaration) { var filenameNoExt = getFilenameNoExt(state.file.opts.filename); var expr = getGlobalExpression(state, filenameNoExt, declaration.id.name); assignToGlobal(expr, nodes, declaration.id); }
javascript
function assignDeclarationToGlobal(state, nodes, declaration) { var filenameNoExt = getFilenameNoExt(state.file.opts.filename); var expr = getGlobalExpression(state, filenameNoExt, declaration.id.name); assignToGlobal(expr, nodes, declaration.id); }
[ "function", "assignDeclarationToGlobal", "(", "state", ",", "nodes", ",", "declaration", ")", "{", "var", "filenameNoExt", "=", "getFilenameNoExt", "(", "state", ".", "file", ".", "opts", ".", "filename", ")", ";", "var", "expr", "=", "getGlobalExpression", "(", "state", ",", "filenameNoExt", ",", "declaration", ".", "id", ".", "name", ")", ";", "assignToGlobal", "(", "expr", ",", "nodes", ",", "declaration", ".", "id", ")", ";", "}" ]
Assigns the given declaration to the appropriate global variable. @param {!Object} state @param {!Array} nodes @param {!Declaration} declaration
[ "Assigns", "the", "given", "declaration", "to", "the", "appropriate", "global", "variable", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L26-L30
40,954
mairatma/babel-plugin-globals
index.js
assignToGlobal
function assignToGlobal(expr, nodes, expression) { createGlobal(expr, nodes); if (!t.isExpression(expression)) { expression = t.toExpression(expression); } nodes.push(t.expressionStatement(t.assignmentExpression('=', expr, expression))); }
javascript
function assignToGlobal(expr, nodes, expression) { createGlobal(expr, nodes); if (!t.isExpression(expression)) { expression = t.toExpression(expression); } nodes.push(t.expressionStatement(t.assignmentExpression('=', expr, expression))); }
[ "function", "assignToGlobal", "(", "expr", ",", "nodes", ",", "expression", ")", "{", "createGlobal", "(", "expr", ",", "nodes", ")", ";", "if", "(", "!", "t", ".", "isExpression", "(", "expression", ")", ")", "{", "expression", "=", "t", ".", "toExpression", "(", "expression", ")", ";", "}", "nodes", ".", "push", "(", "t", ".", "expressionStatement", "(", "t", ".", "assignmentExpression", "(", "'='", ",", "expr", ",", "expression", ")", ")", ")", ";", "}" ]
Assigns the given expression to a global with the given id. @param {!MemberExpression} expr @param {!Array} nodes @param {!Expression} expression
[ "Assigns", "the", "given", "expression", "to", "a", "global", "with", "the", "given", "id", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L38-L44
40,955
mairatma/babel-plugin-globals
index.js
createGlobal
function createGlobal(expr, nodes, opt_namedPartial) { var exprs = []; while (t.isMemberExpression(expr)) { exprs.push(expr); expr = expr.object; } var currGlobalName = ''; for (var i = exprs.length - 2; opt_namedPartial ? i >= 0 : i > 0; i--) { currGlobalName += '.' + exprs[i].property.value; if (!createdGlobals[currGlobalName]) { createdGlobals[currGlobalName] = true; nodes.push(t.expressionStatement( t.assignmentExpression('=', exprs[i], t.logicalExpression( '||', exprs[i], t.objectExpression([]) )) )); } } }
javascript
function createGlobal(expr, nodes, opt_namedPartial) { var exprs = []; while (t.isMemberExpression(expr)) { exprs.push(expr); expr = expr.object; } var currGlobalName = ''; for (var i = exprs.length - 2; opt_namedPartial ? i >= 0 : i > 0; i--) { currGlobalName += '.' + exprs[i].property.value; if (!createdGlobals[currGlobalName]) { createdGlobals[currGlobalName] = true; nodes.push(t.expressionStatement( t.assignmentExpression('=', exprs[i], t.logicalExpression( '||', exprs[i], t.objectExpression([]) )) )); } } }
[ "function", "createGlobal", "(", "expr", ",", "nodes", ",", "opt_namedPartial", ")", "{", "var", "exprs", "=", "[", "]", ";", "while", "(", "t", ".", "isMemberExpression", "(", "expr", ")", ")", "{", "exprs", ".", "push", "(", "expr", ")", ";", "expr", "=", "expr", ".", "object", ";", "}", "var", "currGlobalName", "=", "''", ";", "for", "(", "var", "i", "=", "exprs", ".", "length", "-", "2", ";", "opt_namedPartial", "?", "i", ">=", "0", ":", "i", ">", "0", ";", "i", "--", ")", "{", "currGlobalName", "+=", "'.'", "+", "exprs", "[", "i", "]", ".", "property", ".", "value", ";", "if", "(", "!", "createdGlobals", "[", "currGlobalName", "]", ")", "{", "createdGlobals", "[", "currGlobalName", "]", "=", "true", ";", "nodes", ".", "push", "(", "t", ".", "expressionStatement", "(", "t", ".", "assignmentExpression", "(", "'='", ",", "exprs", "[", "i", "]", ",", "t", ".", "logicalExpression", "(", "'||'", ",", "exprs", "[", "i", "]", ",", "t", ".", "objectExpression", "(", "[", "]", ")", ")", ")", ")", ")", ";", "}", "}", "}" ]
Creates the global for the given name, if it hasn't been created yet. @param {!MemberExpression} expr @param {!Array} nodes Array to add the global creation assignments to.
[ "Creates", "the", "global", "for", "the", "given", "name", "if", "it", "hasn", "t", "been", "created", "yet", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L51-L72
40,956
mairatma/babel-plugin-globals
index.js
getGlobalExpression
function getGlobalExpression(state, filePath, name, opt_isWildcard) { assertFilenameRequired(state.file.opts.filename); var globalName = state.opts.globalName; var id; if (typeof globalName === 'function') { id = globalName(state, filePath, name, opt_isWildcard); } else { if (name || opt_isWildcard) { globalName += 'Named'; } filePath = path.resolve(path.dirname(state.file.opts.filename), filePath); var splitPath = filePath.split(path.sep); var moduleName = splitPath[splitPath.length - 1]; id = 'this.' + globalName + '.' + moduleName + (name && name !== true ? '.' + name : ''); } var parts = id.split('.'); var expr = t.identifier(parts[0]); for (var i = 1; i < parts.length; i++) { expr = t.memberExpression(expr, t.stringLiteral(parts[i]), true); } return expr; }
javascript
function getGlobalExpression(state, filePath, name, opt_isWildcard) { assertFilenameRequired(state.file.opts.filename); var globalName = state.opts.globalName; var id; if (typeof globalName === 'function') { id = globalName(state, filePath, name, opt_isWildcard); } else { if (name || opt_isWildcard) { globalName += 'Named'; } filePath = path.resolve(path.dirname(state.file.opts.filename), filePath); var splitPath = filePath.split(path.sep); var moduleName = splitPath[splitPath.length - 1]; id = 'this.' + globalName + '.' + moduleName + (name && name !== true ? '.' + name : ''); } var parts = id.split('.'); var expr = t.identifier(parts[0]); for (var i = 1; i < parts.length; i++) { expr = t.memberExpression(expr, t.stringLiteral(parts[i]), true); } return expr; }
[ "function", "getGlobalExpression", "(", "state", ",", "filePath", ",", "name", ",", "opt_isWildcard", ")", "{", "assertFilenameRequired", "(", "state", ".", "file", ".", "opts", ".", "filename", ")", ";", "var", "globalName", "=", "state", ".", "opts", ".", "globalName", ";", "var", "id", ";", "if", "(", "typeof", "globalName", "===", "'function'", ")", "{", "id", "=", "globalName", "(", "state", ",", "filePath", ",", "name", ",", "opt_isWildcard", ")", ";", "}", "else", "{", "if", "(", "name", "||", "opt_isWildcard", ")", "{", "globalName", "+=", "'Named'", ";", "}", "filePath", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "state", ".", "file", ".", "opts", ".", "filename", ")", ",", "filePath", ")", ";", "var", "splitPath", "=", "filePath", ".", "split", "(", "path", ".", "sep", ")", ";", "var", "moduleName", "=", "splitPath", "[", "splitPath", ".", "length", "-", "1", "]", ";", "id", "=", "'this.'", "+", "globalName", "+", "'.'", "+", "moduleName", "+", "(", "name", "&&", "name", "!==", "true", "?", "'.'", "+", "name", ":", "''", ")", ";", "}", "var", "parts", "=", "id", ".", "split", "(", "'.'", ")", ";", "var", "expr", "=", "t", ".", "identifier", "(", "parts", "[", "0", "]", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "expr", "=", "t", ".", "memberExpression", "(", "expr", ",", "t", ".", "stringLiteral", "(", "parts", "[", "i", "]", ")", ",", "true", ")", ";", "}", "return", "expr", ";", "}" ]
Gets the global identifier for the given information. @param {!Object} state This plugin's current state object. @param {string} filePath The path of the module. @param {?string} name The name of the variable being imported or exported from the module. @param {boolean=} opt_isWildcard If the import or export declaration is using a wildcard. @return {!MemberExpression}
[ "Gets", "the", "global", "identifier", "for", "the", "given", "information", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L96-L121
40,957
mairatma/babel-plugin-globals
index.js
removeExtensions
function removeExtensions(filename) { var extension = path.extname(filename); while (extension !== '') { filename = path.basename(filename, extension); extension = path.extname(filename); } return filename; }
javascript
function removeExtensions(filename) { var extension = path.extname(filename); while (extension !== '') { filename = path.basename(filename, extension); extension = path.extname(filename); } return filename; }
[ "function", "removeExtensions", "(", "filename", ")", "{", "var", "extension", "=", "path", ".", "extname", "(", "filename", ")", ";", "while", "(", "extension", "!==", "''", ")", "{", "filename", "=", "path", ".", "basename", "(", "filename", ",", "extension", ")", ";", "extension", "=", "path", ".", "extname", "(", "filename", ")", ";", "}", "return", "filename", ";", "}" ]
Removes all extensions from the given filename. @param {string} filename @return {string}
[ "Removes", "all", "extensions", "from", "the", "given", "filename", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L128-L135
40,958
mairatma/babel-plugin-globals
index.js
function(nodePath) { createdGlobals = {}; filenameNoExtCache = null; var node = nodePath.node; var contents = node.body; node.body = [t.expressionStatement(t.callExpression( t.memberExpression( t.functionExpression(null, [], t.blockStatement(contents)), t.identifier('call'), false ), [t.identifier('this')] ))]; }
javascript
function(nodePath) { createdGlobals = {}; filenameNoExtCache = null; var node = nodePath.node; var contents = node.body; node.body = [t.expressionStatement(t.callExpression( t.memberExpression( t.functionExpression(null, [], t.blockStatement(contents)), t.identifier('call'), false ), [t.identifier('this')] ))]; }
[ "function", "(", "nodePath", ")", "{", "createdGlobals", "=", "{", "}", ";", "filenameNoExtCache", "=", "null", ";", "var", "node", "=", "nodePath", ".", "node", ";", "var", "contents", "=", "node", ".", "body", ";", "node", ".", "body", "=", "[", "t", ".", "expressionStatement", "(", "t", ".", "callExpression", "(", "t", ".", "memberExpression", "(", "t", ".", "functionExpression", "(", "null", ",", "[", "]", ",", "t", ".", "blockStatement", "(", "contents", ")", ")", ",", "t", ".", "identifier", "(", "'call'", ")", ",", "false", ")", ",", "[", "t", ".", "identifier", "(", "'this'", ")", "]", ")", ")", "]", ";", "}" ]
Wraps the program body in a closure, protecting local variables. @param {!NodePath} nodePath
[ "Wraps", "the", "program", "body", "in", "a", "closure", "protecting", "local", "variables", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L143-L157
40,959
mairatma/babel-plugin-globals
index.js
function(nodePath, state) { var replacements = []; if ( nodePath.node.source.value.match(/^[\./]/) ) { nodePath.node.specifiers.forEach(function(specifier) { var expr = getGlobalExpression( state, removeExtensions(nodePath.node.source.value), specifier.imported ? specifier.imported.name : null, t.isImportNamespaceSpecifier(specifier) ); replacements.push(t.variableDeclaration('var', [ t.variableDeclarator(specifier.local, expr) ])); }); } nodePath.replaceWithMultiple(replacements); }
javascript
function(nodePath, state) { var replacements = []; if ( nodePath.node.source.value.match(/^[\./]/) ) { nodePath.node.specifiers.forEach(function(specifier) { var expr = getGlobalExpression( state, removeExtensions(nodePath.node.source.value), specifier.imported ? specifier.imported.name : null, t.isImportNamespaceSpecifier(specifier) ); replacements.push(t.variableDeclaration('var', [ t.variableDeclarator(specifier.local, expr) ])); }); } nodePath.replaceWithMultiple(replacements); }
[ "function", "(", "nodePath", ",", "state", ")", "{", "var", "replacements", "=", "[", "]", ";", "if", "(", "nodePath", ".", "node", ".", "source", ".", "value", ".", "match", "(", "/", "^[\\./]", "/", ")", ")", "{", "nodePath", ".", "node", ".", "specifiers", ".", "forEach", "(", "function", "(", "specifier", ")", "{", "var", "expr", "=", "getGlobalExpression", "(", "state", ",", "removeExtensions", "(", "nodePath", ".", "node", ".", "source", ".", "value", ")", ",", "specifier", ".", "imported", "?", "specifier", ".", "imported", ".", "name", ":", "null", ",", "t", ".", "isImportNamespaceSpecifier", "(", "specifier", ")", ")", ";", "replacements", ".", "push", "(", "t", ".", "variableDeclaration", "(", "'var'", ",", "[", "t", ".", "variableDeclarator", "(", "specifier", ".", "local", ",", "expr", ")", "]", ")", ")", ";", "}", ")", ";", "}", "nodePath", ".", "replaceWithMultiple", "(", "replacements", ")", ";", "}" ]
Replaces import declarations with assignments from global to local variables. @param {!NodePath} nodePath @param {!Object} state
[ "Replaces", "import", "declarations", "with", "assignments", "from", "global", "to", "local", "variables", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L164-L181
40,960
mairatma/babel-plugin-globals
index.js
function(nodePath, state) { var replacements = []; var expr = getGlobalExpression(state, getFilenameNoExt(state.file.opts.filename)); var expression = nodePath.node.declaration; if (expression.id && (t.isFunctionDeclaration(expression) || t.isClassDeclaration(expression))) { replacements.push(expression); expression = expression.id; } assignToGlobal(expr, replacements, expression); nodePath.replaceWithMultiple(replacements); }
javascript
function(nodePath, state) { var replacements = []; var expr = getGlobalExpression(state, getFilenameNoExt(state.file.opts.filename)); var expression = nodePath.node.declaration; if (expression.id && (t.isFunctionDeclaration(expression) || t.isClassDeclaration(expression))) { replacements.push(expression); expression = expression.id; } assignToGlobal(expr, replacements, expression); nodePath.replaceWithMultiple(replacements); }
[ "function", "(", "nodePath", ",", "state", ")", "{", "var", "replacements", "=", "[", "]", ";", "var", "expr", "=", "getGlobalExpression", "(", "state", ",", "getFilenameNoExt", "(", "state", ".", "file", ".", "opts", ".", "filename", ")", ")", ";", "var", "expression", "=", "nodePath", ".", "node", ".", "declaration", ";", "if", "(", "expression", ".", "id", "&&", "(", "t", ".", "isFunctionDeclaration", "(", "expression", ")", "||", "t", ".", "isClassDeclaration", "(", "expression", ")", ")", ")", "{", "replacements", ".", "push", "(", "expression", ")", ";", "expression", "=", "expression", ".", "id", ";", "}", "assignToGlobal", "(", "expr", ",", "replacements", ",", "expression", ")", ";", "nodePath", ".", "replaceWithMultiple", "(", "replacements", ")", ";", "}" ]
Replaces default export declarations with assignments to global variables. @param {!NodePath} nodePath @param {!Object} state
[ "Replaces", "default", "export", "declarations", "with", "assignments", "to", "global", "variables", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L225-L236
40,961
mairatma/babel-plugin-globals
index.js
function(nodePath, state) { var replacements = []; var node = nodePath.node; if (node.declaration) { replacements.push(node.declaration); if (t.isVariableDeclaration(node.declaration)) { node.declaration.declarations.forEach(assignDeclarationToGlobal.bind(null, state, replacements)); } else { assignDeclarationToGlobal(state, replacements, node.declaration); } } else { node.specifiers.forEach(function(specifier) { var exprToAssign = specifier.local; if (node.source) { var specifierName = specifier.local ? specifier.local.name : null; exprToAssign = getGlobalExpression(state, node.source.value, specifierName); } var filenameNoExt = getFilenameNoExt(state.file.opts.filename); var expr = getGlobalExpression(state, filenameNoExt, specifier.exported.name); assignToGlobal(expr, replacements, exprToAssign); }); } nodePath.replaceWithMultiple(replacements); }
javascript
function(nodePath, state) { var replacements = []; var node = nodePath.node; if (node.declaration) { replacements.push(node.declaration); if (t.isVariableDeclaration(node.declaration)) { node.declaration.declarations.forEach(assignDeclarationToGlobal.bind(null, state, replacements)); } else { assignDeclarationToGlobal(state, replacements, node.declaration); } } else { node.specifiers.forEach(function(specifier) { var exprToAssign = specifier.local; if (node.source) { var specifierName = specifier.local ? specifier.local.name : null; exprToAssign = getGlobalExpression(state, node.source.value, specifierName); } var filenameNoExt = getFilenameNoExt(state.file.opts.filename); var expr = getGlobalExpression(state, filenameNoExt, specifier.exported.name); assignToGlobal(expr, replacements, exprToAssign); }); } nodePath.replaceWithMultiple(replacements); }
[ "function", "(", "nodePath", ",", "state", ")", "{", "var", "replacements", "=", "[", "]", ";", "var", "node", "=", "nodePath", ".", "node", ";", "if", "(", "node", ".", "declaration", ")", "{", "replacements", ".", "push", "(", "node", ".", "declaration", ")", ";", "if", "(", "t", ".", "isVariableDeclaration", "(", "node", ".", "declaration", ")", ")", "{", "node", ".", "declaration", ".", "declarations", ".", "forEach", "(", "assignDeclarationToGlobal", ".", "bind", "(", "null", ",", "state", ",", "replacements", ")", ")", ";", "}", "else", "{", "assignDeclarationToGlobal", "(", "state", ",", "replacements", ",", "node", ".", "declaration", ")", ";", "}", "}", "else", "{", "node", ".", "specifiers", ".", "forEach", "(", "function", "(", "specifier", ")", "{", "var", "exprToAssign", "=", "specifier", ".", "local", ";", "if", "(", "node", ".", "source", ")", "{", "var", "specifierName", "=", "specifier", ".", "local", "?", "specifier", ".", "local", ".", "name", ":", "null", ";", "exprToAssign", "=", "getGlobalExpression", "(", "state", ",", "node", ".", "source", ".", "value", ",", "specifierName", ")", ";", "}", "var", "filenameNoExt", "=", "getFilenameNoExt", "(", "state", ".", "file", ".", "opts", ".", "filename", ")", ";", "var", "expr", "=", "getGlobalExpression", "(", "state", ",", "filenameNoExt", ",", "specifier", ".", "exported", ".", "name", ")", ";", "assignToGlobal", "(", "expr", ",", "replacements", ",", "exprToAssign", ")", ";", "}", ")", ";", "}", "nodePath", ".", "replaceWithMultiple", "(", "replacements", ")", ";", "}" ]
Replaces named export declarations with assignments to global variables. @param {!NodePath} nodePath @param {!Object} state
[ "Replaces", "named", "export", "declarations", "with", "assignments", "to", "global", "variables", "." ]
37499200e1c34a2bf86add2910cc31dd66f2a8a7
https://github.com/mairatma/babel-plugin-globals/blob/37499200e1c34a2bf86add2910cc31dd66f2a8a7/index.js#L243-L268
40,962
ivnivnch/angular-parse
src/Parse.js
defineAttributes
function defineAttributes(object, attributes) { if (object instanceof Parse.Object) { if (!(attributes instanceof Array)) attributes = Array.prototype.slice.call(arguments, 1); attributes.forEach(function (attribute) { Object.defineProperty(object, attribute, { get: function () { return this.get(attribute); }, set: function (value) { this.set(attribute, value); }, configurable: true, enumerable: true }); }); } else if (typeof object == 'function') { return defineAttributes(object.prototype, attributes) } else { if (object instanceof Array) attributes = object; else attributes = Array.prototype.slice.call(arguments, 0); return function defineAttributesDecorator(target) { defineAttributes(target, attributes); } } }
javascript
function defineAttributes(object, attributes) { if (object instanceof Parse.Object) { if (!(attributes instanceof Array)) attributes = Array.prototype.slice.call(arguments, 1); attributes.forEach(function (attribute) { Object.defineProperty(object, attribute, { get: function () { return this.get(attribute); }, set: function (value) { this.set(attribute, value); }, configurable: true, enumerable: true }); }); } else if (typeof object == 'function') { return defineAttributes(object.prototype, attributes) } else { if (object instanceof Array) attributes = object; else attributes = Array.prototype.slice.call(arguments, 0); return function defineAttributesDecorator(target) { defineAttributes(target, attributes); } } }
[ "function", "defineAttributes", "(", "object", ",", "attributes", ")", "{", "if", "(", "object", "instanceof", "Parse", ".", "Object", ")", "{", "if", "(", "!", "(", "attributes", "instanceof", "Array", ")", ")", "attributes", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "attributes", ".", "forEach", "(", "function", "(", "attribute", ")", "{", "Object", ".", "defineProperty", "(", "object", ",", "attribute", ",", "{", "get", ":", "function", "(", ")", "{", "return", "this", ".", "get", "(", "attribute", ")", ";", "}", ",", "set", ":", "function", "(", "value", ")", "{", "this", ".", "set", "(", "attribute", ",", "value", ")", ";", "}", ",", "configurable", ":", "true", ",", "enumerable", ":", "true", "}", ")", ";", "}", ")", ";", "}", "else", "if", "(", "typeof", "object", "==", "'function'", ")", "{", "return", "defineAttributes", "(", "object", ".", "prototype", ",", "attributes", ")", "}", "else", "{", "if", "(", "object", "instanceof", "Array", ")", "attributes", "=", "object", ";", "else", "attributes", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "return", "function", "defineAttributesDecorator", "(", "target", ")", "{", "defineAttributes", "(", "target", ",", "attributes", ")", ";", "}", "}", "}" ]
Defines getters and setters for the attributes of the given object or function prototype. Or create a decorator that defines getters and setters for the subclass Parse.Object. @param {Object|Function|String|String[]} object @param {...String|String[]=} attributes @returns {*}
[ "Defines", "getters", "and", "setters", "for", "the", "attributes", "of", "the", "given", "object", "or", "function", "prototype", ".", "Or", "create", "a", "decorator", "that", "defines", "getters", "and", "setters", "for", "the", "subclass", "Parse", ".", "Object", "." ]
27a8cbe1d348c168a898f05a53cd69f6dad67671
https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L23-L47
40,963
ivnivnch/angular-parse
src/Parse.js
wrapParsePromise
function wrapParsePromise(promise, parsePromise) { ['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve'] .forEach(function (prop) { promise[prop] = parsePromise[prop]; }); ['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) { promise[method] = wrap(parsePromise[method]); }); ['then', 'catch'].forEach(function (method) { var func = promise[method]; promise[method] = function wrappedAngularPromise() { var args = Array.prototype.slice.call(arguments, 0); var promise = func.apply(this, args); wrapParsePromise(promise, parsePromise); return promise; }; }); return promise; }
javascript
function wrapParsePromise(promise, parsePromise) { ['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve'] .forEach(function (prop) { promise[prop] = parsePromise[prop]; }); ['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) { promise[method] = wrap(parsePromise[method]); }); ['then', 'catch'].forEach(function (method) { var func = promise[method]; promise[method] = function wrappedAngularPromise() { var args = Array.prototype.slice.call(arguments, 0); var promise = func.apply(this, args); wrapParsePromise(promise, parsePromise); return promise; }; }); return promise; }
[ "function", "wrapParsePromise", "(", "promise", ",", "parsePromise", ")", "{", "[", "'_rejected'", ",", "'_rejectedCallbacks'", ",", "'_resolved'", ",", "'_resolvedCallbacks'", ",", "'_result'", ",", "'reject'", ",", "'resolve'", "]", ".", "forEach", "(", "function", "(", "prop", ")", "{", "promise", "[", "prop", "]", "=", "parsePromise", "[", "prop", "]", ";", "}", ")", ";", "[", "'_continueWith'", ",", "'_thenRunCallbacks'", ",", "'always'", ",", "'done'", ",", "'fail'", "]", ".", "forEach", "(", "function", "(", "method", ")", "{", "promise", "[", "method", "]", "=", "wrap", "(", "parsePromise", "[", "method", "]", ")", ";", "}", ")", ";", "[", "'then'", ",", "'catch'", "]", ".", "forEach", "(", "function", "(", "method", ")", "{", "var", "func", "=", "promise", "[", "method", "]", ";", "promise", "[", "method", "]", "=", "function", "wrappedAngularPromise", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "promise", "=", "func", ".", "apply", "(", "this", ",", "args", ")", ";", "wrapParsePromise", "(", "promise", ",", "parsePromise", ")", ";", "return", "promise", ";", "}", ";", "}", ")", ";", "return", "promise", ";", "}" ]
Wraps Promise. @param {Object} promise @param {Object} parsePromise @returns {Object}
[ "Wraps", "Promise", "." ]
27a8cbe1d348c168a898f05a53cd69f6dad67671
https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L85-L106
40,964
ivnivnch/angular-parse
src/Parse.js
wrap
function wrap(func) { return function wrappedParsePromise() { var args = Array.prototype.slice.call(arguments, 0); var parsePromise = func.apply(this, args); var promise = $q(parsePromise.then.bind(parsePromise)); wrapParsePromise(promise, parsePromise); return promise; }; }
javascript
function wrap(func) { return function wrappedParsePromise() { var args = Array.prototype.slice.call(arguments, 0); var parsePromise = func.apply(this, args); var promise = $q(parsePromise.then.bind(parsePromise)); wrapParsePromise(promise, parsePromise); return promise; }; }
[ "function", "wrap", "(", "func", ")", "{", "return", "function", "wrappedParsePromise", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "parsePromise", "=", "func", ".", "apply", "(", "this", ",", "args", ")", ";", "var", "promise", "=", "$q", "(", "parsePromise", ".", "then", ".", "bind", "(", "parsePromise", ")", ")", ";", "wrapParsePromise", "(", "promise", ",", "parsePromise", ")", ";", "return", "promise", ";", "}", ";", "}" ]
Wraps function. @param {Function} func Function that returns [Parse.Promise]{@link https://parse.com/docs/js/api/classes/Parse.Promise.html}. @returns {Function} Function that returns $q promises.
[ "Wraps", "function", "." ]
27a8cbe1d348c168a898f05a53cd69f6dad67671
https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L115-L123
40,965
ivnivnch/angular-parse
src/Parse.js
wrapObject
function wrapObject(object, methods) { if (!(methods instanceof Array)) methods = Array.prototype.slice.call(arguments, 1); methods.forEach(function (method) { object[method] = wrap(object[method]); }); }
javascript
function wrapObject(object, methods) { if (!(methods instanceof Array)) methods = Array.prototype.slice.call(arguments, 1); methods.forEach(function (method) { object[method] = wrap(object[method]); }); }
[ "function", "wrapObject", "(", "object", ",", "methods", ")", "{", "if", "(", "!", "(", "methods", "instanceof", "Array", ")", ")", "methods", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "methods", ".", "forEach", "(", "function", "(", "method", ")", "{", "object", "[", "method", "]", "=", "wrap", "(", "object", "[", "method", "]", ")", ";", "}", ")", ";", "}" ]
Wraps object. @param {Object} object @param {...String|String[]=} methods
[ "Wraps", "object", "." ]
27a8cbe1d348c168a898f05a53cd69f6dad67671
https://github.com/ivnivnch/angular-parse/blob/27a8cbe1d348c168a898f05a53cd69f6dad67671/src/Parse.js#L131-L136
40,966
emmetio/abbreviation
lib/attribute.js
eatUnquoted
function eatUnquoted(stream) { const start = stream.pos; if (stream.eatWhile(isUnquoted)) { stream.start = start; return true; } }
javascript
function eatUnquoted(stream) { const start = stream.pos; if (stream.eatWhile(isUnquoted)) { stream.start = start; return true; } }
[ "function", "eatUnquoted", "(", "stream", ")", "{", "const", "start", "=", "stream", ".", "pos", ";", "if", "(", "stream", ".", "eatWhile", "(", "isUnquoted", ")", ")", "{", "stream", ".", "start", "=", "start", ";", "return", "true", ";", "}", "}" ]
Eats token that can be an unquoted value from given stream @param {StreamReader} stream @return {Boolean}
[ "Eats", "token", "that", "can", "be", "an", "unquoted", "value", "from", "given", "stream" ]
9b1dde05eedccb7d824bd6d67d06921dfab524cd
https://github.com/emmetio/abbreviation/blob/9b1dde05eedccb7d824bd6d67d06921dfab524cd/lib/attribute.js#L112-L118
40,967
fzaninotto/cron-as-a-service
app/web/public/javascripts/jquery.form.js
doSubmit
function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { extraInputs.push( $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n]) .appendTo(form)[0]); } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } }
javascript
function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { extraInputs.push( $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n]) .appendTo(form)[0]); } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } }
[ "function", "doSubmit", "(", ")", "{", "// make sure form attrs are set", "var", "t", "=", "$form", ".", "attr", "(", "'target'", ")", ",", "a", "=", "$form", ".", "attr", "(", "'action'", ")", ";", "// update form attrs in IE friendly way", "form", ".", "setAttribute", "(", "'target'", ",", "id", ")", ";", "if", "(", "!", "method", ")", "{", "form", ".", "setAttribute", "(", "'method'", ",", "'POST'", ")", ";", "}", "if", "(", "a", "!=", "s", ".", "url", ")", "{", "form", ".", "setAttribute", "(", "'action'", ",", "s", ".", "url", ")", ";", "}", "// ie borks in some cases when setting encoding", "if", "(", "!", "s", ".", "skipEncodingOverride", "&&", "(", "!", "method", "||", "/", "post", "/", "i", ".", "test", "(", "method", ")", ")", ")", "{", "$form", ".", "attr", "(", "{", "encoding", ":", "'multipart/form-data'", ",", "enctype", ":", "'multipart/form-data'", "}", ")", ";", "}", "// support timout", "if", "(", "s", ".", "timeout", ")", "{", "timeoutHandle", "=", "setTimeout", "(", "function", "(", ")", "{", "timedOut", "=", "true", ";", "cb", "(", "CLIENT_TIMEOUT_ABORT", ")", ";", "}", ",", "s", ".", "timeout", ")", ";", "}", "// look for server aborts", "function", "checkState", "(", ")", "{", "try", "{", "var", "state", "=", "getDoc", "(", "io", ")", ".", "readyState", ";", "log", "(", "'state = '", "+", "state", ")", ";", "if", "(", "state", "&&", "state", ".", "toLowerCase", "(", ")", "==", "'uninitialized'", ")", "setTimeout", "(", "checkState", ",", "50", ")", ";", "}", "catch", "(", "e", ")", "{", "log", "(", "'Server abort: '", ",", "e", ",", "' ('", ",", "e", ".", "name", ",", "')'", ")", ";", "cb", "(", "SERVER_ABORT", ")", ";", "if", "(", "timeoutHandle", ")", "clearTimeout", "(", "timeoutHandle", ")", ";", "timeoutHandle", "=", "undefined", ";", "}", "}", "// add \"extra\" data to form if provided in options", "var", "extraInputs", "=", "[", "]", ";", "try", "{", "if", "(", "s", ".", "extraData", ")", "{", "for", "(", "var", "n", "in", "s", ".", "extraData", ")", "{", "if", "(", "s", ".", "extraData", ".", "hasOwnProperty", "(", "n", ")", ")", "{", "extraInputs", ".", "push", "(", "$", "(", "'<input type=\"hidden\" name=\"'", "+", "n", "+", "'\">'", ")", ".", "attr", "(", "'value'", ",", "s", ".", "extraData", "[", "n", "]", ")", ".", "appendTo", "(", "form", ")", "[", "0", "]", ")", ";", "}", "}", "}", "if", "(", "!", "s", ".", "iframeTarget", ")", "{", "// add iframe to doc and submit the form", "$io", ".", "appendTo", "(", "'body'", ")", ";", "if", "(", "io", ".", "attachEvent", ")", "io", ".", "attachEvent", "(", "'onload'", ",", "cb", ")", ";", "else", "io", ".", "addEventListener", "(", "'load'", ",", "cb", ",", "false", ")", ";", "}", "setTimeout", "(", "checkState", ",", "15", ")", ";", "form", ".", "submit", "(", ")", ";", "}", "finally", "{", "// reset attrs and remove \"extra\" input elements", "form", ".", "setAttribute", "(", "'action'", ",", "a", ")", ";", "if", "(", "t", ")", "{", "form", ".", "setAttribute", "(", "'target'", ",", "t", ")", ";", "}", "else", "{", "$form", ".", "removeAttr", "(", "'target'", ")", ";", "}", "$", "(", "extraInputs", ")", ".", "remove", "(", ")", ";", "}", "}" ]
take a breath so that pending repaints get some cpu time before the upload starts
[ "take", "a", "breath", "so", "that", "pending", "repaints", "get", "some", "cpu", "time", "before", "the", "upload", "starts" ]
35334898730d44c96c1f7b4c235295c48fb992ab
https://github.com/fzaninotto/cron-as-a-service/blob/35334898730d44c96c1f7b4c235295c48fb992ab/app/web/public/javascripts/jquery.form.js#L380-L457
40,968
fzaninotto/cron-as-a-service
app/web/public/javascripts/jquery.form.js
checkState
function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } }
javascript
function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } }
[ "function", "checkState", "(", ")", "{", "try", "{", "var", "state", "=", "getDoc", "(", "io", ")", ".", "readyState", ";", "log", "(", "'state = '", "+", "state", ")", ";", "if", "(", "state", "&&", "state", ".", "toLowerCase", "(", ")", "==", "'uninitialized'", ")", "setTimeout", "(", "checkState", ",", "50", ")", ";", "}", "catch", "(", "e", ")", "{", "log", "(", "'Server abort: '", ",", "e", ",", "' ('", ",", "e", ".", "name", ",", "')'", ")", ";", "cb", "(", "SERVER_ABORT", ")", ";", "if", "(", "timeoutHandle", ")", "clearTimeout", "(", "timeoutHandle", ")", ";", "timeoutHandle", "=", "undefined", ";", "}", "}" ]
look for server aborts
[ "look", "for", "server", "aborts" ]
35334898730d44c96c1f7b4c235295c48fb992ab
https://github.com/fzaninotto/cron-as-a-service/blob/35334898730d44c96c1f7b4c235295c48fb992ab/app/web/public/javascripts/jquery.form.js#L407-L421
40,969
fzaninotto/cron-as-a-service
app/web/public/javascripts/jquery.form.js
doAjaxSubmit
function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }
javascript
function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }
[ "function", "doAjaxSubmit", "(", "e", ")", "{", "/*jshint validthis:true */", "var", "options", "=", "e", ".", "data", ";", "if", "(", "!", "e", ".", "isDefaultPrevented", "(", ")", ")", "{", "// if event has been canceled, don't proceed", "e", ".", "preventDefault", "(", ")", ";", "$", "(", "this", ")", ".", "ajaxSubmit", "(", "options", ")", ";", "}", "}" ]
private event handlers
[ "private", "event", "handlers" ]
35334898730d44c96c1f7b4c235295c48fb992ab
https://github.com/fzaninotto/cron-as-a-service/blob/35334898730d44c96c1f7b4c235295c48fb992ab/app/web/public/javascripts/jquery.form.js#L713-L720
40,970
daleeidd/postcss-define-property
index.js
function (properties, rule, options) { var signature = rule.selector || rule.params; var name = signature.match(customPropertyPattern).shift().replace(propertyKeyDelimiter, '').trim(); var parameters = signature.replace(customPropertyPattern, '').match(parametersPattern).map(function (parameter) { return parameter.replace(options.syntax.parameter, options.syntax.variable); }); var property = { name: name, parameters: parameters, declarations: rule.nodes.map(function (node) { return { property: node.prop, value: node.value, // Parses variables that are also parameters. Ignores other variables for compatability with Sass variables. // We only need the index of each parameter variables: (node.value.match(variablesPattern) || []) .filter(function (variable) { return node.value.indexOf(variable) !== -1; }).map(function (variable) { return parameters.indexOf(variable); }) }; }) }; properties[options.syntax.property + property.name + signatureSeparator + parameters.length] = property; rule.remove(); }
javascript
function (properties, rule, options) { var signature = rule.selector || rule.params; var name = signature.match(customPropertyPattern).shift().replace(propertyKeyDelimiter, '').trim(); var parameters = signature.replace(customPropertyPattern, '').match(parametersPattern).map(function (parameter) { return parameter.replace(options.syntax.parameter, options.syntax.variable); }); var property = { name: name, parameters: parameters, declarations: rule.nodes.map(function (node) { return { property: node.prop, value: node.value, // Parses variables that are also parameters. Ignores other variables for compatability with Sass variables. // We only need the index of each parameter variables: (node.value.match(variablesPattern) || []) .filter(function (variable) { return node.value.indexOf(variable) !== -1; }).map(function (variable) { return parameters.indexOf(variable); }) }; }) }; properties[options.syntax.property + property.name + signatureSeparator + parameters.length] = property; rule.remove(); }
[ "function", "(", "properties", ",", "rule", ",", "options", ")", "{", "var", "signature", "=", "rule", ".", "selector", "||", "rule", ".", "params", ";", "var", "name", "=", "signature", ".", "match", "(", "customPropertyPattern", ")", ".", "shift", "(", ")", ".", "replace", "(", "propertyKeyDelimiter", ",", "''", ")", ".", "trim", "(", ")", ";", "var", "parameters", "=", "signature", ".", "replace", "(", "customPropertyPattern", ",", "''", ")", ".", "match", "(", "parametersPattern", ")", ".", "map", "(", "function", "(", "parameter", ")", "{", "return", "parameter", ".", "replace", "(", "options", ".", "syntax", ".", "parameter", ",", "options", ".", "syntax", ".", "variable", ")", ";", "}", ")", ";", "var", "property", "=", "{", "name", ":", "name", ",", "parameters", ":", "parameters", ",", "declarations", ":", "rule", ".", "nodes", ".", "map", "(", "function", "(", "node", ")", "{", "return", "{", "property", ":", "node", ".", "prop", ",", "value", ":", "node", ".", "value", ",", "// Parses variables that are also parameters. Ignores other variables for compatability with Sass variables.", "// We only need the index of each parameter", "variables", ":", "(", "node", ".", "value", ".", "match", "(", "variablesPattern", ")", "||", "[", "]", ")", ".", "filter", "(", "function", "(", "variable", ")", "{", "return", "node", ".", "value", ".", "indexOf", "(", "variable", ")", "!==", "-", "1", ";", "}", ")", ".", "map", "(", "function", "(", "variable", ")", "{", "return", "parameters", ".", "indexOf", "(", "variable", ")", ";", "}", ")", "}", ";", "}", ")", "}", ";", "properties", "[", "options", ".", "syntax", ".", "property", "+", "property", ".", "name", "+", "signatureSeparator", "+", "parameters", ".", "length", "]", "=", "property", ";", "rule", ".", "remove", "(", ")", ";", "}" ]
Adds a property definition to properties
[ "Adds", "a", "property", "definition", "to", "properties" ]
8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453
https://github.com/daleeidd/postcss-define-property/blob/8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453/index.js#L13-L41
40,971
daleeidd/postcss-define-property
index.js
function (customProperty, declaration) { customProperty.declarations.forEach(function (customDeclaration) { // No need to copy value here as replace will copy value var value = customDeclaration.value; // Replace parameter variables with user given values customDeclaration.variables.forEach(function (variable) { value = value.replace(customProperty.parameters[variable], declaration.values[variable]); }); // Using cloneBefore to insert declaration provides sourcemap support declaration.cloneBefore({ prop: customDeclaration.property, value: value }); }); declaration.remove(); }
javascript
function (customProperty, declaration) { customProperty.declarations.forEach(function (customDeclaration) { // No need to copy value here as replace will copy value var value = customDeclaration.value; // Replace parameter variables with user given values customDeclaration.variables.forEach(function (variable) { value = value.replace(customProperty.parameters[variable], declaration.values[variable]); }); // Using cloneBefore to insert declaration provides sourcemap support declaration.cloneBefore({ prop: customDeclaration.property, value: value }); }); declaration.remove(); }
[ "function", "(", "customProperty", ",", "declaration", ")", "{", "customProperty", ".", "declarations", ".", "forEach", "(", "function", "(", "customDeclaration", ")", "{", "// No need to copy value here as replace will copy value", "var", "value", "=", "customDeclaration", ".", "value", ";", "// Replace parameter variables with user given values", "customDeclaration", ".", "variables", ".", "forEach", "(", "function", "(", "variable", ")", "{", "value", "=", "value", ".", "replace", "(", "customProperty", ".", "parameters", "[", "variable", "]", ",", "declaration", ".", "values", "[", "variable", "]", ")", ";", "}", ")", ";", "// Using cloneBefore to insert declaration provides sourcemap support", "declaration", ".", "cloneBefore", "(", "{", "prop", ":", "customDeclaration", ".", "property", ",", "value", ":", "value", "}", ")", ";", "}", ")", ";", "declaration", ".", "remove", "(", ")", ";", "}" ]
Applies the custom property to the given declaration
[ "Applies", "the", "custom", "property", "to", "the", "given", "declaration" ]
8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453
https://github.com/daleeidd/postcss-define-property/blob/8dbd84ea1e86cff37d96f5539f55e5dbaaa6d453/index.js#L44-L63
40,972
samuelcarreira/electron-shutdown-command
index.js
abort
function abort(options = {}) { if (process.platform !== 'win32' && process.platform !== 'linux') { throw new Error('Unsupported OS (only Windows and Linux are supported)!'); } let cmdarguments = ['shutdown']; if (process.platform === 'win32') { cmdarguments.push('-a'); // abort } else { // linux cmdarguments.push('-c'); // cancel a pending shutdown } executeCmd(cmdarguments, options.debug, options.quitapp); }
javascript
function abort(options = {}) { if (process.platform !== 'win32' && process.platform !== 'linux') { throw new Error('Unsupported OS (only Windows and Linux are supported)!'); } let cmdarguments = ['shutdown']; if (process.platform === 'win32') { cmdarguments.push('-a'); // abort } else { // linux cmdarguments.push('-c'); // cancel a pending shutdown } executeCmd(cmdarguments, options.debug, options.quitapp); }
[ "function", "abort", "(", "options", "=", "{", "}", ")", "{", "if", "(", "process", ".", "platform", "!==", "'win32'", "&&", "process", ".", "platform", "!==", "'linux'", ")", "{", "throw", "new", "Error", "(", "'Unsupported OS (only Windows and Linux are supported)!'", ")", ";", "}", "let", "cmdarguments", "=", "[", "'shutdown'", "]", ";", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "cmdarguments", ".", "push", "(", "'-a'", ")", ";", "// abort\r", "}", "else", "{", "// linux\r", "cmdarguments", ".", "push", "(", "'-c'", ")", ";", "// cancel a pending shutdown\r", "}", "executeCmd", "(", "cmdarguments", ",", "options", ".", "debug", ",", "options", ".", "quitapp", ")", ";", "}" ]
Aborts current scheduled shutdown @param {Object} options
[ "Aborts", "current", "scheduled", "shutdown" ]
1c2dd056a1fe524cd5663eed96dc66993b11285c
https://github.com/samuelcarreira/electron-shutdown-command/blob/1c2dd056a1fe524cd5663eed96dc66993b11285c/index.js#L100-L115
40,973
samuelcarreira/electron-shutdown-command
index.js
setTimer
function setTimer(timervalue) { let cmdarguments = []; if (process.platform === 'linux' ) { if (timervalue) { cmdarguments.push(timervalue.toString()); } else { cmdarguments.push('now'); } } if (process.platform === 'darwin') { if (timervalue) { let timeinminutes = Math.round(Number(timervalue) / 60); if (timeinminutes === 0) { timeinminutes = 1; // min 1 minute } cmdarguments.push('-t ' + timeinminutes.toString()); } else { cmdarguments.push('now'); } } if (process.platform === 'win32') { if (timervalue) { cmdarguments.push('-t ' + timervalue.toString()); } else { cmdarguments.push('-t 0'); // set to 0 because default is 20 seconds } } return cmdarguments; }
javascript
function setTimer(timervalue) { let cmdarguments = []; if (process.platform === 'linux' ) { if (timervalue) { cmdarguments.push(timervalue.toString()); } else { cmdarguments.push('now'); } } if (process.platform === 'darwin') { if (timervalue) { let timeinminutes = Math.round(Number(timervalue) / 60); if (timeinminutes === 0) { timeinminutes = 1; // min 1 minute } cmdarguments.push('-t ' + timeinminutes.toString()); } else { cmdarguments.push('now'); } } if (process.platform === 'win32') { if (timervalue) { cmdarguments.push('-t ' + timervalue.toString()); } else { cmdarguments.push('-t 0'); // set to 0 because default is 20 seconds } } return cmdarguments; }
[ "function", "setTimer", "(", "timervalue", ")", "{", "let", "cmdarguments", "=", "[", "]", ";", "if", "(", "process", ".", "platform", "===", "'linux'", ")", "{", "if", "(", "timervalue", ")", "{", "cmdarguments", ".", "push", "(", "timervalue", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "cmdarguments", ".", "push", "(", "'now'", ")", ";", "}", "}", "if", "(", "process", ".", "platform", "===", "'darwin'", ")", "{", "if", "(", "timervalue", ")", "{", "let", "timeinminutes", "=", "Math", ".", "round", "(", "Number", "(", "timervalue", ")", "/", "60", ")", ";", "if", "(", "timeinminutes", "===", "0", ")", "{", "timeinminutes", "=", "1", ";", "// min 1 minute\r", "}", "cmdarguments", ".", "push", "(", "'-t '", "+", "timeinminutes", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "cmdarguments", ".", "push", "(", "'now'", ")", ";", "}", "}", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "if", "(", "timervalue", ")", "{", "cmdarguments", ".", "push", "(", "'-t '", "+", "timervalue", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "cmdarguments", ".", "push", "(", "'-t 0'", ")", ";", "// set to 0 because default is 20 seconds\r", "}", "}", "return", "cmdarguments", ";", "}" ]
set current time argument @param {Number} timervalue value in seconds to delay, false to execute now
[ "set", "current", "time", "argument" ]
1c2dd056a1fe524cd5663eed96dc66993b11285c
https://github.com/samuelcarreira/electron-shutdown-command/blob/1c2dd056a1fe524cd5663eed96dc66993b11285c/index.js#L153-L185
40,974
KoryNunn/interact
interact.js
getActualTarget
function getActualTarget() { var scrollX = window.scrollX, scrollY = window.scrollY; // IE is stupid and doesn't support scrollX/Y if(scrollX === undefined){ scrollX = d.body.scrollLeft; scrollY = d.body.scrollTop; } return d.elementFromPoint(this.pageX - window.scrollX, this.pageY - window.scrollY); }
javascript
function getActualTarget() { var scrollX = window.scrollX, scrollY = window.scrollY; // IE is stupid and doesn't support scrollX/Y if(scrollX === undefined){ scrollX = d.body.scrollLeft; scrollY = d.body.scrollTop; } return d.elementFromPoint(this.pageX - window.scrollX, this.pageY - window.scrollY); }
[ "function", "getActualTarget", "(", ")", "{", "var", "scrollX", "=", "window", ".", "scrollX", ",", "scrollY", "=", "window", ".", "scrollY", ";", "// IE is stupid and doesn't support scrollX/Y\r", "if", "(", "scrollX", "===", "undefined", ")", "{", "scrollX", "=", "d", ".", "body", ".", "scrollLeft", ";", "scrollY", "=", "d", ".", "body", ".", "scrollTop", ";", "}", "return", "d", ".", "elementFromPoint", "(", "this", ".", "pageX", "-", "window", ".", "scrollX", ",", "this", ".", "pageY", "-", "window", ".", "scrollY", ")", ";", "}" ]
For some reason touch browsers never change the event target during a touch. This is, lets face it, fucking stupid.
[ "For", "some", "reason", "touch", "browsers", "never", "change", "the", "event", "target", "during", "a", "touch", ".", "This", "is", "lets", "face", "it", "fucking", "stupid", "." ]
c11e9596359f8cea166778a261d48a747a0e3533
https://github.com/KoryNunn/interact/blob/c11e9596359f8cea166778a261d48a747a0e3533/interact.js#L74-L85
40,975
hutkev/Shared
lib/shared.js
defaultLogger
function defaultLogger() { if(!_defaultLogger) { var prefix = 'master'; if(cluster.worker) { prefix = 'work ' + cluster.worker.id; } _defaultLogger = new Logger(process.stdout, prefix, utils.LogLevel.INFO, []); } return _defaultLogger; }
javascript
function defaultLogger() { if(!_defaultLogger) { var prefix = 'master'; if(cluster.worker) { prefix = 'work ' + cluster.worker.id; } _defaultLogger = new Logger(process.stdout, prefix, utils.LogLevel.INFO, []); } return _defaultLogger; }
[ "function", "defaultLogger", "(", ")", "{", "if", "(", "!", "_defaultLogger", ")", "{", "var", "prefix", "=", "'master'", ";", "if", "(", "cluster", ".", "worker", ")", "{", "prefix", "=", "'work '", "+", "cluster", ".", "worker", ".", "id", ";", "}", "_defaultLogger", "=", "new", "Logger", "(", "process", ".", "stdout", ",", "prefix", ",", "utils", ".", "LogLevel", ".", "INFO", ",", "[", "]", ")", ";", "}", "return", "_defaultLogger", ";", "}" ]
Obtains the default logger. If one has not been set then logging is to process.stdout at the INFO level.
[ "Obtains", "the", "default", "logger", ".", "If", "one", "has", "not", "been", "set", "then", "logging", "is", "to", "process", ".", "stdout", "at", "the", "INFO", "level", "." ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L462-L471
40,976
hutkev/Shared
lib/shared.js
typeOf
function typeOf(value) { var s = typeof value; if(s === 'object') { if(value) { if(value instanceof Array) { s = 'array'; } } else { s = 'null'; } } return s; }
javascript
function typeOf(value) { var s = typeof value; if(s === 'object') { if(value) { if(value instanceof Array) { s = 'array'; } } else { s = 'null'; } } return s; }
[ "function", "typeOf", "(", "value", ")", "{", "var", "s", "=", "typeof", "value", ";", "if", "(", "s", "===", "'object'", ")", "{", "if", "(", "value", ")", "{", "if", "(", "value", "instanceof", "Array", ")", "{", "s", "=", "'array'", ";", "}", "}", "else", "{", "s", "=", "'null'", ";", "}", "}", "return", "s", ";", "}" ]
Corrected type of value. Arrays & null are not 'objects'
[ "Corrected", "type", "of", "value", ".", "Arrays", "&", "null", "are", "not", "objects" ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L568-L580
40,977
hutkev/Shared
lib/shared.js
treatAs
function treatAs(value) { var s = typeof value; if(s === 'object') { if(value) { return Object.prototype.toString.call(value).match(/^\[object\s(.*)\]$/)[1]; } else { s = 'null'; } } return s; }
javascript
function treatAs(value) { var s = typeof value; if(s === 'object') { if(value) { return Object.prototype.toString.call(value).match(/^\[object\s(.*)\]$/)[1]; } else { s = 'null'; } } return s; }
[ "function", "treatAs", "(", "value", ")", "{", "var", "s", "=", "typeof", "value", ";", "if", "(", "s", "===", "'object'", ")", "{", "if", "(", "value", ")", "{", "return", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ".", "match", "(", "/", "^\\[object\\s(.*)\\]$", "/", ")", "[", "1", "]", ";", "}", "else", "{", "s", "=", "'null'", ";", "}", "}", "return", "s", ";", "}" ]
Corrected type of value. Arrays & null are not 'objects' Objects return their prototype type.
[ "Corrected", "type", "of", "value", ".", "Arrays", "&", "null", "are", "not", "objects", "Objects", "return", "their", "prototype", "type", "." ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L587-L597
40,978
hutkev/Shared
lib/shared.js
toInteger
function toInteger(val) { var v = +val;// toNumber conversion if(isNaN(v)) { return 0; } if(v === 0 || v === Infinity || v == -Infinity) { return v; } if(v < 0) { return -1 * Math.floor(-v); } else { return Math.floor(v); } }
javascript
function toInteger(val) { var v = +val;// toNumber conversion if(isNaN(v)) { return 0; } if(v === 0 || v === Infinity || v == -Infinity) { return v; } if(v < 0) { return -1 * Math.floor(-v); } else { return Math.floor(v); } }
[ "function", "toInteger", "(", "val", ")", "{", "var", "v", "=", "+", "val", ";", "// toNumber conversion\r", "if", "(", "isNaN", "(", "v", ")", ")", "{", "return", "0", ";", "}", "if", "(", "v", "===", "0", "||", "v", "===", "Infinity", "||", "v", "==", "-", "Infinity", ")", "{", "return", "v", ";", "}", "if", "(", "v", "<", "0", ")", "{", "return", "-", "1", "*", "Math", ".", "floor", "(", "-", "v", ")", ";", "}", "else", "{", "return", "Math", ".", "floor", "(", "v", ")", ";", "}", "}" ]
ES5 9.2
[ "ES5", "9", ".", "2" ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L623-L637
40,979
hutkev/Shared
lib/shared.js
UnknownReference
function UnknownReference(id, prop, missing) { this._id = id; this._prop = prop; this._missing = missing; }
javascript
function UnknownReference(id, prop, missing) { this._id = id; this._prop = prop; this._missing = missing; }
[ "function", "UnknownReference", "(", "id", ",", "prop", ",", "missing", ")", "{", "this", ".", "_id", "=", "id", ";", "this", ".", "_prop", "=", "prop", ";", "this", ".", "_missing", "=", "missing", ";", "}" ]
Id of missing object
[ "Id", "of", "missing", "object" ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L1186-L1190
40,980
hutkev/Shared
lib/shared.js
function (obj, prop, value) { shared.utils.dassert(getTracker(obj) === this); this._lastTx = this.tc().addNew(obj, prop, value, this._lastTx); }
javascript
function (obj, prop, value) { shared.utils.dassert(getTracker(obj) === this); this._lastTx = this.tc().addNew(obj, prop, value, this._lastTx); }
[ "function", "(", "obj", ",", "prop", ",", "value", ")", "{", "shared", ".", "utils", ".", "dassert", "(", "getTracker", "(", "obj", ")", "===", "this", ")", ";", "this", ".", "_lastTx", "=", "this", ".", "tc", "(", ")", ".", "addNew", "(", "obj", ",", "prop", ",", "value", ",", "this", ".", "_lastTx", ")", ";", "}" ]
Change notification handlers called to record changes
[ "Change", "notification", "handlers", "called", "to", "record", "changes" ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L1377-L1380
40,981
hutkev/Shared
lib/shared.js
function (obj) { shared.utils.dassert(getTracker(obj) === this); this._rev += 1; this._type = shared.types.TypeStore.instance().type(obj); }
javascript
function (obj) { shared.utils.dassert(getTracker(obj) === this); this._rev += 1; this._type = shared.types.TypeStore.instance().type(obj); }
[ "function", "(", "obj", ")", "{", "shared", ".", "utils", ".", "dassert", "(", "getTracker", "(", "obj", ")", "===", "this", ")", ";", "this", ".", "_rev", "+=", "1", ";", "this", ".", "_type", "=", "shared", ".", "types", ".", "TypeStore", ".", "instance", "(", ")", ".", "type", "(", "obj", ")", ";", "}" ]
Uprev an object recording new properties
[ "Uprev", "an", "object", "recording", "new", "properties" ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L1434-L1438
40,982
hutkev/Shared
lib/shared.js
MongoStore
function MongoStore(options) { if (typeof options === "undefined") { options = { }; } _super.call(this); this._logger = shared.utils.defaultLogger(); // Database stuff this._collection = null; this._pending = []; // Outstanding work queue this._root = null; // Root object this._cache = new shared.mtx.ObjectCache(); this._host = options.host || 'localhost'; this._port = options.port || 27017; this._dbName = options.db || 'shared'; this._collectionName = options.collection || 'shared'; this._safe = options.safe || 'false'; this._logger.debug('STORE', '%s: Store created', this.id()); }
javascript
function MongoStore(options) { if (typeof options === "undefined") { options = { }; } _super.call(this); this._logger = shared.utils.defaultLogger(); // Database stuff this._collection = null; this._pending = []; // Outstanding work queue this._root = null; // Root object this._cache = new shared.mtx.ObjectCache(); this._host = options.host || 'localhost'; this._port = options.port || 27017; this._dbName = options.db || 'shared'; this._collectionName = options.collection || 'shared'; this._safe = options.safe || 'false'; this._logger.debug('STORE', '%s: Store created', this.id()); }
[ "function", "MongoStore", "(", "options", ")", "{", "if", "(", "typeof", "options", "===", "\"undefined\"", ")", "{", "options", "=", "{", "}", ";", "}", "_super", ".", "call", "(", "this", ")", ";", "this", ".", "_logger", "=", "shared", ".", "utils", ".", "defaultLogger", "(", ")", ";", "// Database stuff\r", "this", ".", "_collection", "=", "null", ";", "this", ".", "_pending", "=", "[", "]", ";", "// Outstanding work queue\r", "this", ".", "_root", "=", "null", ";", "// Root object\r", "this", ".", "_cache", "=", "new", "shared", ".", "mtx", ".", "ObjectCache", "(", ")", ";", "this", ".", "_host", "=", "options", ".", "host", "||", "'localhost'", ";", "this", ".", "_port", "=", "options", ".", "port", "||", "27017", ";", "this", ".", "_dbName", "=", "options", ".", "db", "||", "'shared'", ";", "this", ".", "_collectionName", "=", "options", ".", "collection", "||", "'shared'", ";", "this", ".", "_safe", "=", "options", ".", "safe", "||", "'false'", ";", "this", ".", "_logger", ".", "debug", "(", "'STORE'", ",", "'%s: Store created'", ",", "this", ".", "id", "(", ")", ")", ";", "}" ]
For checking for lock changes
[ "For", "checking", "for", "lock", "changes" ]
9fb63e54d16256c6b8fbac381e11adc4daea5dc6
https://github.com/hutkev/Shared/blob/9fb63e54d16256c6b8fbac381e11adc4daea5dc6/lib/shared.js#L2509-L2527
40,983
emiloberg/markdown-styleguide-generator
index.js
saveFile
function saveFile(html) { fs.outputFile(options.outputFile, html, function(err, data) { if (err) { console.log(error('ERROR!')); console.dir(err); process.exit(1); } console.log(good('\n\nAll done!')); console.log('Created file: ' + good(options.outputFile)); }); }
javascript
function saveFile(html) { fs.outputFile(options.outputFile, html, function(err, data) { if (err) { console.log(error('ERROR!')); console.dir(err); process.exit(1); } console.log(good('\n\nAll done!')); console.log('Created file: ' + good(options.outputFile)); }); }
[ "function", "saveFile", "(", "html", ")", "{", "fs", ".", "outputFile", "(", "options", ".", "outputFile", ",", "html", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "error", "(", "'ERROR!'", ")", ")", ";", "console", ".", "dir", "(", "err", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "console", ".", "log", "(", "good", "(", "'\\n\\nAll done!'", ")", ")", ";", "console", ".", "log", "(", "'Created file: '", "+", "good", "(", "options", ".", "outputFile", ")", ")", ";", "}", ")", ";", "}" ]
Save html to file @param html
[ "Save", "html", "to", "file" ]
7052f4185fba682c4e309faa78fd1a40ed2c010d
https://github.com/emiloberg/markdown-styleguide-generator/blob/7052f4185fba682c4e309faa78fd1a40ed2c010d/index.js#L213-L223
40,984
emiloberg/markdown-styleguide-generator
index.js
doTemplating
function doTemplating(json) { // Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre' highlightSource = highlightSource.replace('.hljs {', '#styleguide .hljs pre, .hljs {'); handlebars.registerPartial("jquery", '<script>\n' + jqSource+ '\n</script>'); handlebars.registerPartial("theme", '<style>\n' + themeSource + '\n</style>'); handlebars.registerPartial("highlight", '<style>\n' + highlightSource + '\n</style>'); var template = handlebars.compile(templateSource); return template(json); }
javascript
function doTemplating(json) { // Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre' highlightSource = highlightSource.replace('.hljs {', '#styleguide .hljs pre, .hljs {'); handlebars.registerPartial("jquery", '<script>\n' + jqSource+ '\n</script>'); handlebars.registerPartial("theme", '<style>\n' + themeSource + '\n</style>'); handlebars.registerPartial("highlight", '<style>\n' + highlightSource + '\n</style>'); var template = handlebars.compile(templateSource); return template(json); }
[ "function", "doTemplating", "(", "json", ")", "{", "// Adding '#styleguide .hljs pre' to highlight css, to override common used styling for 'pre'", "highlightSource", "=", "highlightSource", ".", "replace", "(", "'.hljs {'", ",", "'#styleguide .hljs pre, .hljs {'", ")", ";", "handlebars", ".", "registerPartial", "(", "\"jquery\"", ",", "'<script>\\n'", "+", "jqSource", "+", "'\\n</script>'", ")", ";", "handlebars", ".", "registerPartial", "(", "\"theme\"", ",", "'<style>\\n'", "+", "themeSource", "+", "'\\n</style>'", ")", ";", "handlebars", ".", "registerPartial", "(", "\"highlight\"", ",", "'<style>\\n'", "+", "highlightSource", "+", "'\\n</style>'", ")", ";", "var", "template", "=", "handlebars", ".", "compile", "(", "templateSource", ")", ";", "return", "template", "(", "json", ")", ";", "}" ]
Run through Handlebars to create HTML @param {object} json @returns {string} html
[ "Run", "through", "Handlebars", "to", "create", "HTML" ]
7052f4185fba682c4e309faa78fd1a40ed2c010d
https://github.com/emiloberg/markdown-styleguide-generator/blob/7052f4185fba682c4e309faa78fd1a40ed2c010d/index.js#L231-L241
40,985
roccivic/cron-converter
src/seeker.js
Seeker
function Seeker(cron, now) { if (cron.parts === null) { throw new Error('No schedule found'); } var date; if (cron.options.timezone) { date = moment.tz(now, cron.options.timezone); } else { date = moment(now); } if (!date.isValid()) { throw new Error('Invalid date provided'); } if (date.seconds() > 0) { // Add a minute to the date to prevent returning dates in the past date.add(1, 'minute'); } this.cron = cron; this.now = date; this.date = date; this.pristine = true; }
javascript
function Seeker(cron, now) { if (cron.parts === null) { throw new Error('No schedule found'); } var date; if (cron.options.timezone) { date = moment.tz(now, cron.options.timezone); } else { date = moment(now); } if (!date.isValid()) { throw new Error('Invalid date provided'); } if (date.seconds() > 0) { // Add a minute to the date to prevent returning dates in the past date.add(1, 'minute'); } this.cron = cron; this.now = date; this.date = date; this.pristine = true; }
[ "function", "Seeker", "(", "cron", ",", "now", ")", "{", "if", "(", "cron", ".", "parts", "===", "null", ")", "{", "throw", "new", "Error", "(", "'No schedule found'", ")", ";", "}", "var", "date", ";", "if", "(", "cron", ".", "options", ".", "timezone", ")", "{", "date", "=", "moment", ".", "tz", "(", "now", ",", "cron", ".", "options", ".", "timezone", ")", ";", "}", "else", "{", "date", "=", "moment", "(", "now", ")", ";", "}", "if", "(", "!", "date", ".", "isValid", "(", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid date provided'", ")", ";", "}", "if", "(", "date", ".", "seconds", "(", ")", ">", "0", ")", "{", "// Add a minute to the date to prevent returning dates in the past", "date", ".", "add", "(", "1", ",", "'minute'", ")", ";", "}", "this", ".", "cron", "=", "cron", ";", "this", ".", "now", "=", "date", ";", "this", ".", "date", "=", "date", ";", "this", ".", "pristine", "=", "true", ";", "}" ]
Creates an instance of Seeker. Seeker objects search for execution times of a cron schedule. @constructor @this {Seeker}
[ "Creates", "an", "instance", "of", "Seeker", ".", "Seeker", "objects", "search", "for", "execution", "times", "of", "a", "cron", "schedule", "." ]
ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9
https://github.com/roccivic/cron-converter/blob/ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9/src/seeker.js#L12-L33
40,986
roccivic/cron-converter
src/seeker.js
function(parts, date, reverse) { var operation = 'add'; var reset = 'startOf'; if (reverse) { operation = 'subtract'; reset = 'endOf'; date.subtract(1, 'minute'); // Ensure prev and next cannot be same time } var retry = 24; while (--retry) { shiftMonth(parts, date, operation, reset); var monthChanged = shiftDay(parts, date, operation, reset); if (!monthChanged) { var dayChanged = shiftHour(parts, date, operation, reset); if (!dayChanged) { var hourChanged = shiftMinute(parts, date, operation, reset); if (!hourChanged) { break; } } } } if (!retry) { throw new Error('Unable to find execution time for schedule'); } date.seconds(0).milliseconds(0); // Return new moment object return moment(date); }
javascript
function(parts, date, reverse) { var operation = 'add'; var reset = 'startOf'; if (reverse) { operation = 'subtract'; reset = 'endOf'; date.subtract(1, 'minute'); // Ensure prev and next cannot be same time } var retry = 24; while (--retry) { shiftMonth(parts, date, operation, reset); var monthChanged = shiftDay(parts, date, operation, reset); if (!monthChanged) { var dayChanged = shiftHour(parts, date, operation, reset); if (!dayChanged) { var hourChanged = shiftMinute(parts, date, operation, reset); if (!hourChanged) { break; } } } } if (!retry) { throw new Error('Unable to find execution time for schedule'); } date.seconds(0).milliseconds(0); // Return new moment object return moment(date); }
[ "function", "(", "parts", ",", "date", ",", "reverse", ")", "{", "var", "operation", "=", "'add'", ";", "var", "reset", "=", "'startOf'", ";", "if", "(", "reverse", ")", "{", "operation", "=", "'subtract'", ";", "reset", "=", "'endOf'", ";", "date", ".", "subtract", "(", "1", ",", "'minute'", ")", ";", "// Ensure prev and next cannot be same time", "}", "var", "retry", "=", "24", ";", "while", "(", "--", "retry", ")", "{", "shiftMonth", "(", "parts", ",", "date", ",", "operation", ",", "reset", ")", ";", "var", "monthChanged", "=", "shiftDay", "(", "parts", ",", "date", ",", "operation", ",", "reset", ")", ";", "if", "(", "!", "monthChanged", ")", "{", "var", "dayChanged", "=", "shiftHour", "(", "parts", ",", "date", ",", "operation", ",", "reset", ")", ";", "if", "(", "!", "dayChanged", ")", "{", "var", "hourChanged", "=", "shiftMinute", "(", "parts", ",", "date", ",", "operation", ",", "reset", ")", ";", "if", "(", "!", "hourChanged", ")", "{", "break", ";", "}", "}", "}", "}", "if", "(", "!", "retry", ")", "{", "throw", "new", "Error", "(", "'Unable to find execution time for schedule'", ")", ";", "}", "date", ".", "seconds", "(", "0", ")", ".", "milliseconds", "(", "0", ")", ";", "// Return new moment object", "return", "moment", "(", "date", ")", ";", "}" ]
Returns the time the schedule would run next. @param {array} parts An array of Cron parts. @param {Date} date The reference date. @param {boolean} reverse Whether to find the previous value instead of next. @return {Moment} The date the schedule would have executed at.
[ "Returns", "the", "time", "the", "schedule", "would", "run", "next", "." ]
ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9
https://github.com/roccivic/cron-converter/blob/ebfae6a2f5cf3fd621af1ad1e34dfbe4ee6f7df9/src/seeker.js#L79-L107
40,987
cubehouse/PSNjs
psn_request.js
DebugLog
function DebugLog(msg) { console.log("[PSN] :: " + ((typeof msg == "object") ? JSON.stringify(msg, null, 2) : msg)); }
javascript
function DebugLog(msg) { console.log("[PSN] :: " + ((typeof msg == "object") ? JSON.stringify(msg, null, 2) : msg)); }
[ "function", "DebugLog", "(", "msg", ")", "{", "console", ".", "log", "(", "\"[PSN] :: \"", "+", "(", "(", "typeof", "msg", "==", "\"object\"", ")", "?", "JSON", ".", "stringify", "(", "msg", ",", "null", ",", "2", ")", ":", "msg", ")", ")", ";", "}" ]
In-Build logger
[ "In", "-", "Build", "logger" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L100-L103
40,988
cubehouse/PSNjs
psn_request.js
GetHeaders
function GetHeaders(additional_headers) { var ret_headers = {}; // clone default headers into our return object (parsed) for(var key in headers) { ret_headers[key] = ParseStaches(headers[key]); } // add accept-language header based on our language ret_headers['Accept-Language'] = auth_obj.npLanguage + "," + languages.join(','); // add access token (if we have one) if (auth_obj.access_token) { ret_headers['Authorization'] = 'Bearer ' + auth_obj.access_token; } // add additional headers (if supplied) (parsed) if (additional_headers) for(var key in additional_headers) { ret_headers[key] = ParseStaches(additional_headers[key]); } return ret_headers; }
javascript
function GetHeaders(additional_headers) { var ret_headers = {}; // clone default headers into our return object (parsed) for(var key in headers) { ret_headers[key] = ParseStaches(headers[key]); } // add accept-language header based on our language ret_headers['Accept-Language'] = auth_obj.npLanguage + "," + languages.join(','); // add access token (if we have one) if (auth_obj.access_token) { ret_headers['Authorization'] = 'Bearer ' + auth_obj.access_token; } // add additional headers (if supplied) (parsed) if (additional_headers) for(var key in additional_headers) { ret_headers[key] = ParseStaches(additional_headers[key]); } return ret_headers; }
[ "function", "GetHeaders", "(", "additional_headers", ")", "{", "var", "ret_headers", "=", "{", "}", ";", "// clone default headers into our return object (parsed)", "for", "(", "var", "key", "in", "headers", ")", "{", "ret_headers", "[", "key", "]", "=", "ParseStaches", "(", "headers", "[", "key", "]", ")", ";", "}", "// add accept-language header based on our language", "ret_headers", "[", "'Accept-Language'", "]", "=", "auth_obj", ".", "npLanguage", "+", "\",\"", "+", "languages", ".", "join", "(", "','", ")", ";", "// add access token (if we have one)", "if", "(", "auth_obj", ".", "access_token", ")", "{", "ret_headers", "[", "'Authorization'", "]", "=", "'Bearer '", "+", "auth_obj", ".", "access_token", ";", "}", "// add additional headers (if supplied) (parsed)", "if", "(", "additional_headers", ")", "for", "(", "var", "key", "in", "additional_headers", ")", "{", "ret_headers", "[", "key", "]", "=", "ParseStaches", "(", "additional_headers", "[", "key", "]", ")", ";", "}", "return", "ret_headers", ";", "}" ]
Generate headers for a PSN request
[ "Generate", "headers", "for", "a", "PSN", "request" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L207-L232
40,989
cubehouse/PSNjs
psn_request.js
GetOAuthData
function GetOAuthData(additional_fields) { var ret_fields = {}; // clone base oauth settings for(var key in oauth_settings) { ret_fields[key] = ParseStaches(oauth_settings[key]); } // add additional fields (if supplied) if (additional_fields) for(var key in additional_fields) { ret_fields[key] = ParseStaches(additional_fields[key]); } return ret_fields; }
javascript
function GetOAuthData(additional_fields) { var ret_fields = {}; // clone base oauth settings for(var key in oauth_settings) { ret_fields[key] = ParseStaches(oauth_settings[key]); } // add additional fields (if supplied) if (additional_fields) for(var key in additional_fields) { ret_fields[key] = ParseStaches(additional_fields[key]); } return ret_fields; }
[ "function", "GetOAuthData", "(", "additional_fields", ")", "{", "var", "ret_fields", "=", "{", "}", ";", "// clone base oauth settings", "for", "(", "var", "key", "in", "oauth_settings", ")", "{", "ret_fields", "[", "key", "]", "=", "ParseStaches", "(", "oauth_settings", "[", "key", "]", ")", ";", "}", "// add additional fields (if supplied)", "if", "(", "additional_fields", ")", "for", "(", "var", "key", "in", "additional_fields", ")", "{", "ret_fields", "[", "key", "]", "=", "ParseStaches", "(", "additional_fields", "[", "key", "]", ")", ";", "}", "return", "ret_fields", ";", "}" ]
Get OAuth data
[ "Get", "OAuth", "data" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L235-L251
40,990
cubehouse/PSNjs
psn_request.js
URLGET
function URLGET(url, fields, method, callback) { // method variable is optional if (typeof method == "function") { callback = method; method = "GET"; } _URLGET(url, fields, GetHeaders({"Access-Control-Request-Method": method}), method, function(err, body) { if (err) { // got error, bounce it up if (callback) callback(err); return; } else { var JSONBody; if (typeof body == "object") { // already a JSON object? JSONBody = body; } else { // try to parse JSON body if (!body || !/\S/.test(body)) { // string is empty, return empty object if (callback) callback(false, {}); return; } else { try { JSONBody = JSON.parse(body); } catch(parse_err) { // error parsing JSON result Log("Parse JSON error: " + parse_err + "\r\nURL:\r\n" + url + "\r\nBody:\r\n" + body); if (callback) callback("Parse JSON error: " + parse_err); return; } } } // success! return JSON object if (callback) callback(false, JSONBody); } }); }
javascript
function URLGET(url, fields, method, callback) { // method variable is optional if (typeof method == "function") { callback = method; method = "GET"; } _URLGET(url, fields, GetHeaders({"Access-Control-Request-Method": method}), method, function(err, body) { if (err) { // got error, bounce it up if (callback) callback(err); return; } else { var JSONBody; if (typeof body == "object") { // already a JSON object? JSONBody = body; } else { // try to parse JSON body if (!body || !/\S/.test(body)) { // string is empty, return empty object if (callback) callback(false, {}); return; } else { try { JSONBody = JSON.parse(body); } catch(parse_err) { // error parsing JSON result Log("Parse JSON error: " + parse_err + "\r\nURL:\r\n" + url + "\r\nBody:\r\n" + body); if (callback) callback("Parse JSON error: " + parse_err); return; } } } // success! return JSON object if (callback) callback(false, JSONBody); } }); }
[ "function", "URLGET", "(", "url", ",", "fields", ",", "method", ",", "callback", ")", "{", "// method variable is optional", "if", "(", "typeof", "method", "==", "\"function\"", ")", "{", "callback", "=", "method", ";", "method", "=", "\"GET\"", ";", "}", "_URLGET", "(", "url", ",", "fields", ",", "GetHeaders", "(", "{", "\"Access-Control-Request-Method\"", ":", "method", "}", ")", ",", "method", ",", "function", "(", "err", ",", "body", ")", "{", "if", "(", "err", ")", "{", "// got error, bounce it up", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "else", "{", "var", "JSONBody", ";", "if", "(", "typeof", "body", "==", "\"object\"", ")", "{", "// already a JSON object?", "JSONBody", "=", "body", ";", "}", "else", "{", "// try to parse JSON body", "if", "(", "!", "body", "||", "!", "/", "\\S", "/", ".", "test", "(", "body", ")", ")", "{", "// string is empty, return empty object", "if", "(", "callback", ")", "callback", "(", "false", ",", "{", "}", ")", ";", "return", ";", "}", "else", "{", "try", "{", "JSONBody", "=", "JSON", ".", "parse", "(", "body", ")", ";", "}", "catch", "(", "parse_err", ")", "{", "// error parsing JSON result", "Log", "(", "\"Parse JSON error: \"", "+", "parse_err", "+", "\"\\r\\nURL:\\r\\n\"", "+", "url", "+", "\"\\r\\nBody:\\r\\n\"", "+", "body", ")", ";", "if", "(", "callback", ")", "callback", "(", "\"Parse JSON error: \"", "+", "parse_err", ")", ";", "return", ";", "}", "}", "}", "// success! return JSON object", "if", "(", "callback", ")", "callback", "(", "false", ",", "JSONBody", ")", ";", "}", "}", ")", ";", "}" ]
Make a PSN GET request
[ "Make", "a", "PSN", "GET", "request" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L254-L307
40,991
cubehouse/PSNjs
psn_request.js
Login
function Login(callback) { Log("Making OAuth Request..."); // start OAuth request (use our internal GET function as this is different!) _URLGET( // URL urls.login_base + "/2.0/oauth/authorize", // query string GetOAuthData({ response_type: "code", service_entity: "urn:service-entity:psn", returnAuthCode: true, state: "1156936032" }), // headers { 'User-Agent': ParseStaches(useragent) }, function(err, body, response) { if (err) { // return login error if (callback) callback(err); return; } else { // get the login path var login_referrer = response.req.path; Log("Logging in..."); // now actually login using the previous URL as the referrer request( { url: urls.login_base + "/login.do", method: "POST", headers: { 'User-Agent': ParseStaches(useragent), 'X-Requested-With': headers["X-Requested-With"], 'Origin': 'https://auth.api.sonyentertainmentnetwork.com', 'Referer': login_referrer, }, form: { 'params': new Buffer(login_params).toString('base64'), 'j_username': login_details.email, 'j_password': login_details.password } }, function (err, response, body) { if (err) { // login failed Log("Failed to make login request"); if (callback) callback(err); return; } else { Log("Following login..."); request.get(response.headers.location, function (err, response, body) { if (!err) { // parse URL var result = url.parse(response.req.path, true); if (result.query.authentication_error) { // try to extract login error from website var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body); if (error_message && error_message[1]) { Log("Login failed! Error from Sony: " + error_message[1]); if (callback) callback(error_message[1]); } else { Log("Login failed!"); if (callback) callback("Login failed!"); } return; } else { // no auth error! var auth_result = url.parse(result.query.targetUrl, true); if (auth_result.query.authCode) { Log("Got auth code: " + auth_result.query.authCode); auth_obj.auth_code = auth_result.query.authCode; if (callback) callback(false); return; } else { Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description); if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description); return; } } } else { Log("Auth code fetch error: " + err); if (callback) callback(err); return; } }); } } ); } } ); }
javascript
function Login(callback) { Log("Making OAuth Request..."); // start OAuth request (use our internal GET function as this is different!) _URLGET( // URL urls.login_base + "/2.0/oauth/authorize", // query string GetOAuthData({ response_type: "code", service_entity: "urn:service-entity:psn", returnAuthCode: true, state: "1156936032" }), // headers { 'User-Agent': ParseStaches(useragent) }, function(err, body, response) { if (err) { // return login error if (callback) callback(err); return; } else { // get the login path var login_referrer = response.req.path; Log("Logging in..."); // now actually login using the previous URL as the referrer request( { url: urls.login_base + "/login.do", method: "POST", headers: { 'User-Agent': ParseStaches(useragent), 'X-Requested-With': headers["X-Requested-With"], 'Origin': 'https://auth.api.sonyentertainmentnetwork.com', 'Referer': login_referrer, }, form: { 'params': new Buffer(login_params).toString('base64'), 'j_username': login_details.email, 'j_password': login_details.password } }, function (err, response, body) { if (err) { // login failed Log("Failed to make login request"); if (callback) callback(err); return; } else { Log("Following login..."); request.get(response.headers.location, function (err, response, body) { if (!err) { // parse URL var result = url.parse(response.req.path, true); if (result.query.authentication_error) { // try to extract login error from website var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body); if (error_message && error_message[1]) { Log("Login failed! Error from Sony: " + error_message[1]); if (callback) callback(error_message[1]); } else { Log("Login failed!"); if (callback) callback("Login failed!"); } return; } else { // no auth error! var auth_result = url.parse(result.query.targetUrl, true); if (auth_result.query.authCode) { Log("Got auth code: " + auth_result.query.authCode); auth_obj.auth_code = auth_result.query.authCode; if (callback) callback(false); return; } else { Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description); if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description); return; } } } else { Log("Auth code fetch error: " + err); if (callback) callback(err); return; } }); } } ); } } ); }
[ "function", "Login", "(", "callback", ")", "{", "Log", "(", "\"Making OAuth Request...\"", ")", ";", "// start OAuth request (use our internal GET function as this is different!)", "_URLGET", "(", "// URL", "urls", ".", "login_base", "+", "\"/2.0/oauth/authorize\"", ",", "// query string", "GetOAuthData", "(", "{", "response_type", ":", "\"code\"", ",", "service_entity", ":", "\"urn:service-entity:psn\"", ",", "returnAuthCode", ":", "true", ",", "state", ":", "\"1156936032\"", "}", ")", ",", "// headers", "{", "'User-Agent'", ":", "ParseStaches", "(", "useragent", ")", "}", ",", "function", "(", "err", ",", "body", ",", "response", ")", "{", "if", "(", "err", ")", "{", "// return login error", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "else", "{", "// get the login path", "var", "login_referrer", "=", "response", ".", "req", ".", "path", ";", "Log", "(", "\"Logging in...\"", ")", ";", "// now actually login using the previous URL as the referrer", "request", "(", "{", "url", ":", "urls", ".", "login_base", "+", "\"/login.do\"", ",", "method", ":", "\"POST\"", ",", "headers", ":", "{", "'User-Agent'", ":", "ParseStaches", "(", "useragent", ")", ",", "'X-Requested-With'", ":", "headers", "[", "\"X-Requested-With\"", "]", ",", "'Origin'", ":", "'https://auth.api.sonyentertainmentnetwork.com'", ",", "'Referer'", ":", "login_referrer", ",", "}", ",", "form", ":", "{", "'params'", ":", "new", "Buffer", "(", "login_params", ")", ".", "toString", "(", "'base64'", ")", ",", "'j_username'", ":", "login_details", ".", "email", ",", "'j_password'", ":", "login_details", ".", "password", "}", "}", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "if", "(", "err", ")", "{", "// login failed", "Log", "(", "\"Failed to make login request\"", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "else", "{", "Log", "(", "\"Following login...\"", ")", ";", "request", ".", "get", "(", "response", ".", "headers", ".", "location", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "if", "(", "!", "err", ")", "{", "// parse URL", "var", "result", "=", "url", ".", "parse", "(", "response", ".", "req", ".", "path", ",", "true", ")", ";", "if", "(", "result", ".", "query", ".", "authentication_error", ")", "{", "// try to extract login error from website", "var", "error_message", "=", "/", "errorDivMessage\\\"\\>\\s*(.*)\\<br \\/\\>", "/", ".", "exec", "(", "body", ")", ";", "if", "(", "error_message", "&&", "error_message", "[", "1", "]", ")", "{", "Log", "(", "\"Login failed! Error from Sony: \"", "+", "error_message", "[", "1", "]", ")", ";", "if", "(", "callback", ")", "callback", "(", "error_message", "[", "1", "]", ")", ";", "}", "else", "{", "Log", "(", "\"Login failed!\"", ")", ";", "if", "(", "callback", ")", "callback", "(", "\"Login failed!\"", ")", ";", "}", "return", ";", "}", "else", "{", "// no auth error!", "var", "auth_result", "=", "url", ".", "parse", "(", "result", ".", "query", ".", "targetUrl", ",", "true", ")", ";", "if", "(", "auth_result", ".", "query", ".", "authCode", ")", "{", "Log", "(", "\"Got auth code: \"", "+", "auth_result", ".", "query", ".", "authCode", ")", ";", "auth_obj", ".", "auth_code", "=", "auth_result", ".", "query", ".", "authCode", ";", "if", "(", "callback", ")", "callback", "(", "false", ")", ";", "return", ";", "}", "else", "{", "Log", "(", "\"Auth error \"", "+", "auth_result", ".", "query", ".", "error_code", "+", "\": \"", "+", "auth_result", ".", "query", ".", "error_description", ")", ";", "if", "(", "callback", ")", "callback", "(", "\"Auth error \"", "+", "auth_result", ".", "query", ".", "error_code", "+", "\": \"", "+", "auth_result", ".", "query", ".", "error_description", ")", ";", "return", ";", "}", "}", "}", "else", "{", "Log", "(", "\"Auth code fetch error: \"", "+", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Login to app and get auth token
[ "Login", "to", "app", "and", "get", "auth", "token" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L424-L544
40,992
cubehouse/PSNjs
psn_request.js
GetAccessToken
function GetAccessToken(callback) { // do we have a refresh token? Or do we need to login from scratch? if (auth_obj.refresh_token) { // we have a refresh token! Log("Refreshing session..."); if (!auth_obj.refresh_token) { if (callback) callback("No refresh token found!"); return; } // request new access_token request.post( { url: urls.oauth, form: GetOAuthData({ "grant_type": "refresh_token", "refresh_token": auth_obj.refresh_token }) }, function(err, response, body) { _ParseTokenResponse(err, body, callback); } ); } else { // no refresh token, sign-in from scratch Log("Signing in with OAuth..."); // make sure we have an authcode if (!auth_obj.auth_code) { if (callback) callback("No authcode available for OAuth!"); return; } // request initial access_token request.post( { url: urls.oauth, form: GetOAuthData({ "grant_type": "authorization_code", "code": auth_obj.auth_code }) }, function(err, response, body) { _ParseTokenResponse(err, body, callback); } ); } }
javascript
function GetAccessToken(callback) { // do we have a refresh token? Or do we need to login from scratch? if (auth_obj.refresh_token) { // we have a refresh token! Log("Refreshing session..."); if (!auth_obj.refresh_token) { if (callback) callback("No refresh token found!"); return; } // request new access_token request.post( { url: urls.oauth, form: GetOAuthData({ "grant_type": "refresh_token", "refresh_token": auth_obj.refresh_token }) }, function(err, response, body) { _ParseTokenResponse(err, body, callback); } ); } else { // no refresh token, sign-in from scratch Log("Signing in with OAuth..."); // make sure we have an authcode if (!auth_obj.auth_code) { if (callback) callback("No authcode available for OAuth!"); return; } // request initial access_token request.post( { url: urls.oauth, form: GetOAuthData({ "grant_type": "authorization_code", "code": auth_obj.auth_code }) }, function(err, response, body) { _ParseTokenResponse(err, body, callback); } ); } }
[ "function", "GetAccessToken", "(", "callback", ")", "{", "// do we have a refresh token? Or do we need to login from scratch?", "if", "(", "auth_obj", ".", "refresh_token", ")", "{", "// we have a refresh token!", "Log", "(", "\"Refreshing session...\"", ")", ";", "if", "(", "!", "auth_obj", ".", "refresh_token", ")", "{", "if", "(", "callback", ")", "callback", "(", "\"No refresh token found!\"", ")", ";", "return", ";", "}", "// request new access_token", "request", ".", "post", "(", "{", "url", ":", "urls", ".", "oauth", ",", "form", ":", "GetOAuthData", "(", "{", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "auth_obj", ".", "refresh_token", "}", ")", "}", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "_ParseTokenResponse", "(", "err", ",", "body", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "{", "// no refresh token, sign-in from scratch", "Log", "(", "\"Signing in with OAuth...\"", ")", ";", "// make sure we have an authcode", "if", "(", "!", "auth_obj", ".", "auth_code", ")", "{", "if", "(", "callback", ")", "callback", "(", "\"No authcode available for OAuth!\"", ")", ";", "return", ";", "}", "// request initial access_token", "request", ".", "post", "(", "{", "url", ":", "urls", ".", "oauth", ",", "form", ":", "GetOAuthData", "(", "{", "\"grant_type\"", ":", "\"authorization_code\"", ",", "\"code\"", ":", "auth_obj", ".", "auth_code", "}", ")", "}", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "_ParseTokenResponse", "(", "err", ",", "body", ",", "callback", ")", ";", "}", ")", ";", "}", "}" ]
Get an access token using the PSN oauth service using our current auth config
[ "Get", "an", "access", "token", "using", "the", "PSN", "oauth", "service", "using", "our", "current", "auth", "config" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L547-L603
40,993
cubehouse/PSNjs
psn_request.js
GetUserData
function GetUserData(callback) { Log("Fetching user profile data"); // get the current user's data parent.Get("https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info", {}, function(error, data) { if (error) { Log("Error fetching user profile: " + error); if (callback) callback("Error fetching user profile: " + error); return; } if (!data.onlineId) { Log("Missing PSNId from profile result: " + JSON.stringify(data, null, 2)); if (callback) callback("Missing PSNId from profile result: " + JSON.stringify(data, null, 2)); return; } // store user ID Log("We're logged in as " + data.onlineId); auth_obj.username = data.onlineId; // store user's region too auth_obj.region = data.region; // save updated data object DoSave(function() { // return no error if (callback) callback(false); } ); // supply self to let API know we are a token fetch function }, GetUserData); }
javascript
function GetUserData(callback) { Log("Fetching user profile data"); // get the current user's data parent.Get("https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info", {}, function(error, data) { if (error) { Log("Error fetching user profile: " + error); if (callback) callback("Error fetching user profile: " + error); return; } if (!data.onlineId) { Log("Missing PSNId from profile result: " + JSON.stringify(data, null, 2)); if (callback) callback("Missing PSNId from profile result: " + JSON.stringify(data, null, 2)); return; } // store user ID Log("We're logged in as " + data.onlineId); auth_obj.username = data.onlineId; // store user's region too auth_obj.region = data.region; // save updated data object DoSave(function() { // return no error if (callback) callback(false); } ); // supply self to let API know we are a token fetch function }, GetUserData); }
[ "function", "GetUserData", "(", "callback", ")", "{", "Log", "(", "\"Fetching user profile data\"", ")", ";", "// get the current user's data", "parent", ".", "Get", "(", "\"https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info\"", ",", "{", "}", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "Log", "(", "\"Error fetching user profile: \"", "+", "error", ")", ";", "if", "(", "callback", ")", "callback", "(", "\"Error fetching user profile: \"", "+", "error", ")", ";", "return", ";", "}", "if", "(", "!", "data", ".", "onlineId", ")", "{", "Log", "(", "\"Missing PSNId from profile result: \"", "+", "JSON", ".", "stringify", "(", "data", ",", "null", ",", "2", ")", ")", ";", "if", "(", "callback", ")", "callback", "(", "\"Missing PSNId from profile result: \"", "+", "JSON", ".", "stringify", "(", "data", ",", "null", ",", "2", ")", ")", ";", "return", ";", "}", "// store user ID", "Log", "(", "\"We're logged in as \"", "+", "data", ".", "onlineId", ")", ";", "auth_obj", ".", "username", "=", "data", ".", "onlineId", ";", "// store user's region too", "auth_obj", ".", "region", "=", "data", ".", "region", ";", "// save updated data object", "DoSave", "(", "function", "(", ")", "{", "// return no error", "if", "(", "callback", ")", "callback", "(", "false", ")", ";", "}", ")", ";", "// supply self to let API know we are a token fetch function", "}", ",", "GetUserData", ")", ";", "}" ]
Fetch the user's profile data
[ "Fetch", "the", "user", "s", "profile", "data" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L698-L734
40,994
cubehouse/PSNjs
psn_request.js
CheckTokens
function CheckTokens(callback, token_fetch) { // build list of tokens we're missing var todo = []; // force token_fetch to an array token_fetch = [].concat(token_fetch); // make sure we're actually logged in first if (!auth_obj.auth_code) { Log("Need to login - no auth token found"); todo.push({name: "Login", func: Login}); } if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime()) { // token has expired! Fetch access_token again Log("Need to fetch access tokens - tokens expired"); todo.push({name: "GetAccessToken", func: GetAccessToken}); } else if (!auth_obj.access_token) { // we have no access token (?!) Log("Need to fetch access tokens - no token available"); todo.push({name: "GetAccessToken", func: GetAccessToken}); } if (!auth_obj.username || !auth_obj.region) { // missing player username/region Log("Need to fetch userdata - no region or username available"); todo.push({name: "GetUserData", func: GetUserData}); } if (todo.length == 0) { // everything is fine if (callback) callback(false); } else { // work through our list of tokens we need to update var step = function() { var func = todo.shift(); if (!func) { // all done! if (callback) callback(false); return; } if (token_fetch.indexOf(func.func) >= 0) { // if we're actually calling a token fetch function, skip! process.nextTick(step); } else { func.func(function(error) { if (error) { // token fetching error! if (callback) callback(func.name + " :: " + error); return; } // do next step process.nextTick(step); }); } }; // start updating tokens process.nextTick(step); } }
javascript
function CheckTokens(callback, token_fetch) { // build list of tokens we're missing var todo = []; // force token_fetch to an array token_fetch = [].concat(token_fetch); // make sure we're actually logged in first if (!auth_obj.auth_code) { Log("Need to login - no auth token found"); todo.push({name: "Login", func: Login}); } if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime()) { // token has expired! Fetch access_token again Log("Need to fetch access tokens - tokens expired"); todo.push({name: "GetAccessToken", func: GetAccessToken}); } else if (!auth_obj.access_token) { // we have no access token (?!) Log("Need to fetch access tokens - no token available"); todo.push({name: "GetAccessToken", func: GetAccessToken}); } if (!auth_obj.username || !auth_obj.region) { // missing player username/region Log("Need to fetch userdata - no region or username available"); todo.push({name: "GetUserData", func: GetUserData}); } if (todo.length == 0) { // everything is fine if (callback) callback(false); } else { // work through our list of tokens we need to update var step = function() { var func = todo.shift(); if (!func) { // all done! if (callback) callback(false); return; } if (token_fetch.indexOf(func.func) >= 0) { // if we're actually calling a token fetch function, skip! process.nextTick(step); } else { func.func(function(error) { if (error) { // token fetching error! if (callback) callback(func.name + " :: " + error); return; } // do next step process.nextTick(step); }); } }; // start updating tokens process.nextTick(step); } }
[ "function", "CheckTokens", "(", "callback", ",", "token_fetch", ")", "{", "// build list of tokens we're missing", "var", "todo", "=", "[", "]", ";", "// force token_fetch to an array", "token_fetch", "=", "[", "]", ".", "concat", "(", "token_fetch", ")", ";", "// make sure we're actually logged in first", "if", "(", "!", "auth_obj", ".", "auth_code", ")", "{", "Log", "(", "\"Need to login - no auth token found\"", ")", ";", "todo", ".", "push", "(", "{", "name", ":", "\"Login\"", ",", "func", ":", "Login", "}", ")", ";", "}", "if", "(", "!", "auth_obj", ".", "expire_time", "||", "auth_obj", ".", "expire_time", "<", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", "{", "// token has expired! Fetch access_token again", "Log", "(", "\"Need to fetch access tokens - tokens expired\"", ")", ";", "todo", ".", "push", "(", "{", "name", ":", "\"GetAccessToken\"", ",", "func", ":", "GetAccessToken", "}", ")", ";", "}", "else", "if", "(", "!", "auth_obj", ".", "access_token", ")", "{", "// we have no access token (?!)", "Log", "(", "\"Need to fetch access tokens - no token available\"", ")", ";", "todo", ".", "push", "(", "{", "name", ":", "\"GetAccessToken\"", ",", "func", ":", "GetAccessToken", "}", ")", ";", "}", "if", "(", "!", "auth_obj", ".", "username", "||", "!", "auth_obj", ".", "region", ")", "{", "// missing player username/region", "Log", "(", "\"Need to fetch userdata - no region or username available\"", ")", ";", "todo", ".", "push", "(", "{", "name", ":", "\"GetUserData\"", ",", "func", ":", "GetUserData", "}", ")", ";", "}", "if", "(", "todo", ".", "length", "==", "0", ")", "{", "// everything is fine", "if", "(", "callback", ")", "callback", "(", "false", ")", ";", "}", "else", "{", "// work through our list of tokens we need to update", "var", "step", "=", "function", "(", ")", "{", "var", "func", "=", "todo", ".", "shift", "(", ")", ";", "if", "(", "!", "func", ")", "{", "// all done!", "if", "(", "callback", ")", "callback", "(", "false", ")", ";", "return", ";", "}", "if", "(", "token_fetch", ".", "indexOf", "(", "func", ".", "func", ")", ">=", "0", ")", "{", "// if we're actually calling a token fetch function, skip!", "process", ".", "nextTick", "(", "step", ")", ";", "}", "else", "{", "func", ".", "func", "(", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "// token fetching error!", "if", "(", "callback", ")", "callback", "(", "func", ".", "name", "+", "\" :: \"", "+", "error", ")", ";", "return", ";", "}", "// do next step", "process", ".", "nextTick", "(", "step", ")", ";", "}", ")", ";", "}", "}", ";", "// start updating tokens", "process", ".", "nextTick", "(", "step", ")", ";", "}", "}" ]
Check the session's tokens are still valid! token_fetch var is the function calling the token check in cases where the function is actually already fetching tokens!
[ "Check", "the", "session", "s", "tokens", "are", "still", "valid!", "token_fetch", "var", "is", "the", "function", "calling", "the", "token", "check", "in", "cases", "where", "the", "function", "is", "actually", "already", "fetching", "tokens!" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L738-L815
40,995
cubehouse/PSNjs
psn_request.js
function() { var func = todo.shift(); if (!func) { // all done! if (callback) callback(false); return; } if (token_fetch.indexOf(func.func) >= 0) { // if we're actually calling a token fetch function, skip! process.nextTick(step); } else { func.func(function(error) { if (error) { // token fetching error! if (callback) callback(func.name + " :: " + error); return; } // do next step process.nextTick(step); }); } }
javascript
function() { var func = todo.shift(); if (!func) { // all done! if (callback) callback(false); return; } if (token_fetch.indexOf(func.func) >= 0) { // if we're actually calling a token fetch function, skip! process.nextTick(step); } else { func.func(function(error) { if (error) { // token fetching error! if (callback) callback(func.name + " :: " + error); return; } // do next step process.nextTick(step); }); } }
[ "function", "(", ")", "{", "var", "func", "=", "todo", ".", "shift", "(", ")", ";", "if", "(", "!", "func", ")", "{", "// all done!", "if", "(", "callback", ")", "callback", "(", "false", ")", ";", "return", ";", "}", "if", "(", "token_fetch", ".", "indexOf", "(", "func", ".", "func", ")", ">=", "0", ")", "{", "// if we're actually calling a token fetch function, skip!", "process", ".", "nextTick", "(", "step", ")", ";", "}", "else", "{", "func", ".", "func", "(", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "// token fetching error!", "if", "(", "callback", ")", "callback", "(", "func", ".", "name", "+", "\" :: \"", "+", "error", ")", ";", "return", ";", "}", "// do next step", "process", ".", "nextTick", "(", "step", ")", ";", "}", ")", ";", "}", "}" ]
work through our list of tokens we need to update
[ "work", "through", "our", "list", "of", "tokens", "we", "need", "to", "update" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L781-L810
40,996
cubehouse/PSNjs
psn_request.js
MakePSNRequest
function MakePSNRequest(method, url, fields, callback, token_fetch) { // use fields var as callback if it's missed out if (typeof fields == "function") { token_fetch = false; callback = fields; fields = {}; } else if (typeof method == "function") { token_fetch = false; callback = method; } // parse stache fields in fields list for(var field_key in fields) { fields[field_key] = ParseStaches(fields[field_key]); } CheckTokens(function(error) { // check our tokens are fine if (!error) { // make PSN GET request URLGET( // parse URL for region etc. ParseStaches(url), fields, method, function(error, data) { if (error) { Log("PSN " + method + " Error: " + error); if (callback) callback(error); return; } if (data.error && (data.error.code === 2105858 || data.error.code === 2138626)) { // access token has expired/failed/borked // login again! Log("Access token failure, try to login again."); Login(function(error) { if (error) { if (callback) callback(error); return; } // call ourselves parent.Get(url, fields, callback, token_fetch); }); } if (data.error && data.error.message) { // server error if (callback) callback(data.error.code + ": " + data.error.message, data.error); return; } // everything is fine! return data if (callback) callback(false, data); } ); } else { Log("Token error: " + error); if (callback) callback(error); return; } }, token_fetch); }
javascript
function MakePSNRequest(method, url, fields, callback, token_fetch) { // use fields var as callback if it's missed out if (typeof fields == "function") { token_fetch = false; callback = fields; fields = {}; } else if (typeof method == "function") { token_fetch = false; callback = method; } // parse stache fields in fields list for(var field_key in fields) { fields[field_key] = ParseStaches(fields[field_key]); } CheckTokens(function(error) { // check our tokens are fine if (!error) { // make PSN GET request URLGET( // parse URL for region etc. ParseStaches(url), fields, method, function(error, data) { if (error) { Log("PSN " + method + " Error: " + error); if (callback) callback(error); return; } if (data.error && (data.error.code === 2105858 || data.error.code === 2138626)) { // access token has expired/failed/borked // login again! Log("Access token failure, try to login again."); Login(function(error) { if (error) { if (callback) callback(error); return; } // call ourselves parent.Get(url, fields, callback, token_fetch); }); } if (data.error && data.error.message) { // server error if (callback) callback(data.error.code + ": " + data.error.message, data.error); return; } // everything is fine! return data if (callback) callback(false, data); } ); } else { Log("Token error: " + error); if (callback) callback(error); return; } }, token_fetch); }
[ "function", "MakePSNRequest", "(", "method", ",", "url", ",", "fields", ",", "callback", ",", "token_fetch", ")", "{", "// use fields var as callback if it's missed out", "if", "(", "typeof", "fields", "==", "\"function\"", ")", "{", "token_fetch", "=", "false", ";", "callback", "=", "fields", ";", "fields", "=", "{", "}", ";", "}", "else", "if", "(", "typeof", "method", "==", "\"function\"", ")", "{", "token_fetch", "=", "false", ";", "callback", "=", "method", ";", "}", "// parse stache fields in fields list", "for", "(", "var", "field_key", "in", "fields", ")", "{", "fields", "[", "field_key", "]", "=", "ParseStaches", "(", "fields", "[", "field_key", "]", ")", ";", "}", "CheckTokens", "(", "function", "(", "error", ")", "{", "// check our tokens are fine", "if", "(", "!", "error", ")", "{", "// make PSN GET request", "URLGET", "(", "// parse URL for region etc.", "ParseStaches", "(", "url", ")", ",", "fields", ",", "method", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "Log", "(", "\"PSN \"", "+", "method", "+", "\" Error: \"", "+", "error", ")", ";", "if", "(", "callback", ")", "callback", "(", "error", ")", ";", "return", ";", "}", "if", "(", "data", ".", "error", "&&", "(", "data", ".", "error", ".", "code", "===", "2105858", "||", "data", ".", "error", ".", "code", "===", "2138626", ")", ")", "{", "// access token has expired/failed/borked", "// login again!", "Log", "(", "\"Access token failure, try to login again.\"", ")", ";", "Login", "(", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "if", "(", "callback", ")", "callback", "(", "error", ")", ";", "return", ";", "}", "// call ourselves", "parent", ".", "Get", "(", "url", ",", "fields", ",", "callback", ",", "token_fetch", ")", ";", "}", ")", ";", "}", "if", "(", "data", ".", "error", "&&", "data", ".", "error", ".", "message", ")", "{", "// server error", "if", "(", "callback", ")", "callback", "(", "data", ".", "error", ".", "code", "+", "\": \"", "+", "data", ".", "error", ".", "message", ",", "data", ".", "error", ")", ";", "return", ";", "}", "// everything is fine! return data", "if", "(", "callback", ")", "callback", "(", "false", ",", "data", ")", ";", "}", ")", ";", "}", "else", "{", "Log", "(", "\"Token error: \"", "+", "error", ")", ";", "if", "(", "callback", ")", "callback", "(", "error", ")", ";", "return", ";", "}", "}", ",", "token_fetch", ")", ";", "}" ]
Make a PSN request
[ "Make", "a", "PSN", "request" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L819-L896
40,997
cubehouse/PSNjs
psn_request.js
Ready
function Ready() { if (options.autoconnect) { // make a connection request immediately (optional) parent.GetPSN(true, function() { if (options.onReady) options.onReady(); return; }); } else { // just callback that we're ready (if anyone is listening) if (options.onReady) options.onReady(); return; } }
javascript
function Ready() { if (options.autoconnect) { // make a connection request immediately (optional) parent.GetPSN(true, function() { if (options.onReady) options.onReady(); return; }); } else { // just callback that we're ready (if anyone is listening) if (options.onReady) options.onReady(); return; } }
[ "function", "Ready", "(", ")", "{", "if", "(", "options", ".", "autoconnect", ")", "{", "// make a connection request immediately (optional)", "parent", ".", "GetPSN", "(", "true", ",", "function", "(", ")", "{", "if", "(", "options", ".", "onReady", ")", "options", ".", "onReady", "(", ")", ";", "return", ";", "}", ")", ";", "}", "else", "{", "// just callback that we're ready (if anyone is listening)", "if", "(", "options", ".", "onReady", ")", "options", ".", "onReady", "(", ")", ";", "return", ";", "}", "}" ]
Called when we're all setup
[ "Called", "when", "we", "re", "all", "setup" ]
1da280d26e1c61f1237c8ed3b86ea3af48494769
https://github.com/cubehouse/PSNjs/blob/1da280d26e1c61f1237c8ed3b86ea3af48494769/psn_request.js#L944-L960
40,998
kchapelier/poisson-disk-sampling
src/poisson-disk-sampling.js
squaredEuclideanDistance
function squaredEuclideanDistance (point1, point2) { var result = 0, i = 0; for (; i < point1.length; i++) { result += Math.pow(point1[i] - point2[i], 2); } return result; }
javascript
function squaredEuclideanDistance (point1, point2) { var result = 0, i = 0; for (; i < point1.length; i++) { result += Math.pow(point1[i] - point2[i], 2); } return result; }
[ "function", "squaredEuclideanDistance", "(", "point1", ",", "point2", ")", "{", "var", "result", "=", "0", ",", "i", "=", "0", ";", "for", "(", ";", "i", "<", "point1", ".", "length", ";", "i", "++", ")", "{", "result", "+=", "Math", ".", "pow", "(", "point1", "[", "i", "]", "-", "point2", "[", "i", "]", ",", "2", ")", ";", "}", "return", "result", ";", "}" ]
Get the squared euclidean distance from two points of arbitrary, but equal, dimensions @param {Array} point1 @param {Array} point2 @returns {number} Squared euclidean distance
[ "Get", "the", "squared", "euclidean", "distance", "from", "two", "points", "of", "arbitrary", "but", "equal", "dimensions" ]
61246065acb2398bce9447370caa3926cf15989c
https://github.com/kchapelier/poisson-disk-sampling/blob/61246065acb2398bce9447370caa3926cf15989c/src/poisson-disk-sampling.js#L13-L22
40,999
kchapelier/poisson-disk-sampling
src/poisson-disk-sampling.js
getNeighbourhood
function getNeighbourhood (dimensionNumber) { var neighbourhood = moore(2, dimensionNumber), origin = [], dimension; for (dimension = 0; dimension < dimensionNumber; dimension++) { origin.push(0); } neighbourhood.push(origin); // sort by ascending distance to optimize proximity checks // see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008 // http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1 neighbourhood.sort(function (n1, n2) { var squareDist1 = 0, squareDist2 = 0; for (var dimension = 0; dimension < dimensionNumber; dimension++) { squareDist1 += Math.pow(n1[dimension], 2); squareDist2 += Math.pow(n2[dimension], 2); } if (squareDist1 < squareDist2) { return -1; } else if(squareDist1 > squareDist2) { return 1; } else { return 0; } }); return neighbourhood; }
javascript
function getNeighbourhood (dimensionNumber) { var neighbourhood = moore(2, dimensionNumber), origin = [], dimension; for (dimension = 0; dimension < dimensionNumber; dimension++) { origin.push(0); } neighbourhood.push(origin); // sort by ascending distance to optimize proximity checks // see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008 // http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1 neighbourhood.sort(function (n1, n2) { var squareDist1 = 0, squareDist2 = 0; for (var dimension = 0; dimension < dimensionNumber; dimension++) { squareDist1 += Math.pow(n1[dimension], 2); squareDist2 += Math.pow(n2[dimension], 2); } if (squareDist1 < squareDist2) { return -1; } else if(squareDist1 > squareDist2) { return 1; } else { return 0; } }); return neighbourhood; }
[ "function", "getNeighbourhood", "(", "dimensionNumber", ")", "{", "var", "neighbourhood", "=", "moore", "(", "2", ",", "dimensionNumber", ")", ",", "origin", "=", "[", "]", ",", "dimension", ";", "for", "(", "dimension", "=", "0", ";", "dimension", "<", "dimensionNumber", ";", "dimension", "++", ")", "{", "origin", ".", "push", "(", "0", ")", ";", "}", "neighbourhood", ".", "push", "(", "origin", ")", ";", "// sort by ascending distance to optimize proximity checks", "// see point 5.1 in Parallel Poisson Disk Sampling by Li-Yi Wei, 2008", "// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.460.3061&rank=1", "neighbourhood", ".", "sort", "(", "function", "(", "n1", ",", "n2", ")", "{", "var", "squareDist1", "=", "0", ",", "squareDist2", "=", "0", ";", "for", "(", "var", "dimension", "=", "0", ";", "dimension", "<", "dimensionNumber", ";", "dimension", "++", ")", "{", "squareDist1", "+=", "Math", ".", "pow", "(", "n1", "[", "dimension", "]", ",", "2", ")", ";", "squareDist2", "+=", "Math", ".", "pow", "(", "n2", "[", "dimension", "]", ",", "2", ")", ";", "}", "if", "(", "squareDist1", "<", "squareDist2", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "squareDist1", ">", "squareDist2", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}", ")", ";", "return", "neighbourhood", ";", "}" ]
Get the neighbourhood ordered by distance, including the origin point @param {int} dimensionNumber Number of dimensions @returns {Array} Neighbourhood
[ "Get", "the", "neighbourhood", "ordered", "by", "distance", "including", "the", "origin", "point" ]
61246065acb2398bce9447370caa3926cf15989c
https://github.com/kchapelier/poisson-disk-sampling/blob/61246065acb2398bce9447370caa3926cf15989c/src/poisson-disk-sampling.js#L29-L62